google-people api的简单示例用法

时间:2017-11-28 07:18:00

标签: crystal-lang google-people

这是我第一次使用Google API,而且我在google-people api上遇到了困难,这里有人可以解释一下auth的标题/正文数据需要什么(我使用https://crystal-lang.org/api/latest/OAuth2.html),请分享一个简单的代码(香草/没有图书馆)用你最喜欢的编程语言^^

1 个答案:

答案 0 :(得分:4)

按照Get Ready to Use the People API中描述的步骤操作。在那里,您将找到用Java,Python,PHP,.NET编写的示例。

我们假设你完成了第1步和第2步。这是一个用于发出授权请求的Crystal代码:

require "oauth2"

client_id = "CLIENT_ID"
client_secret = "CLIENT_SECRET"
scope = "profile"
redirect_uri = "urn:ietf:wg:oauth:2.0:oob"

client = OAuth2::Client.new(
  "accounts.google.com",
  client_id,
  client_secret,
  authorize_uri: "/o/oauth2/v2/auth",
  redirect_uri: redirect_uri
)

authorize_uri = client.get_authorize_uri(scope)
authorize_uri #=> https://accounts.google.com/o/oauth2/v2/auth?client_id=CLIENT_ID&redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&response_type=code&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcontacts.readonly

在您的浏览器中打开授权链接,允许访问您的数据,您将获得下一步所需的令牌。

authorization_code = code # authorization code taken from the previous step

client = OAuth2::Client.new(
  "www.googleapis.com",
  client_id,
  client_secret,
  token_uri: "/oauth2/v4/token",
  redirect_uri: redirect_uri
)

access_token = client.get_access_token_using_authorization_code(authorization_code)
client = HTTP::Client.new("people.googleapis.com", tls: true)
access_token.authenticate(client)

response = client.get "/v1/people/me?personFields=names"
response.body # a json that contains my name