///purchase handler
const functions = require("firebase-functions");
const admin = require("firebase-admin");
const googleServiceAccountKey = require("./serviceAccount.json");
admin.initializeApp({
credential: admin.credential.cert(googleServiceAccountKey),
});
const {google} = require("googleapis");
const axios = require("axios");
exports.androidPurchaseHandler = functions.https.onRequest((request, response) => {
const {purchaseObject, type} = request.body;
// get the token and product id from the request
const purchaseToken = purchaseObject.purchaseToken;
const productId = purchaseObject.productId;
functions.logger.info(`trying to handle ${type} for the follow ${JSON.stringify(purchaseObject)}`);
// set your package id
const packageID = "edu.fit.my.jgibb2018.pob";
const returnTheResponse = (data) => {
response.status(200).send(data);
};
const acknowledgePurchase = (err, tokens) => {
functions.logger.info("acknowledging purchase");
const config = {
method: "post",
url: `https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${packageID}/purchases/products/${productId}/tokens/${purchaseToken}:acknowledge`,
headers: {
"Authorization": `Bearer ${tokens.access_token}`,
},
};
axios(config)
.then(function(r) {
functions.logger.info("acknowledge success. returning ", JSON.stringify(r.data));
returnTheResponse(r.data);
})
.catch(function(e) {
returnTheResponse(JSON.stringify({error: e.data, status: e.status, message: e.message}));
});
};
const verifyPurchase = (err, tokens) => {
functions.logger.info("verifying purchase");
const config = {
method: "get",
url: `https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${packageID}/purchases/products/${productId}/tokens/${purchaseToken}`,
headers: {
"Authorization": `Bearer ${tokens.access_token}`,
},
};
axios(config)
.then(function(r) {
functions.logger.info("verify success. returning ", JSON.stringify(r.data));
returnTheResponse(r.data);
})
.catch(function(e) {
returnTheResponse(JSON.stringify({error: e.data, status: e.status, message: e.message}));
});
};
const getAccessToken = () => {
const jwtClient = new google.auth.JWT(
googleServiceAccountKey.client_email,
null,
googleServiceAccountKey.private_key,
["https://www.googleapis.com/auth/androidpublisher"],
null,
);
try {
functions.logger.info("type is ", type);
if (type == "purchaseAcknowledge") {
jwtClient.authorize(acknowledgePurchase);
} else {
jwtClient.authorize(verifyPurchase);
}
} catch (error) {
functions.logger.log(error);
response.status(500).send("getting auth", error);
}
};
getAccessToken();
});