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 app to get all Google contacts from a person account that authorizes the app. We will develop our app in asp.net platform and will use C# to communicate with Google Contacts API. Follow the steps as outlined in this tutorial.

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

STEP 1 – Create Project and give it API Permissions

The first thing to do here is to create our API Project in Google APP Console

  • a. Visit https://console.developers.google.com/project.
  • b. Click ‘Create Project’ button.
  • c. Give your project some name and check the ‘Terms of Service’ checkbox.
  • d. Click ‘Create’ button to create your project. The project will create and you will be taken to ‘Project Dashboard’ page.
  • e. On the left sidebar of the page, under ‘APIs & auth’ click on ‘APIs’.
  • f. You will see list of all Google API. Find ‘Contacts API’ and press the ‘OFF’ button against it to turn it on.
Creating Project In Google Console

Creating Project In Google Console

 

New Project In Google Console

New Project In Google Console

 

Turning On The Google Contacts API

Turning On The Google Contacts API

 

Google API In Google Console

Google API In Google Console

STEP 2 – Manage Consent Screen and Create New Client ID

On the left sidebar click ‘Consent Screen’ under ‘APIs & auth’. In the screen that opens enter email address and product name. You can also provide other optional parameters there, finally click save button.

Now on the left sidebar again, click on ‘Credentials’ (just over ‘Consent Screen’). Then click ‘Create new Client ID’. A new screen opens, here select ‘Web application’ for ‘Application Type’ and enter the ‘Authorized Redirect URI’ path (which is the URL the person is taken to, when he gives his permission to the app). Finally click ‘Create Client ID’ button. This will create Client ID and Client Secret. Save the client id and client secret as we will use them again in the steps to come.

Consent Screen In Google Developers Console

Consent Screen In Google Developers Console

 

Consent Screen Fields

Consent Screen Fields

 

Setting Credentials

Setting Credentials

 

Creating New Client ID

Creating New Client ID

 

Create Client ID and Fields

Create Client ID and Fields

STEP 3 – Authenticate the user with OAuth 2.0 to get Authorization Code

OAuth 2.0 authenticates the user and asks for his permission for sharing contacts with the app. 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 Structure

Google OAuth 2.0

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

Implementation

  • a. Redirect user to URL – https://accounts.google.com/o/oauth2/auth.
  • b. Pass the following query string parameters with it-

    redirect_uri – given by you when creating New Client ID in step 2

    response_type – code

    client_id – your client id

    scope – https://www.google.com/m8/feeds/&approval_prompt=force&access_type=offline

We will do this in a button 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.yogihosting.com/TutorialCode/GoogleContactAPI/google-contact-api.aspx";
    Response.Redirect("https://accounts.google.com/o/oauth2/auth?redirect_uri="+redirectUrl+"&amp;response_type=code&amp;client_id=" + clientId + "&amp;scope=https://www.google.com/m8/feeds/&amp;approval_prompt=force&amp;access_type=offline");
}

STEP 4 – 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 we have to pass the following parameters with it –

  • a. code –authorization code.
  • b. client_id – client id of our app.
  • c. client_secret – client secret of our app.
  • 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’.

Implementation

The authorization code we receive in query string parameter 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 whose definition is given below-

public void GetAccessToken()
{
    string code = Request.QueryString["code"];
    string google_client_id = "292511778773-nktorr50e1palg9svl49825uqfqv9q0a.apps.googleusercontent.com";
    string google_client_sceret = "sKuhzvMEN3-ye8BYWlP6hMm2";
    string google_redirect_url = "http://www.yogihosting.com/TutorialCode/GoogleContactAPI/google-contact-api.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 + "&amp;client_id=" + google_client_id + "&amp;client_secret=" + google_client_sceret + "&amp;redirect_uri=" + google_redirect_url + "&amp;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(responseFromServer);
    /*End*/

    GetContacts(serStatus);
}

In the end this function will call the GetContacts() function whose work is to make Google API Calls (as explained in Step 5)

With JsonConvert class we extract the response and put it in our 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; }
}

Step 5 – Make Google API Calls with the Access Token to get Users Contacts

Please note that in this step we have used few Google dot net dlls for making the API call. It simplifies our approach. 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)
{
    string google_client_id = "292511778773-nktorr50e1palg9svl49825uqfqv9q0a.apps.googleusercontent.com";
    string google_client_sceret = "sKuhzvMEN3-ye8BYWlP6hMm2";
    
    /*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()
    {
        ClientId = google_client_id,
        ClientSecret = google_client_sceret,
        RedirectUri = "http://www.yogihosting.com/TutorialCode/GoogleContactAPI/google-contact-api.aspx",
        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 feed = cr.Get(query);
    StringBuilder sb = new StringBuilder();
    int i = 1;
    foreach (Contact entry in feed.Entries)
    {
        foreach (EMail email in entry.Emails)
        {
            sb.Append(i + " ").Append(email.Address).Append("");
            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.

This Completes our Google Contacts API project. 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.