0

c# google Contact api, I want to register users in my google contact list. but issue is each time when I save the contact google asks for permission. Currently I am using below code in Asp.net website but I want to use Web.Api.

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

protected void googleButton_Click(object sender, EventArgs e)
{
    /*https://developers.google.com/google-apps/contacts/v3/
      https://developers.google.com/accounts/docs/OAuth2WebServer
      https://developers.google.com/oauthplayground/
    */
    string clientId = "yourclientId";
    string redirectUrl = "http://www.yogihosting.com/TutorialCode/GoogleContactAPI/google-contact-api.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");
}

public void GetAccessToken()
{
    string code = Request.QueryString["code"];
    string google_client_id = "yourclientId";
    string google_client_sceret = "yourclientSecret";
    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 + "&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);
}

public void GetContacts(GooglePlusAccessToken serStatus)
{
    string google_client_id = "yourclientId";
    string google_client_sceret = "yourclientSecret";
    /*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<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(i + "&nbsp;").Append(email.Address).Append("<br/>");
            i++;
        }
    }

   Contact newEntry = new Contact();
        // Set the contact's name.
        newEntry.Name = new Name()
        {
            FullName = "Elizabeth Bennet",
            GivenName = "Elizabeth",
            FamilyName = "Bennet",
        };
        newEntry.Content = "Notes";
        // Set the contact's e-mail addresses.
        newEntry.Emails.Add(new EMail()
        {
            Primary = true,
            Rel = ContactsRelationships.IsHome,
            Address = "liz@gmail.com"
        });
        newEntry.Emails.Add(new EMail()
        {
            Rel = ContactsRelationships.IsWork,
            Address = "liz@example.com"
        });
        // Set the contact's phone numbers.
        newEntry.Phonenumbers.Add(new PhoneNumber()
        {
            Primary = true,
            Rel = ContactsRelationships.IsWork,
            Value = "(206)555-1212",
        });
        newEntry.Phonenumbers.Add(new PhoneNumber()
        {
            Rel = ContactsRelationships.IsHome,
            Value = "(206)555-1213",
        });
        // Set the contact's IM information.
        newEntry.IMs.Add(new IMAddress()
        {
            Primary = true,
            Rel = ContactsRelationships.IsHome,
            Protocol = ContactsProtocols.IsGoogleTalk,
        });
        // Set the contact's postal address.
        newEntry.PostalAddresses.Add(new StructuredPostalAddress()
        {
            Rel = ContactsRelationships.IsWork,
            Primary = true,
            Street = "1600 Amphitheatre Pkwy",
            City = "Mountain View",
            Region = "CA",
            Postcode = "94043",
            Country = "United States",
            FormattedAddress = "1600 Amphitheatre Pkwy Mountain View",
        });
        // Insert the contact.
        Uri feedUri = new Uri(ContactsQuery.CreateContactsUri("default"));
        Contact createdEntry = cr.Insert(feedUri, newEntry);

    /*End*/
    dataDiv.InnerHtml = sb.ToString();
}

Is there any way i can save users details in google permission, Even I am ok if google asks for permission only first time, but not all time.

Abhishek P
  • 68
  • 10
  • 1
    The urgency of a question is never relevant to the question itself, although I'd say that the more urgent it is, the more important it is that you include all relevant context so that people can help you straight away. Now, what sort of app is this? How are you getting permission? If you're getting OAuth tokens, are you able to store the refresh token somewhere? – Jon Skeet Nov 08 '16 at 12:59
  • now I added the code. – Abhishek P Nov 08 '16 at 13:21
  • Right, so you're getting a refresh token - can't you store that, so you can refresh the access token later? – Jon Skeet Nov 08 '16 at 13:30
  • See also: http://stackoverflow.com/questions/14163632/how-refresh-token-should-be-saved – Jon Skeet Nov 08 '16 at 13:31
  • Can I use same token more than once, If yes then I can save and I will use that one only. – Abhishek P Nov 08 '16 at 13:32
  • Yes, you use an access token until it's stale, then use a refresh token to get a new access token - at least, that's my understanding... – Jon Skeet Nov 08 '16 at 13:33
  • See also: https://developers.google.com/identity/protocols/OAuth2WebServer – Jon Skeet Nov 08 '16 at 13:34
  • Ok, I will try with same token, also is there any way by which I can bypass google permission, each time its asks for permission for my website. – Abhishek P Nov 08 '16 at 13:35
  • I would certainly hope not - do you think we *should* let people access contacts without permission? Really? – Jon Skeet Nov 08 '16 at 13:50
  • My requirement is I will have one form where people will fill their details and through api/service I will save users details in my google accounts. So in that case I should not ask. – Abhishek P Nov 08 '16 at 13:53
  • If you're only saving the information in *your* Google account, then I would be surprised if getting the *user's* access token did anything at all for you. It sounds like you should be using service account authentication instead. – Jon Skeet Nov 08 '16 at 14:26
  • ok, thanks i will try service account authentication. do you have any good .net reference for this. – Abhishek P Nov 08 '16 at 17:22
  • See https://cloud.google.com/docs/authentication - and you can use `GoogleCredential.FromStream` to load a JSON file with the service account details explicitly. – Jon Skeet Nov 08 '16 at 17:25

0 Answers0