Obtain email addresses from a Google account

I've encountered a challenge while creating a website for a client who requested the ability for users to sign up or log in using their Google and Facebook accounts. My current hurdle involves extracting the user's email address from their Google profile so that it can be stored in our database.

Below is the code snippet I have been working on. However, instead of retrieving the complete user profile, I am only able to obtain the username.

try
{
     WebClient client = new WebClient();
     var urlProfile = "https://www.googleapis.com/oauth2/v1/userinfo?access_token="
         + access_token;

     string outputData = client.DownloadString(urlProfile);

     GoogleUserOutputData serStatus =
         JsonConvert.DeserializeObject<GoogleUserOutputData>(outputData);

     if (serStatus != null)
     {
         return serStatus;
         // The user information will be available here.
     }
 }
 catch (Exception ex)
 {
     // Handling exceptions
 }

 return null;

Answer №1

If you're looking to gather data (such as email addresses) using JavaScript, I have a solution for you. This code snippet demonstrates how to receive and display data with an alert message at the end. You can also save this data into a database. It's a comprehensive example that includes a Google Sign-in button.

<html>

  <head>
    <title>Demo: Capture email address with Google+ Sign-in button</title>
    <!-- Import necessary API and client scripts for Google+. -->
    <script src = "https://plus.google.com/js/client:platform.js" async defer></script>
  </head>

  <body>
    <!-- Area containing the Google Sign-In button. -->
    <div id="gConnect" class="button">
      <button class="g-signin"
          data-scope="email"
          data-clientid="Your_Client_ID"
          data-callback="onSignInCallback"
          data-theme="dark"
          data-cookiepolicy="single_host_origin">
      </button>
      <!-- Text area to display output data -->
      <div id="response" class="hide">
        <textarea id="responseContainer" style="width:100%; height:150px"></textarea>
      </div>
    </div>
 </body>

  <script>
  /**
   * Function called after user signs in with Google.
   */
      function onSignInCallback(resp) {

    gapi.client.load('plus', 'v1', apiClientLoaded);
  }

  /**
   * Initiates an API call upon loading of Google API client.
   */
      function apiClientLoaded() {

    gapi.client.plus.people.get({userId: 'me'}).execute(handleEmailResponse);
  }

  /**
   * Callback function executed when API client receives a response.
   *
   * @param resp The API response object containing user email and profile information.
   */
  function handleEmailResponse(resp) {
      var primaryEmail;
      var name;
      var gender;

    for (var i=0; i < resp.emails.length; i++) {
        if (resp.emails[i].type === 'account')
            primaryEmail = resp.emails[i].value;
        if (resp.displayName != null)
            name = resp.displayName;
        gender = resp.gender;
    }
    document.getElementById('responseContainer').value = 'Primary email: ' +
          primaryEmail + '\n\nFull Response:\n' + JSON.stringify(resp);
      ShowAlert("Email: "+primaryEmail+" "+"Name: "+resp.displayName+" "+"Gender: "+gender);
  }

  </script>

</html>

For more detailed information and guidance, visit this link: Getting people and profile information

Answer №2

Exploring the documentation thoroughly is crucial for understanding.

Check out this link for more information

<meta name="google-signin-client_id" content="YOUR_CLIENT_ID.apps.googleusercontent.com">
<div class="g-signin2" data-onsuccess="onSignIn"></div>
function onSignIn(googleUser) {
  var profile = googleUser.getBasicProfile();
  console.log('ID: ' + profile.getId()); // Remember not to send sensitive information to your backend!
  console.log('Name: ' + profile.getName());
  console.log('Image URL: ' + profile.getImageUrl());
  console.log('Email: ' + profile.getEmail()); // Note that this may be null without the 'email' scope.
}
<a href="#" onclick="signOut();">Sign out</a>

<script>
function signOut() {
    var auth2 = gapi.auth2.getAuthInstance();
    auth2.signOut().then(function () {
      console.log('User signed out.');
    });
  }
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the Process of Loading and Storing Objects in C# Using JSON

