Home > Software engineering >  Update user in database on success from Stripe prebuilt checkout
Update user in database on success from Stripe prebuilt checkout

Time:04-21

I am using Stripe's prebuilt checkout with react and firebase. The checkout process works fine and directs the user to the succes_url, but I would like to update a field under the user in the database as well. I don't understand how I can include a function that updates the DB that runs upon a successful checkout.

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
};

Thankful for any help.

Update:

I solved it, in 2 parts.

  1. In Stripe I created a new webhook that points to a exported firebase function (2) that fires when "checkout.session.completed" is fired.

  2. In Firebase i created a function that listens for the "checkout.session.completed" event and then calls a function that updates the DB based on the user email that I get from the Stripe event.

CodePudding user response:

If you need to run some code when the Checkout Session is successful, then you should use Stripe webhooks and listen to the checkout.session.completed event. This is covered in the Stripe documentation.

  • Related