掌握聚合最新动态了解行业最新趋势
API接口,开发服务,免费咨询服务

如何使用OAuth 2.0在C#和ASP.NET中部署Google Contacts API V3.0

在将内容直接推送给用户的时候,电子邮件依然是最有力的工具之一,因此在很多营销战略中,电子邮件都扮演着重要的作用。为了让邮件营销发挥作用,许多客户端程序的开发者都会使用Google Contacts API来获取当前用户的联系人列表,从而找到更多潜在用户,最终提升流量。

与其他  Google Data APIs一样,这个系统会接受含有XML-encoded输入参数的HTTP请求,然后返回含有被请求信息的Atom feed,这些信息可以在任何XML-aware的编程语言中被解析。今天,我们就来了解以下如何使用OAuth 2.0验证,在C#ASP.NET中部署Google Contacts API v3.0 

第一步:创建项目,准许其使用API


首先我们需要在Google APP Console中创建一个新的API项目-

  • a. 访问 https://console.developers.google.com/project
  • b. 点击创建项目
  • c. 给项目起个名字,然后勾选服务条款复选框
  • d. 点击创建。项目创建完毕之后,浏览器会将你带到项目控制面板页面。
  • e. 在页面左边栏中,点击APIs
  • f. 你会看到所有谷歌API的列表。找到“Contacts API”,然后点击“OFF”按钮

Google Console中创建项目

 

Google Console中的新项目

 

打开Google Contacts API

 

Google Console中的谷歌API

第二步:管理OAuth同意屏幕,并且创建新的Cliend ID


在左边栏中,点击同意屏幕。在打开的页面中输入电子邮件地址和产品名称。然后点击保存。

再一次回到左边栏,点击凭据。之后点击创建新的客户端ID”。之后浏览器会打开新页面,程序类别请选择网页应用,然后输入获得授权的重定向 URI”(也就是用户被带向的URL,用户需要在这里给应用授权)。最后点击创建,这一步会创建新的客户端ID和客户端密钥。保存好ID和密钥,我们将会在后面用上它们。

 

同意屏幕

 

同意屏幕字段

 

设定参数 

 

创建新的客户端ID

 

创建客户端ID

第三步:使用OAuth 2.0验证用户,获取验证码


OAuth 2.0会对用户的身份进行验证,并且向用户发送让应用获取他们的联系人信息的请求。如果用户接受了请求,谷歌就会给他发送验证码。

 

Google OAuth 2.0 架构

Google OAuth 2.0在线文档 – Using OAuth 2.0 for Web Server Applications

部署


  • a. 将用户重新定向到这个URL – https://accounts.google.com/o/oauth2/auth
  • b.  Pass下面这个查询字符串参数-redirect_uri(你在第二部创建新的客户端ID的时候所获得的参数)

response_type – 代码

client_id – 你的客户端ID

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

 我们要以点击事件的方式完成这个步骤

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+"&response_type=code&client_id=" + clientId + "&scope=https://www.google.com/m8/feeds/&approval_prompt=force&access_type=offline");

    }

第四步:交换验证代码,获得Access Code


现在我们需要将HTTP POST请求指向https://accounts.google.com/o/oauth2/token,而且我们还需要pass下面的参数:

  • a. code –验证代码
  • b. client_id – 应用的客户端ID
  • c. client_secret – 应用的客户端密钥
  • d. redirect_url – 项目的重定向URL之一
  • e. grant_type – authorization_code

一个成功的响应会以JSON格式返回下列东西:

  • a. access_token – 可以可以生成Google API调用的token
  • b. refresh_token – 当当前Access Token过期的时候,用来生成新Access Tokentoken
  • c. expires_in – Access Token的生命周期
  • d. token_type – token发挥的类别,在我们的例子中,类别为“bearer”

部署


protected void Page_Load(object sender, EventArgs e)

    {

        if (Request.QueryString["code"] != null)

            GetAccessToken();

    }

它会调用GetAccessToken()函数:

 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 + "&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(responseFromServer);

        /*End*/

        GetContacts(serStatus);

    }

 最后,这个函数会调用GetContacts()函数,其功能是调用Google API

 在从响应中获取JsonConvert类之后,我们将其放在GooglePlusAccessToken类中:

 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; }

}

第五步:使用Access Token调用Google API,获取用户联系人


请注意,在这一步中,为了调用API,我们需要使用一些Google dot net dll,它可以让我们的工作变得更简单。API调用的URLhttps://www.google.com/m8/feeds/contacts/{userEmail}/full

GetContacts()函数的定义:

 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();

    }

用户联系人数据是以JSON格式发送的,我们需要将其提取,然后对其进行loop,并且在一个div钟显示。

上面五部之后,Google Contacts API项目就完成了。

对谷歌API程序进行测试,请点击这里。下载请点击这里


Image

原文来自:SDK.cn

声明:所有来源为“聚合数据”的内容信息,未经本网许可,不得转载!如对内容有异议或投诉,请与我们联系。邮箱:marketing@think-land.com

  • 个人/企业涉诉查询

    通过企业关键词查询企业涉松详情,如裁判文书、开庭公告、执行公告、失信公告、案件流程等等。

    通过企业关键词查询企业涉松详情,如裁判文书、开庭公告、执行公告、失信公告、案件流程等等。

  • 账号黑产风险识别

    根据手机号来查询是否命中黑产风险

    根据手机号来查询是否命中黑产风险

  • IP反查域名

    IP反查域名是通过IP查询相关联的域名信息的功能,它提供IP地址历史上绑定过的域名信息。

    IP反查域名是通过IP查询相关联的域名信息的功能,它提供IP地址历史上绑定过的域名信息。

  • 人脸卫士

    结合权威身份认证的精准人脸风险查询服务,提升人脸应用及身份认证生态的安全性。人脸风险情报库,覆盖范围广、准确性高,数据权威可靠。

    结合权威身份认证的精准人脸风险查询服务,提升人脸应用及身份认证生态的安全性。人脸风险情报库,覆盖范围广、准确性高,数据权威可靠。

  • 全国城市空气质量

    全国城市和站点空气质量查询,污染物浓度及空气质量分指数、空气质量指数、首要污染物及空气质量级别、健康指引及建议采取的措施等。

    全国城市和站点空气质量查询,污染物浓度及空气质量分指数、空气质量指数、首要污染物及空气质量级别、健康指引及建议采取的措施等。

0512-88869195
数 据 驱 动 未 来
Data Drives The Future