简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM