条带支付firebase云功能无法正确更新数据库

时间:2018-11-11 16:26:54

标签: angular firebase google-cloud-firestore stripe-payments payment

我正在我的应用程序中使用分期付款-试图实现用户余额。

当前,我的index.js中包含以下代码。问题的关键是最后的.then()代码块。本部分写入我的Cloud Firestore数据库。但是,它似乎并没有真正更新我的数据库。当我查看数据库时,余额不会更改,也不会将费用字段添加到保存在数据库中的分条付款对象中。我没有任何错误,也不确定如何调试它。

const functions = require('firebase-functions'); //firebase functions library
const admin = require('firebase-admin'); //firebase admin database
admin.initializeApp(functions.config().firebase);
//initialse stripe with apikey
const stripe = require('stripe')('<stripe test key>')

//name of function is stripe charge
exports.stripeCharge = functions.database
    //whenever a new payment is written to the database, the following will be invoked
    .ref('/payments/{userId}/payments/{paymentId}')
    //event object has the data from the node in the database which is the payment and the token
    .onWrite((change, context) => {
        const payment = change.after.val();
        const userId = context.params.userId;
        const paymentId = context.params.paymentId;

        let balance = 0;

        //return null if there is no payment or if payment already has a charge
        if(!payment || payment.charge) return;

        //now we chain a promise - this is the user in the database
        //this is good for recurring charges or to save customer data in the database
        return admin.database()
            .ref(`/users/${userId}`)
            //once gives a single snapshot of this data
            .once('value')
            //return the snapshot value
            .then(snapshot => {
                return snapshop.val();
            })

            //tell stripe to charge the customer with the payment token
            .then(customer => {

                balance = customer.balance;

                const customerChargeAmount = payment.amount;
                const idempotency_key = paymentId; //prevents duplicate charges on customer cards
                const source = payment.token.id;
                const currency = 'gbp';
                const charge = {customerChargeAmount, currency, source};

                return stripe.charges.create(charge, {idempotency_key});
            })

            //wait for stripe to return the actual stripe object which tells us whether the charge succeeded
            .then(charge => {

                if(!charge) return;

                let updates = {};
                updates[`/payments/${userId}/payments/${paymentId}/charge`] = charge

                if(charge.paid){
                    balance += charge.amount;
                    updates[`/users/${userId}/balance`] = balance;
                }

                admin.database().ref().update(updates);
                return true;
            })
    })

感谢您的帮助。

0 个答案:

没有答案