Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integrate Stripe Elements in Nuxt Js

Last week I successfully integrated stripe in my react + spring boot by following this doc https://stripe.com/docs/stripe-js/react application and using in my react class component,

now I am migrating to nuxt from react and I want to integrate stripe in nuxt js.

How I use those components in my nuxt project?

like image 294
chaitanya gupta Avatar asked Nov 06 '22 01:11

chaitanya gupta


1 Answers

Install the stripe module

yarn add @stripe/stripe-js

Setup any needed env variable

nuxt.config.js

export default {
  publicRuntimeConfig: {
    stripePublishableKey: process.env.STRIPE_PUBLISHABLE_KEY,
  },
}

Then, let's take a component and import Stripe into it

Example.vue

<template>
  <div id="iban-element" class="mt-2 stripe-iban-element"></div>
</template>

<script>
import { loadStripe } from '@stripe/stripe-js/pure'

loadStripe.setLoadParameters({ advancedFraudSignals: false }) // https://github.com/stripe/stripe-js#disabling-advanced-fraud-detection-signals
let stripe, elements

export default {
  methods: {
    async loadStripeWhenModalOpens() {
      if (!stripe) {
        stripe = await loadStripe(this.$config.stripePublishableKey)
        elements = stripe.elements()
      }
      this.$nextTick(async () => {
        const iban = elements.create('iban', {
          supportedCountries: ['SEPA'],
          placeholderCountry: 'FR',
          iconStyle: 'default',
          style: {
            ... // fancy styling
          },
        })
        // eslint-disable-next-line
        await new Promise((r) => setTimeout(r, 100)) // ugly but needed if you hard refresh the exact page where the module is imported
        iban.mount('#iban-element')
      })
    },

    destroyStripeIbanElement() {
      const ibanElement = elements?.getElement('iban')
      if (ibanElement) ibanElement.destroy()
    },
  },
  beforeDestroy() {
    this.destroyStripeIbanElement()
  },
}

This example is initializing an IBAN element but your pretty much get the point and can use all the methods available here: https://stripe.com/docs/js/elements_object/create_element?type=iban

like image 90
kissu Avatar answered Nov 11 '22 05:11

kissu