Implementing Google Contacts API Version 3.0 & OAuth 2.0 in CSharp and ASP.NET [Updated]

Implementing Google Contacts API Version 3.0 & OAuth 2.0 in CSharp and ASP.NET [Updated]

In this tutorial we will develop a web application to get all Google Contacts from a person account that authorizes the application. This will be made in asp.net platform and will use C# to communicate with Google Contacts API.

Another tutorial on Yahoo API explains how to pro-grammatically export your Yahoo Contacts.

To implement Google Contacts API first you have to create a project in Google APP console and create credentials for accessing it. The following 3 steps will explains this. Later we will use this project to communicate with our C# code.

STEP 1 – Create Project and Enable Google Contacts API

The first step is to create API Project in Google APP Console:

  • a. Visit https://console.developers.google.com/cloud-resource-manager.
  • b. Click ‘Create Project’ button. creating project in google console
  • c. Give your project some name and click the ‘Create’ Button. This will create your project. The project will be created after a few second. Refresh the page with F5 key and you will see your created project name there. new project in google console
  • d. Click on the project to reach the ‘IAM & Admin’ area. There click the Google APIs logo on the top left corner of the screen. This takes you to Google APIs Library page. click google apis logo
  • e. You will see all Google API there. Find Contacts API and click on it. google contacts api
  • f. Click the ‘Enable’ button to enable Google Contact API. Enable Google Contact API

STEP 2 – OAuth Consent Screen

On the same page (‘Google APIs Library’ page), click ‘Credentials’ link then click OAuth Consent Screen.

In this page add your ‘Product Name’ and click the ‘Save’ button.

oauth consent screen

STEP 3 – Create Credentials & Client ID

Next Google ask you to ‘Create Credentials’. Here click on the Create Credentials button (which will show some options on clicking). Select the option that says OAuth Client ID.

create credentials

Next it will ask to select the Application Type. Here select ‘Web Application’ and give name to your Application.

In the ‘Authorised redirect URIs’ field enter the URL where users will be redirected once authenticated with Google.

Finally click the ‘Create’ button.

create client id

Google will create the Application and give you the Client ID and Client Secret.

Save them securely, we will use them later in our application.

client id and client secret

Our Project in Google App Console is created. Next we have to communicate with it using C#. We will use OAuth 2.0 to authenticate users with this project.

Google OAuth 2.0 Working

OAuth 2.0 authenticates the users and asks for his permission for sharing contacts with the applicate. If a user grants his permission then Google sends ‘Authorization Code’ to the return URL in query string variable ‘code’.

I would also recommend you to learn What is OAuth because it forms the backbone of this Google Contacts API application.

Google OAuth 2.0 Structure

Google OAuth 2.0

See Google OAuth 2.0 online doc at – https://developers.google.com/accounts/docs/OAuth2WebServer.

Let us create our ASP.NET Web Application. This application we will communicate with our Google Project and gets all emails addresses of the user’s contacts from his Google account.

It will first ask for user’s consent to get all emails, and when the user allows it, only then the emails are shared.

I will explain you in Steps how you will code. So follow the steps as I have outlined below:

STEP 1 – Authenticate User with Google OAuth 2.0 and ask for Permission

  • a. Redirect user to URL: https://accounts.google.com/o/oauth2/auth.
  • b. Pass the following query string parameters with the URL:
    redirect_uri – given by you when creating New Client ID in step 3 given above.
    response_type – code
    client_id – your client id
    scope – https://www.google.com/m8/feeds/&approval_prompt=force&access_type=offline

I will redirect user on a Button Click Event so create a button and add the redirect code on its click event.

HTML

<asp:Button ID="googleButton" Text="Get Google Contacts" runat="server" 
OnClick="googleButton_Click" />

C#

