Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing Stripe.js as an ES Module into Vue

I'm trying follow the directions from the stripe elements docs and install the ES module into my Vue payment component.

Note, currently the Stripe websites ES module installation tab is down. Here's a substitute.

I ran:

npm install @stripe/stripe-js

Usage

import {loadStripe} from '@stripe/stripe-js';

const stripe = await loadStripe('pk_test_TYooMQauvdEDq54NiTphI7jx');

When I change my code to reflect the installation of the module I get this error:

30:17 error Parsing error: Can not use keyword 'await' outside an async function

import {loadStripe} from '@stripe/stripe-js';
let stripe = await loadStripe(`pk_test_mypin`)
elements = stripe.elements()
card = undefined;

export default {
    mounted: function () {
        card = elements.create('card', {

        });
        card.mount(this.$refs.card);
    },
    data () {
        return {
            cardHolderName: '',
            stripeErrorMessage: null,
            serverErrorMessage: null,
        }
    },
    computed: {

    },
    methods: {
        processPayment(){

            let self = this;

            stripe.createPaymentMethod(
                'card', card, {
                    billing_details: { name: this.cardHolderName }
            }).then(function(result) {

                if(self.subscribitionCheckout){
                    self.submitPaymentForm(result.paymentMethod);
                } else if (self.changePaymentMethod){
                    self.changePaymentMethod(result.paymentMethod)
                }

                if (result.error) {
                    self.stripeErrorMessage = result.error.message;
                    self.hasCardErrors = true;
                    self.$forceUpdate(); // Forcing the DOM to update so the Stripe Element can update.
                return; 
                }
            });

        },
    },
}

Before I had this

let stripe = Stripe(`pk_test_mypin`),
elements = stripe.elements(),
card = undefined;

Also, I based my code on this tutorial

like image 368
Kyle Corbin Hurst Avatar asked Oct 30 '25 06:10

Kyle Corbin Hurst


1 Answers

First, put the expected top level vars in data:

stripe: {}, // or whatever data type
elements: {}, // or whatever data type
card: {}, // or whatever data type

Second, make a created lifecycle hook and load the content there:

created()
{
  loadStripe(`pk_test_TYooMQauvdEDq54NiTphI7jx`).
  then ( (result) =>
  {
    this.elements = result.elements
    // do stuff with card if you have too...

  },
},
like image 200
T.Woody Avatar answered Nov 01 '25 19:11

T.Woody



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!