1
votes

I've created a function to check the in app payments of the google play and execute some actions if everything is ok.

this i the functions:

exports.validatePurchases = functions.firestore
    .document('users/{userID}/purchasesRemoveAds/{documentID}')
    .onCreate(async (snap, context) => {

        const userID = context.params.userID;

        const purchase = snap.data();
        if (!purchase) {
            return null
        } else {
            if (purchase.is_processed === true) {
                console.log('Purchase already processed!, exiting');
                return null;
            }
            // const orderId = context.params.orderId;
            // const dbRoot = event.ref.root;
            const packageName = purchase.packageName;
            const productId = purchase.productId;
            const purchaseToken = purchase.purchaseToken;

            authClient.authorize()
            // authClient.authorize() returns a credentials Object
                .then(credentials => {
                    console.log(credentials, productId, purchaseToken);
                    return playDeveloperApiClient.purchases.products.get({
                        auth: authClient,
                        packageName: packageName,
                        productId: productId,
                        token: purchaseToken
                    });
                })
                // publisher.purchases.products.get() Returns a axiosResponse object with Purchase data within and the status that should be enough for the validation
                .then((axiosResponse) => {
                    console.log(`Status Code: ${axiosResponse.status} Purchase state: ${ axiosResponse.data.purchaseState} ${typeof axiosResponse.status} ${typeof axiosResponse.data.purchaseState}`);
                    if (axiosResponse.status === 200 && axiosResponse.data.purchaseState === 0) {
                        console.log('ok here');
                        // Your purchase is valid, do your thing
                        return changeShowAdsFalse(userID);
                    } else {
                        console.log(typeof axiosResponse.status);
                    }
                    return null;
                })
                .catch(reason => {
                    console.log(`Rejection Code: ${reason.code}`);
                    console.log(`Rejection Message: ${reason.message}`);
                    return null;
                });


            return null;
        }
    });

It's pretty simple, it listen on the firestore database, whene there is a new document in the directory it trigger the function. then it gets the data from the document and it get the purchases with playDeveloperApiClient.purchases.products.get, then it check the new data with axiosResponse and get the purchase status. After that, it should check for the status == 200 and the purchaseState == 0, thing that happen (and I see it because I log those value) but from there nothing more happen. The if is not executed neither the else. Another weird thing is that before the first log and the second log pass almost a minute or sometimes more.

I have a blaze plan on firebase and I don't have any credit card linked.

I don't know what is happening


the log of the cloud function is :

10:14:22.856 PM
validatePurchases
Billing account not configured. External network is not accessible and quotas are severely limited. Configure billing account to remove these restrictions

10:14:23.561 PM
validatePurchases
Function execution took 706 ms, finished with status: 'ok'

10:14:24.457 PM
validatePurchases
{ access_token: 'token.AO-token-token',
  token_type: 'Bearer',
  expiry_date: 1571433263000,
  id_token: undefined,
  refresh_token: 'jwt-placeholder' } 'remove_ads' 'token.AO-token-token'

10:14:27.457 PM
validatePurchases
Status Code: 200 Purchase state: 0 number number
1
What is changeShowAdsFalse()? - Renaud Tarnec
@RenaudTarnec Is it a function that changes a value from true to false in the firestore db. It really does just that, but it never being called - alessandro buffoli
Ok, thanks. Can we see its code: since it is an asynchronous function which is included in the Promises chain it is important to see the details. - Renaud Tarnec

1 Answers

2
votes

There are several points that need to be adapted in your Cloud Function.

First of all you need to configure your billing account, as mentioned in the error log. Apparently you are calling a service that is not considered to be a Google-owned service, therefore you need to have an "active" Flame or Blaze plan. See https://firebase.google.com/pricing/ (hover your mouse on the question mark which is right after the "Cloud Functions" title)


Secondly, you chain different promises by doing

        authClient.authorize()
            .then(credentials => {
                //....
                return playDeveloperApiClient.purchases.products.get();
            })
            .then((axiosResponse) => {..})
            .catch(reason => {
                //....
                return null;
            });

but you don't return the first Promise in the chain: You should do return authClient.authorize().


Thirdly, in parallel of the promise chain (or in the middle of it) you do return null;.

        authClient.authorize()
            .then(credentials => {...})
            .then((axiosResponse) => {..})
            .catch(reason => {...});

        return null;   //  <--- !!

or

            .then((axiosResponse) => {
                if (axiosResponse.status === 200 && axiosResponse.data.purchaseState === 0) {
                    return changeShowAdsFalse(userID);
                } else {
                    console.log(typeof axiosResponse.status);
                    //Here you should do something, i.e. throw an error
                }
                return null;   //  <--- !!
            });

Fourthly, since you are using the then() method to chain your promises, you can remove the async keyword in the onCreate() method.


So, after configuring your billing account, the following should do the trick. However note that I haven't seen the code of the changeShowAdsFalse() function but I make the assumption, from your comment above, that it returns a Promise.

exports.validatePurchases = functions.firestore
    .document('users/{userID}/purchasesRemoveAds/{documentID}')
    .onCreate((snap, context) => {

        const userID = context.params.userID;
        const purchase = snap.data();

        if (!purchase) {
            return null;
        } else {
            if (purchase.is_processed === true) {
                console.log('Purchase already processed!, exiting');
                return null;
            }

            const packageName = purchase.packageName;
            const productId = purchase.productId;
            const purchaseToken = purchase.purchaseToken;

            return authClient.authorize()
                .then(credentials => {
                    return playDeveloperApiClient.purchases.products.get({
                        auth: authClient,
                        packageName: packageName,
                        productId: productId,
                        token: purchaseToken
                    });
                })
                .then((axiosResponse) => {
                    if (axiosResponse.status === 200 && axiosResponse.data.purchaseState === 0) {
                        return changeShowAdsFalse(userID);
                    } else {
                        console.log(typeof axiosResponse.status);
                        throw new Error("Wrong type: " + typeof axiosResponse.status);
                    }
                })
                .catch(reason => {
                    console.log(`Rejection Code: ${reason.code}`);
                    console.log(`Rejection Message: ${reason.message}`);
                    return null;
                });

        }

    });