我正在尝试开发一个服务器端验证我的用户的应用内购买和订阅为 recommended ,我想为此使用 Firebase 函数。基本上,它必须是一个 HTTP 触发函数,它接收购买 token ,调用 Play Developer API 来验证购买,然后对结果进行处理。
但是,调用许多 Google API(包括 Play Developer API )需要重要的授权。以下是我对所需设置的理解:
问题是绝对不存在人类可读的文档或指导。鉴于 Firebase 中的入口流量包含在免费计划中(所以我认为他们鼓励使用 Firebase Functions 中的 Google API),这一事实非常令人失望。我已经设法在这里和那里找到一些信息,但是对 Google API 的经验太少(其中大部分只需要使用 api key ),我需要帮助将它们组合在一起。
到目前为止,这是我发现的:
我很惊讶这没有被询问或记录,因为从 Firebase Functions 验证应用内购买似乎是一项常见任务。以前有没有人成功完成过,或者 Firebase 团队可能会介入回答?
最佳答案
我自己想通了。我还放弃了重量级的客户端库,只是手动编写了这几个请求。
笔记:
scope
JWT 的字段。 Authentication: Bearer
中提供它,无需往返 OAuth 后端。 在您获得带有链接到 Play 商店的服务帐户的私钥的 JSON 文件后,调用 API 的代码如下所示(根据您的需要进行调整)。注意:我使用了
request-promise
作为一种更好的方式 http.request
.const functions = require('firebase-functions');
const jwt = require('jsonwebtoken');
const keyData = require('./key.json'); // Path to your JSON key file
const request = require('request-promise');
/**
* Exchanges the private key file for a temporary access token,
* which is valid for 1 hour and can be reused for multiple requests
*/
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
return request.post({
uri: 'https://www.googleapis.com/oauth2/v4/token',
form: {
'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer',
'assertion': token
},
transform: body => JSON.parse(body).access_token
});
}
/**
* Makes a GET request to given URL with the access token
*/
function makeApiRequest(url, accessToken) {
return request.get({
url: url,
auth: {
bearer: accessToken
},
transform: body => JSON.parse(body)
});
}
// Our test function
exports.testApi = functions.https.onRequest((req, res) => {
// TODO: process the request, extract parameters, authenticate the user etc
// The API url to call - edit this
const url = `https://www.googleapis.com/androidpublisher/v2/applications/${packageName}/purchases/subscriptions/${subscriptionId}/tokens/${token}`;
getAccessToken(keyData)
.then(token => {
return makeApiRequest(url, token);
})
.then(response => {
// TODO: process the response, e.g. validate the purchase, set access claims to the user etc.
res.send(response);
return;
})
.catch(err => {
res.status(500).send(err);
});
});
These是我遵循的文档。
关于firebase - 从 Firebase 函数调用 Google Play Developer API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49836166/