In this tutorial I will develop a web application to get all Google Contacts from a person account who authorizes the application. I will make it in Asp.Net platform and will use C# to communicate with the Google Contacts API.
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 I will use this project to communicate with my C# code.
The first step is to create API Project in Google APP Console:
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.
<img src="https://www.yogihosting.com/wp-content/uploads/2015/02/oauth-consent-screen.png" alt="oauth consent screen" class="img-fluid">
Next, Google asks 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.
<img src="https://www.yogihosting.com/wp-content/uploads/2015/02/create-credentials.png" alt="create credentials" class="img-fluid">
Next, it will ask to select the Application Type. Here select Web Application and give na ame to your Application.
For the Authorised redirect URIs field, enter the URL where users will be redirected once authenticated with Google.
Finally click the ‘Create’ button.
<img src="https://www.yogihosting.com/wp-content/uploads/2015/02/create-client-id.png" alt="create client id" class="img-fluid">
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.
<img src="https://www.yogihosting.com/wp-content/uploads/2015/02/client-id-and-client-secret.png" alt="client id and client secret" class="img-fluid">
OAuth 2.0 authenticates the users and asks for there permissions for sharing contacts with the application. If a user grants his permission then Google sends Authorization Code to the return URL in query string variable called code.
See Google OAuth 2.0 online doc at – here.
Let us create the ASP.NET Web Application. This application will communicate with the Google App and gets all emails addresses of the user’s contacts from his Google account.
Note: It will first ask for user’s consent to get all emails, and when the user allows it, only then the emails are shared.
Now follow the steps as I have outlined below:
I will redirect user on a Button’s 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 = "https://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. Note that it must be the same which we put in for Authorised redirect URIs field when creating the Client ID.
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 I created before.
Click the Allow Button and you will be redirect to the URL set by you earlier.
<img src="https://www.yogihosting.com/wp-content/uploads/2015/02/consent-screen.png" alt="consent screen" class="img-fluid">
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 –
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 the 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 = "https://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 the 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.
Add a div to the .aspx page.
<div id="dataDiv" runat="server"></div>
Please note that in this step I have used a few Google dot net dlls for making the API call. It simplifies the 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 the 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, I extract it, and finally loop through this data and show it in a div.
Now click the button and once you give your consent you will see all your contacts email in the div control like shown in the below image.
This completes our Google Contacts API application. Hope you like it and please share this tutorial in your FB and twitter accounts.
Download link: