简单的示例使用Google-People API



这是我第一次使用Google API,我对Google-People API感到困难,这里的任何人都可以解释AUTH需要的标题/身体数据(我使用https://crystal-lang.org/api/latest/oauth2.html),请在您喜欢的编程语言中共享一个简单的代码(无库)^^

遵循准备使用People API中描述的步骤。在那里,您会发现用Java,Python,Php,.net。

编写的示例

让我们假设您完成了步骤1和2的完成。这是一个授权请求的水晶代码:

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

相关内容

  • 没有找到相关文章

最新更新