Cannot update a Firestore's document after a purchase verification using Firebase functions

帅比萌擦擦* 提交于 2020-01-06 06:55:14

问题


I've been working on a function to verify purchase in server side. Everything works well. Only one issue, when the purchase is valid (the response.status === 200) the console shows (success) but the document hasn't been updated. Here is my code. Did i miss something ?

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: 'my_email',
   key: 'my_key',
   scopes: ['https://www.googleapis.com/auth/androidpublisher']
});

admin.initializeApp();
admin.firestore().settings({timestampsInSnapshots: true});

exports.validatePurchases = functions.firestore
.document('purchases/{channel}')
.onCreate((docSnapshot, context) => {
    const purchase = docSnapshot.data();
    const order_id = purchase.orderId;
    const package_name = purchase.packageName;
    const sku = purchase.sku;
    const purchase_token = purchase.purchaseToken;
    const user_id = purchase.userId;

    authClient.authorize((err, result) => {
        if (err) {
            console.log(err);
        }
        publisher.purchases.subscriptions.get({
            auth: authClient,
            packageName: package_name,
            subscriptionId: sku,
            token: purchase_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) {
                console.log('success');
                return admin.firestore().collection('users').doc(user_id).update({
                    purchaseToken: purchase_token,
                    isPremiumS: 'true'
                });                    
            } else {
                console.log('fail');
                return admin.firestore().collection('users').doc(user_id).update({
                    purchaseToken: purchase_token,
                    isPremiumS: 'false'
                });                    
            }
        });
    });
    return null;
});    

回答1:


Instead of returning null, your function should return the Promise from your Firestore update() calls.

Add return in two places:

  return authClient.authorize((err, result) => {...

  return publisher.purchases.subscriptions.get({...

Delete return null; at the end of the function



来源:https://stackoverflow.com/questions/55687857/cannot-update-a-firestores-document-after-a-purchase-verification-using-firebas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!