Segment struggling with const string _studentRepositoryPath = @"students.json"; static void Save() { using (var file = File.CreateText(_studentRepositoryPath)) { file.WriteAsync(JsonSerializer.Serialize(studentsLi ...

What causes an ajax request to submit "none" as the value of a dom element?

Seeking assistance! I've encountered a frustrating issue with my simple input box in a form. I am attempting to send the value from this input box to Django using Ajax post, but keep encountering a 500 error that reads ValueError at /rest/ Cannot use ...

Guide on modifying the value of a web element attribute in C# with the help of Selenium

Topic Example: <input type="text" id="cargo_q" autocomplete="off" value="5.5"/> What is a way to modify the value of the "value" attribute using Selenium web driver? Can I use a method like: IWebElement search_cargo =driver.FindElement(By.Id("car ...

Can you explain the key distinctions among Highland.js, Kefir.js, and Rx.js?

Given the emphasis on objective answers on SO, my inquiry is focused on understanding the distinct functional and performance characteristics of these three functional/reactive libraries. This knowledge will guide me in selecting the most suitable option ...

C# Audio Visualizer: Enhancing Your Sounds With Visual

I am currently developing an audio visualizer using C#/Asp.net/JavaScript for a website. To ensure that my animations move smoothly in sync with the music, I have decided to preprocess the MP3 file within the code backend. I plan to write the values and fr ...

Enhance hover effects with JQuery through dynamic mouse movements

$(document).ready(function() { $(".hoverimage").hover( function(e) { updateCoords(this,e); openQuicktip(this); }, function() { closeQuicktip(); } ); $("area").hover( function(e) { updateCoords(this,e); openQuicktip(this); }, function ...

Tips for displaying a popup modal when a link is clicked with ajax technology

I am facing an issue with my popup modal. When a user clicks on a link, the modal appears but without any content. I am new to ajax and feeling a bit confused about what steps to take next. Below is the HTML code snippet: <div class="modal fade&quo ...

I am puzzled by the fact that my data is showing as undefined even though I have logged it to the console in

I am currently working on an app using React for the frontend and Node.js for the backend, which connects to a cloud-based MongoDB instance. Although I can successfully retrieve data from the database and see it logged in the console, the returned result i ...

Clicking while holding down the control key in Chrome causes the frame on my website to

My website consists of two frames - the main menu on the left and the content displayed on the right. However, I have noticed that when users use control+click in Chrome to open a new tab, the iframe page is displayed without the menu. Is there a way for ...

Unraveling the mysteries of deciphering extended JSON information

Issue with Data Interpretation I am facing a challenge in my project that is more related to understanding and interpreting data rather than writing code. The project involves using a NoSQL database, specifically MongoDB, to store information sampled from ...

Implementing an infinite scrolling feature using Javascript within a specified div element

I'm currently working on implementing an infinite loading feature using JavaScript. I came across this helpful resource that explains how to achieve infinite scrolling without jQuery: How to do infinite scrolling with javascript only without jquery A ...

Aggregator of Events for ASP.NET

My Requirements I am seeking a way for our standard in-house product to trigger various events when specific actions occur. I would like to be able to connect to these events in different custom solutions using the global asax file and respond accordingly ...

Unable to extract data using Regex

Script if(x.substr(0,4)=='init') { output += 'Initialized<br>'; var rgx = /^\[typ-$\]/i; if (rgx.test(x))output+='Type identified<br>'; else output+='No type detected: ' ...

Exploring the Differences in 3D Coordinates Within a Given Tolerance

Imagine having two sets of Coordinate Lists (in the form of double-triplets) let pointA = new List<(double x, double y, double z)>() {(10,10,10), (15,15,15)}; along with a collection of real-world coordinates, such as let points = new ...

Is there a way to determine if a chosen date and time are prior or subsequent to the current date and time in an AngularJS environment?

When using a datepicker and timepicker, I have obtained a selected date and time. Now, I need to determine if this selected date and time is before or after the current date and time. For example, if the selected date is "Sat Dec 12 2015" and the selected ...

Revolutionize your rotation axis with Axis in three.js

Greetings! I am currently working with three.js and I am attempting to rotate my 3D model along the x-axis. However, when I use the following code: object.rotation.x += 0.01;, it does not produce the desired effect. The image below depicts the current ro ...

Deploying: only publish newly generated files and exclude any previously generated files that are no longer present

After checking out this discussion regarding setting Build Action for an entire folder in Visual Studio, I found a solution that worked for me. My webpack configuration generates hashed files in a Build folder which are then published. However, I encounter ...

What are some strategies for minimizing code repetition when implementing login functionality across various OAuth2 providers?

Currently, I am utilizing various node modules such as Node.js, Express, Passport, and Mongoose. When a user clicks on "sign in with provider", there are two scenarios to consider. Let's take an example of using GitHub Strategy: 1. If the user is al ...

Combining non-minified and minified JavaScript files using browserify: A step-by-step guide

I have received a minified bundle file and now I need to obtain a non-minified bundle alongside it in the same distribution folder. gulpfile.js 'use strict'; var gulp = require('gulp'), gulpLoad = require('gulp-loa ...

I encountered an issue when attempting to upload an image in Windows OS using Adonis JS. Seeking a solution to overcome this obstacle

EIO: I/O error, copyfile 'C:\Users\user\AppData\Local\Temp\ab-4da7f2e2-3f04-4c93-a453-0a71e1304435.tmp' -> 'F:\nipu\eCommerce\public\images\books\1575106014388.jpeg' Check ...