5

I've been thinking of using Google API directly to reward users (update user data on firestore) after verifying purchase through:

GET https://www.googleapis.com/androidpublisher/v3/applications/packageName/purchases/products/productId/tokens/token

But the authorization step is somewhat tricky. How do I achieve it with this Cloud Function I have got from one of you:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
const {google} = require("googleapis");
const publisher = google.androidpublisher('v2');
const authClient = new google.auth.JWT({
    email: 'Service Account Email',
    key: 'BEGIN PRIVATE KEY*************END PRIVATE KEY',
    scopes: ['https://www.googleapis.com/auth/androidpublisher']
});
admin.initializeApp();

exports.validatePurchases = functions.database
    .ref('/purchases/{uId}/{orderId}')
    .onCreate((event, context) => {
        const purchase = event.val();
        if (purchase.is_processed === true) {
            console.log('Purchase already processed!, exiting');
            return null;
        }
        const orderId = context.params.orderId;
        const dbRoot = event.ref.root;
        const package_name = purchase.package_name;
        const sku = purchase.sku;
        const my_token = purchase.token;

        authClient.authorize((err, result) => {
            if (err) {
                console.log(err);
            }
            publisher.purchases.products.get({
                auth: authClient,
                packageName: package_name,
                productId: sku,
                token: my_token
            }, (err, response) => {
                if (err) {
                    console.log(err);
                }
                // Result Status must be equals to 200 so that the purchase is valid
                if (response.status === 200) {
                    return event.ref.child('is_validated').set(true);
                } else {
                    return event.ref.child('is_validated').set(false);
                }
            });
        });
        return null;
    });

Please spot errors and identify if it'll work. How do I authorize and deploy the function? Thanks

Aksh
  • 321
  • 2
  • 16
  • 1
    Possible duplicate of [Call Google Play Developer API from Firebase Functions](https://stackoverflow.com/questions/49836166/call-google-play-developer-api-from-firebase-functions) – Markus Penguin Nov 28 '18 at 06:37
  • ^^ Above answer explains how to make an authorized request to the Play API from Cloud Functions. – Markus Penguin Nov 28 '18 at 06:39

0 Answers0