授权

本部分包含特定于 Google Play Developer API 的说明。如需了解详情,请参阅完整的 OAuth2 文档

初始配置

对 Google Play Android Developer API 的访问权限需使用 OAuth 2.0 Web Server 流程进行身份验证。您需要先设置 API 控制台项目、创建客户端 ID 并生成刷新令牌,然后才能使用该 API。

创建 API 控制台项目

  1. 转到 API 控制台并使用您的 Google Play 管理中心帐号登录。
  2. 选择创建项目
  3. 转到左侧导航面板中的服务
  4. 启用 Google Play Android Developer API
  5. 接受服务条款。
  6. 转到左侧导航面板中的 API 访问权限
  7. 选择创建 OAuth 2.0 客户端 ID
    • 在第一个页面上,您需要填写商品名称,但不需要提供徽标。请注意,您的最终用户不会看到该商品名称。
    • 在第二个页面上,选择 Web 应用并设置重定向 URI 和 JavaScript 源。这两项设置以后都可以更改。
  8. 选择创建客户端 ID

生成刷新令牌

  1. 使用您的 Google Play 管理中心帐号登录,然后转到以下 URI:
    https://accounts.google.com/o/oauth2/auth?scope=https://www.googleapis.com/auth/androidpublisher&response_type=code&access_type=offline&redirect_uri=...&client_id=...
  2. 看到系统提示时,请选择允许访问
  3. 浏览器将使用 code 参数重定向到您的重定向 URI,该参数类似于 4/eWdxD7b-YSQ5CNNb-c2iI83KQx19.wp6198ti5Zc7dJ3UXOl0T3aRLxQmbwI
  4. 将该代码替换为访问权限和刷新令牌组合,为此,您需要向 https://accounts.google.com/o/oauth2/token 发送 POST 请求,并设置以下字段:
    grant_type=authorization_code
    code=<the code from the previous step>
    client_id=<the client ID token created in the APIs Console>
    client_secret=<the client secret corresponding to the client ID>
    redirect_uri=<the URI registered with the client ID>
    
    成功的响应将包含您的 JSON 格式的令牌:
    {
      "access_token" : "ya29.ZStBkRnGyZ2mUYOLgls7QVBxOg82XhBCFo8UIT5gM",
      "token_type" : "Bearer",
      "expires_in" : 3600,
      "refresh_token" : "1/zaaHNytlC3SEBX7F2cfrHcqJEa3KoAHYeXES6nmho"
    }
    

访问 API

在您生成客户端凭据和刷新令牌后,您的服务器无需进行有效登录或人工干预即可访问该 API。

使用访问令牌

服务器可以通过在请求的 Authorization 标头中传递访问令牌来调用该 API:

Authorization: Bearer oauth2-token

使用刷新令牌

每个访问令牌仅在短时间内有效。当前访问令牌过期后,服务器需要使用刷新令牌来获取新的访问令牌。为此,请向 https://accounts.google.com/o/oauth2/token 发送 POST 请求,并设置以下字段:

grant_type=refresh_token
client_id=<the client ID token created in the APIs Console>
client_secret=<the client secret corresponding to the client ID>
refresh_token=<the refresh token from the previous step>

成功的响应将包含另一个访问令牌:

{
  "access_token" : "ya29.AHES3ZQ_MbZCwac9TBWIbjW5ilJkXvLTeSl530Na2",
  "token_type" : "Bearer",
  "expires_in" : 3600,
}

因此,刷新令牌可允许网络服务器继续访问该 API,而无需有效登录 Google 帐号。