'Unable to integrate Stripe checkout into Vue JS app

I am trying to redirect to stripe checkout using a click event that calls the payStripe function

<button @click="payStripe" class="btn btn-primary" type="button">Place Order</button>

I have imported stripe into my Vue component like so;

import { loadStripe } from "@stripe/stripe-js";
const stripe = loadStripe('MY-KEY');

I am using Firebase cloud functions and axois to fetch the session and store this to a data property, this works fine.

But, the payStripe method, when called, gives the following error;

Error in v-on handler: "TypeError: stripe.redirectToCheckout is not a function"

Here is the function i am using which, from all accounts is similar to the Stripe API docs;

  data() {
    return {
      sessionId: null,
    }
  },
  methods: {
    //This function sends us to the stripe checkout
     payStripe() {
        stripe.redirectToCheckout({
          sessionId: this.sessionId
        })
        .then(function(result) {
          console.log(result);
        }).catch(function(error) {
          console.log(error);
        });
     }
  },

I had original issues with babel-core, so i updated to @babel/core to get rid of rest operator issues when compling code, but faced with this new issue. Any advice would be great. Thank you



Solution 1:[1]

According to the documentation here, loadStripe returns a promise that you must wait to resolve.

Try something like

import { loadStripe } from "@stripe/stripe-js"
const stripeInit = loadStripe('MY-KEY') // returns a promise

and when you want to use stripe

methods: {
  //This function sends us to the stripe checkout
  payStripe() {
    // wait for the promise to resolve first
    stripeInit.then(stripe => {
      stripe.redirectToCheckout({
        sessionId: this.sessionId
      }).then(function(result) {
        console.log(result);
      }).catch(function(error) {
        console.error(error);
      });
    })
  }
}

Solution 2:[2]

Using Laravel Homestead as a vm, I turned ssl: true in Homestead.yaml, and entered https://site.test manually in the URL. I didn't get a valid https certificate, but the vue-stripe components load and it works

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Phil
Solution 2 Dazzle