protected void googleButton_Click(object sender, EventArgs e)
{
    string clientId = "ClientId";
    string redirectUrl = "http://www.demo.yogihosting.com/aspnet/
        google-contacts-api/index.aspx";
    Response.Redirect("https://accounts.google.com/o/oauth2/auth?
        redirect_uri="+redirectUrl+"&response_type=code
        &client_id=" + clientId + "&scope=
        https://www.google.com/m8/feeds/&approval_prompt=
        force&access_type=offline");
}

I have kept the redirect URL to the same page where the button is placed. It must be the same which we put in for Authorised redirect URIs when creating the Client ID.

Testing

Run the web page in your browser and click the button. Google will show the Consent Screen and ask you to grant permission to the Google Project which we created before.

Click the Allow Button and you will be redirect to the URL given by you.

consent screen

STEP 2 – Exchange Authorization Code to get Access Code

Here we have to make HTTP POST request to the URL: https://accounts.google.com/o/oauth2/token and must pass the following parameters with it –

  • a. code: authorization code.
  • b. client_id: client id of application.
  • c. client_secret: client secret of application.
  • d. redirect_url: One of the redirect URIs listed for this project.
  • e. grant_type: authorization_code.
A successful response will return the following things in JSON format –
  • a. access_token: the token from which Google API call can be made.
  • b. refresh_token: the token which is used to generate new Access Token when the current one expires.
  • c. expires_in: the life time of Access Token.
  • d. token_type: type of token returned, in our case it will be ‘bearer’.

The redirect URL will contain the Authorization Code in the query string parameter (code) so we put a check in Page_Load event:

protected void Page_Load(object sender, EventArgs e)
{
    if (Request.QueryString["code"] != null)
        GetAccessToken();
}

It will call GetAccessToken() function which will get the Access and Refresh Tokens.

public void GetAccessToken()
{
    string code = Request.QueryString["code"];
    string google_client_id = "ClientId";
    string google_client_sceret = "ClientSecret";
    string google_redirect_url = "http://www.demo.yogihosting.com/aspnet/
      Google-Contacts-API/index.aspx";

    /*Get Access Token and Refresh Token*/
    HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create
      ("https://accounts.google.com/o/oauth2/token");
    webRequest.Method = "POST";
    string parameters = "code=" + code + "&client_id=" + google_client_id + 
      "&client_secret=" + google_client_sceret + "&redirect_uri=" 
      + google_redirect_url + "&grant_type=authorization_code";
    byte[] byteArray = Encoding.UTF8.GetBytes(parameters);
    webRequest.ContentType = "application/x-www-form-urlencoded";
    webRequest.ContentLength = byteArray.Length;
    Stream postStream = webRequest.GetRequestStream();

    // Add the post data to the web request
    postStream.Write(byteArray, 0, byteArray.Length);
    postStream.Close();
    WebResponse response = webRequest.GetResponse();
    postStream = response.GetResponseStream();
    StreamReader reader = new StreamReader(postStream);
    string responseFromServer = reader.ReadToEnd();
    GooglePlusAccessToken serStatus = JsonConvert.DeserializeObject
      <GooglePlusAccessToken>(responseFromServer);
    /*End*/

    GetContacts(serStatus);
}}

Note the last couple of lines, I get response in JSON that also contains Access and Refresh tokens. So I used Json.NET to extract these values and put it inside GooglePlusAccessToken class like this.

GooglePlusAccessToken serStatus = JsonConvert.DeserializeObject
  <GooglePlusAccessToken>(responseFromServer);

The GooglePlusAccessToken class:

public class GooglePlusAccessToken
{
    public string access_token { get; set; }
    public string token_type { get; set; }
    public int expires_in { get; set; }
    public string refresh_token { get; set; }
}

In the end this function I call the GetContacts() function whose work is to make Google Contacts API call.

STEP 3 – Make Google API Calls with the Access Token to get Users Contacts

Add a div to the .aspx page.

<div id="dataDiv" runat="server"></div>

Please note that in this step we have used few Google dot net dlls for making the API call. It simplifies our approach. You will find this in the download code.

The URL to make API call is https://www.google.com/m8/feeds/contacts/{userEmail}/full Just pass ‘default’ for userEmail, ‘default’ refers the authenticated user.

The definition of GetContacts() function is:

public void GetContacts(GooglePlusAccessToken serStatus)
{
    /*Get Google Contacts From Access Token and Refresh Token*/
    string refreshToken = serStatus.refresh_token;
    string accessToken = serStatus.access_token;
    string scopes = "https://www.google.com/m8/feeds/contacts/
      default/full/";
    OAuth2Parameters oAuthparameters = new OAuth2Parameters()
    {
        Scope = scopes,
        AccessToken = accessToken,
        RefreshToken = refreshToken
    };

    RequestSettings settings = new RequestSettings
      ("<var>YOUR_APPLICATION_NAME</var>", oAuthparameters);
    ContactsRequest cr = new ContactsRequest(settings);
    ContactsQuery query = new ContactsQuery(ContactsQuery
      .CreateContactsUri("default"));
    query.NumberToRetrieve = 5000;
    Feed<Contact> feed = cr.Get<Contact>(query);

    StringBuilder sb = new StringBuilder();
    int i = 1;
    foreach (Contact entry in feed.Entries)
    {
        foreach (EMail email in entry.Emails)
        {
            sb.Append("<span>"+ i + ". </span>").Append(email.Address)
              .Append("<br/>");
            i++;
        }
    }
    /*End*/

    dataDiv.InnerHtml = sb.ToString();
}

The user contacts data is send in JSON format, we extract it and finally we loop through this data and show it in a div.

Testing

Now click the button and once you give your consent you will see all your contacts email in the div like shown below.

contacts email

Conclusion

This completes our Google Contacts API application. Hope you like it and we would like to have your comments below.

DEMO DOWNLOAD.

Share this article -

yogihosting

ABOUT THE AUTHOR

This article has been written by the Technical Staff of YogiHosting. Check out other articles on "WordPress, SEO, jQuery, HTML" and more.