Firebase功能访问Google API的服务帐户身份验证(用于应用内购买信息)失败

时间:2018-08-23 09:21:59

标签: node.js google-api google-cloud-functions google-play-developer-api android-inapp-purchase

我们正在准备一个Firebase触发器来处理android的实时开发者通知,并且我们必须使用Google Play开发者API来了解用户订阅的详细信息。因此,我们在Google Play控制台中关联了Firebase服务帐户,并且还授予了必要的访问权限。

我们将Google的nodejs库用于googleapis(github link),并编写了如下代码:

return google.auth.getClient({
  keyFile: path.join(__dirname, './service-account.json'),
  scope: 'https://www.googleapis.com/auth/androidpublisher'
}) .then((client) => {
  const androidpublisher = google.androidpublisher({
    version: 'v3',
    auth: client
  });
  const params = {
    packageName: ANDROID_PACKAGE_NAME,
    subscriptionId: ANDROID_SUBSCRIPTIONID,
    token: token
  };
  return androidpublisher.purchases.subscriptions.get(params)
  .then(res => {
    console.log(`The response is ${res.data}`);
    return null;
  })
  .catch(error => {
    console.error(error);
  });
});

但是它返回一个错误状态:'Invalid Credentials',为此我有点迷失了。我已经使用带有授权令牌的curl对该API进行了测试,它也显示401错误响应。

我不确定上面的流程是否正确,有人可以给我任何建议吗?

1 个答案:

答案 0 :(得分:4)

使用JWT中的google-auth-libraryGoogle sample

const googleapis = require('googleapis');
const { JWT } = require('google-auth-library');
const serviceAccount = require('./serviceAccountKey.json');

const getAuthorizedClient = () => new JWT({
    email: serviceAccount.client_email,
    key: serviceAccount.private_key,
    scopes: ['https://www.googleapis.com/auth/androidpublisher']
});

const getAndroidpublisher = () => googleapis.google.androidpublisher({
    version: 'v3',
    auth: getAuthorizedClient()
});

const requestProductValidation = data => new Promise((resolve, reject) => {
    getAndroidpublisher().purchases["products"].get(data, (err, response) => {
        if (err) {
            console.log(`The API returned an error: ${err}`);
            resolve({status: "Error"});
        } else {
            const isValid = response && response.data && response.data.purchaseState === 0;
            resolve({status: isValid ? "OK" : "Error"});
        }
    });
});

exports.purchaseValidationAndroid = functions.https.onCall((data, context) => {
    return requestProductValidation(data);
});

data包含productIdtokenpackageName