从 Stripe 预建结账成功后更新数据库中的用户

Update user in database on success from Stripe prebuilt checkout

我正在使用 Stripe 的预建结帐和 react 和 firebase。结帐过程工作正常并将用户定向到 succes_url,但我也想更新数据库中用户下的字段。我不明白如何包含更新成功结帐后运行的数据库的函数。

export const checkoutWithStripe = async(user) => {
    const checkoutSessionsRef = collection(db, 'users', user.uid, 'checkout_sessions');

    const singleCheckoutSessionRef = await addDoc(checkoutSessionsRef, {
        price: 'price_xyz',
        allow_promotion_codes: true,
        success_url: `${window.location.origin}/dashboard/app?success=true`,
        cancel_url: `${window.location.origin}/dashboard/app?canceled=true`
    });

    onSnapshot(singleCheckoutSessionRef, (snap) => {
        const { error, url: checkoutUrl } = snap.data();

        if (error) {
            console.error(`An checkout error occured: ${error.message}`);
        }
        if (checkoutUrl) {
            window.location.assign(checkoutUrl);
        }
        
    });

    // TODO: Update user type in firebase from free to starter on successful checkout
};

感谢您的帮助。

更新:

我分两部分解决了。

  1. 在 Stripe 中,我创建了一个新的 webhook,它指向一个导出的 firebase 函数 (2),该函数在“checkout.session.completed”被触发时触发。

  2. 在 Firebase 中,我创建了一个函数来侦听“checkout.session.completed”事件,然后调用一个函数来根据我从 Stripe 事件中获得的用户电子邮件更新数据库。

这是监听事件的 Firebase 函数:

/**
 * A webhook handler function for the relevant Stripe events.
 */
exports.updateCustomer = functions.https.onRequest((req, resp) => {

    functions.logger.log("updateCustomer body", req);

    const relevantEvents = new Set([
        'checkout.session.completed'
    ]);
    let event;

    // Instead of getting the `Stripe.Event`
    // object directly from `req.body`,
    // use the Stripe webhooks API to make sure
    // this webhook call came from a trusted source
    try {
        event = stripe.webhooks.constructEvent(
            req.rawBody,
            req.headers['stripe-signature'],
            endpointSecret
        );
    } catch (error) {
        functions.logger.log(`Webhook Error: Invalid Secret`);
        resp.status(401).send('Webhook Error: Invalid Secret');
        return;
    }

    functions.logger.log("updateCustomer", event.type);

    if (relevantEvents.has(event.type)) {
        // logs.startWebhookEventProcessing(event.id, event.type);
        try {
            switch (event.type) {
                case 'checkout.session.completed':
                    const session = event.data.object;
                    functions.logger.log("checkout.session.completed:", session);
                    updatePlan(session.customer_details.email);
                    break;
                default:
                    functions.logger.log(`Unhandled event type ${event.type}`);
            }
        } catch (error) {
            functions.logger.log(`Unhandled event error ${event.type}`);
            resp.json({
                error: 'Webhook handler failed. View function logs in Firebase.',
            });
            return;
        }
    }

    // Return a response to Stripe to acknowledge receipt of the event.
    resp.json({ received: true });
});

如果在结帐会话成功时需要 运行 一些代码,那么您应该使用 Stripe webhooks 并监听 checkout.session.completed 事件。 the Stripe documentation.

中对此进行了介绍