2

我正在尝试Purchases.Subscriptions: get从我的本地服务器调用,但我收到一条错误消息说Error: Login Required.

我已经创建了一个具有项目所有者角色的服务帐户,如此处所述。然后我设置GOOGLE_APPLICATION_CREDENTIALS环境变量并使其指向下载的 JSON 文件,如此处所述

最后,我尝试根据网站文档示例运行一些用于服务器到服务器身份验证的示例代码,以查看是否可以成功进行身份验证:

import { google } from 'googleapis'

async function main() {
  try {
    const auth = new google.auth.GoogleAuth({
      scopes: ['https://www.googleapis.com/auth/androidpublisher']
    })

    const authClient = await auth.getClient()
    const project = await auth.getProjectId()
    const publisher = google.androidpublisher('v3')

    const result = await publisher.purchases.subscriptions.get({
      packageName: 'com.mywebsite.subdomain',
      subscriptionId: 'com.mywebsite.subscription_name',
      token: '...my purchase token...'
    })

    console.log(result)
  } catch (error) {
    console.error(error)
  }
}

main()

我只是使用了 Billing API 而不是 Compute API,否则我的示例与 docs中给出的示例相同。我不确定为什么我遇到问题,任何帮助将不胜感激!


完整错误:

{ Error: Login Required
    at Gaxios.request (/Users/squadri/Desktop/googlenode/node_modules/gaxios/src/gaxios.ts:86:15)
    at process._tickCallback (internal/process/next_tick.js:68:7)
  response:
   { config:
      { url:
         'https://www.googleapis.com/androidpublisher/v3/applications/com.mywebsite.subdomain/purchases/subscriptions/com.mywebsite.subscription_name/tokens/...my%20purchase%20token...',
        method: 'GET',
        paramsSerializer: [Function],
        headers: [Object],
        params: [Object: null prototype] {},
        validateStatus: [Function],
        retry: true,
        responseType: 'json',
        retryConfig: [Object] },
     data: { error: [Object] },
     headers:
      { 'alt-svc': 'quic=":443"; ma=2592000; v="46,43,39"',
        'cache-control': 'private, max-age=0',
        connection: 'close',
        'content-encoding': 'gzip',
        'content-type': 'application/json; charset=UTF-8',
        date: 'Tue, 20 Aug 2019 04:41:29 GMT',
        expires: 'Tue, 20 Aug 2019 04:41:29 GMT',
        server: 'GSE',
        'transfer-encoding': 'chunked',
        vary: 'Origin, X-Origin',
        'www-authenticate': 'Bearer realm="https://accounts.google.com/"',
        'x-content-type-options': 'nosniff',
        'x-frame-options': 'SAMEORIGIN',
        'x-xss-protection': '1; mode=block' },
     status: 401,
     statusText: 'Unauthorized' },
  config:
   { url:
      'https://www.googleapis.com/androidpublisher/v3/applications/com.mywebsite.subdomain/purchases/subscriptions/com.mywebsite.subscription_name/tokens/...my%20purchase%20token...',
     method: 'GET',
     paramsSerializer: [Function],
     headers:
      { 'x-goog-api-client': 'gdcl/3.1.0 gl-node/10.16.1 auth/5.2.0',
        'Accept-Encoding': 'gzip',
        'User-Agent': 'google-api-nodejs-client/3.1.0 (gzip)',
        Accept: 'application/json' },
     params: [Object: null prototype] {},
     validateStatus: [Function],
     retry: true,
     responseType: 'json',
     retryConfig:
      { currentRetryAttempt: 0,
        retry: 3,
        retryDelay: 100,
        httpMethodsToRetry: [Array],
        noResponseRetries: 2,
        statusCodesToRetry: [Array] } },
  code: 401,
  errors:
   [ { domain: 'global',
       reason: 'required',
       message: 'Login Required',
       locationType: 'header',
       location: 'Authorization' } ] }
4

3 回答 3

2

例如,试试这个代码片段。 使用googleapi、androidpublisher 和服务帐户身份验证(v3)
打印特定 packageName 的 apk 列表。

const {google} = require('googleapis');
const key = require('./privateKey.json')
const packageName = "com.company.example"

let client = new google.auth.JWT(
  key.client_email,
  undefined,
  key.private_key,
  ['https://www.googleapis.com/auth/androidpublisher']
)
const androidApi = google.androidpublisher({
  version: 'v3',
  auth: client
})

async function getApksList() {
    let authorize = await client.authorize();
    //insert edit
    console.log('authorize :', authorize);
    let res = await androidApi.edits.insert({
        packageName: packageName
    })
    //get edit id
    let editId = res.data.id
    const res = await androidApi.edits.apks.list({
        editId: editId,
        packageName: packageName
    });
    console.log(`Result ${(JSON.stringify(res))}`);
}
getApksList().catch(console.error);

于 2020-01-13T09:06:42.957 回答
0

您需要将 JSON 密钥文件添加到google.auth.GoogleAuth

const auth = new google.auth.GoogleAuth({
  keyFile: process.env.GOOGLE_APPLICATION_CREDENTIALS,
  scopes: ['https://www.googleapis.com/auth/androidpublisher']
});

请参阅:https ://github.com/googleapis/google-api-nodejs-client/blob/master/samples/jwt.js

于 2019-12-03T09:33:09.980 回答
0

您需要将 auth 字段 ( authClient ) 传递给google.androidpublisher

const publisher = google.androidpublisher({
  version: 'v3',
  auth: authClient
})
于 2020-09-10T13:13:20.327 回答