Home > Blockchain >  Implement Stripe subscription with Firebase JS SDK version 9
Implement Stripe subscription with Firebase JS SDK version 9

Time:11-26

I'm using Firebase JS V9 in my web application. I'm trying to implement Stripe Etension from Firebase into my app.

The documentation of this extension has not been updated to support Firebase v9. I've been confirmed on Twitter that the documentation will be updated but have no ETA at the moment :)

Here's how they're doing it in previous Firebase version:

const docRef = await db
  .collection('customers')
  .doc(currentUser.uid)
  .collection('checkout_sessions')
  .add({
    price: 'price_1GqIC8HYgolSBA35zoTTN2Zl',
    success_url: window.location.origin,
    cancel_url: window.location.origin,
  });
// Wait for the CheckoutSession to get attached by the extension
docRef.onSnapshot((snap) => {
  const { error, url } = snap.data();
  if (error) {
    // Show an error to your customer and
    // inspect your Cloud Function logs in the Firebase console.
    alert(`An error occured: ${error.message}`);
  }
  if (url) {
    // We have a Stripe Checkout URL, let's redirect.
    window.location.assign(url);
  }
});

So I'm trying to do this but with the new stuff from v9, everything is different. I've search the web and the only solution I can find are about previous Firebase version.

It's my first time using Firebase so it's does not help either.

Anyone have an idea on how to do the above code snippet in Firebase JS SDK V9?

Thanks!

CodePudding user response:

You’ll find below the V9 version of your code. In the JS SDK documentation there are two tabs, one for V9 and one for V8, so it is not very difficult to translate from one version to the other. Example for the onSnapshot() method.

import { collection, addDoc, onSnapshot } from "firebase/firestore"; 

const docRef = await addDoc(collection(db, `customers/${currentUser.uid}/checkout_sessions`), {
          price: 'price_1GqIC8HYgolSBA35zoTTN2Zl',
          success_url: window.location.origin,
          cancel_url: window.location.origin,
        });

onSnapshot(docRef, (snap) => {
    const { error, url } = snap.data();
        if (error) {
          // Show an error to your customer and
          // inspect your Cloud Function logs in the Firebase console.
          alert(`An error occured: ${error.message}`);
        }
        if (url) {
          // We have a Stripe Checkout URL, let's redirect.
          window.location.assign(url);
        }
})
  • Related