我正在尝试访问google subscriptions api,而我一直在为该错误苦苦挣扎几天。根据此处的文档:https://developers.google.com/identity/protocols/oauth2/service-account#httprest,我必须创建一个JWT令牌,然后将其交换为access_token,这是我成功完成的。但是,当我尝试在订阅API上使用此令牌时,得到401的响应。我正在Node.js环境中工作:
const functions = require('firebase-functions');
const jwt = require('jsonwebtoken');
const keyData = require('./key.json'); // Path to your JSON key file
const axios = require('axios');
function getAccessToken(keyData) {
// Create a JSON Web Token for the Service Account linked to Play Store
const token = jwt.sign(
{ scope: 'https://www.googleapis.com/auth/androidpublisher' },
keyData.private_key,
{
algorithm: 'RS256',
expiresIn: '1h',
issuer: keyData.client_email,
subject: keyData.client_email,
audience: 'https://www.googleapis.com/oauth2/v4/token'
}
);
// Make a request to Google APIs OAuth backend to exchange it for an access token
// Returns a promise
config = {
method: 'post',
url: 'https://www.googleapis.com/oauth2/v4/token',
data: {
grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
assertion: token
}
};
return axios(config);
}
function makeApiRequest(url, accessToken) {
config = {
method: 'get',
url: url,
auth: {
bearer: accessToken
}
};
return axios(config);
}
console.log("start");
purchaseToken = "token";
requestUrl = "https://androidpublisher.googleapis.com/androidpublisher/v3/applications/{package}/purchases/subscriptions/{id}/tokens/" + purchaseToken;
getAccessToken(keyData)
.then(response => {
console.log("access_token: " + response.data.access_token);
return makeApiRequest(requestUrl, response.data.access_token);
})
.then(response => {
// TODO: process the response, e.g. validate the purchase, set access claims to the user etc.
response.send(response);
return;
})
.catch(err => {
console.log(err);
});
错误:
{
code: 401,
message: 'Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.',
errors: [
{
message: 'Login Required.',
domain: 'global',
reason: 'required',
location: 'Authorization',
locationType: 'header'
}
],
status: 'UNAUTHENTICATED'
}
也许我以错误的方式发送令牌?
答案 0 :(得分:0)
找到了解决方案。对于其他在调用Play开发人员API时遇到麻烦的人,您只需用以下命令替换makeApiRequest函数:
function makeApiRequest(url, accessToken) {
config = {
method: 'get',
url: url + `?access_token=${accessToken}`
};
return axios(config);
}
只需将access_token作为参数传递,我仍然不知道为什么它不能与auth属性一起使用。