c#google联系api未经许可插入联系人

时间:2016-11-08 12:49:14

标签: c# api service

c#google联系api,我想在我的谷歌联系人列表中注册用户。但问题是每次我保存联系人谷歌要求许可。 目前我在Asp.net网站上使用以下代码,但我想使用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();
}

有什么方法可以在google权限中保存用户详细信息, 如果google第一次请求许可,即使我没有时间也是如此。

0 个答案:

没有答案