在 Nuxt Js 中集成 Stripe 元素 [英] Integrate Stripe Elements in Nuxt Js

查看:28
本文介绍了在 Nuxt Js 中集成 Stripe 元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

上周我按照这个文档成功地在我的 react + spring boot 中集成了 Stripe https://stripe.com/docs/stripe-js/react 应用程序并在我的 React 类组件中使用,

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,

现在我要从 react 迁移到 nuxt,我想在 nuxt js 中集成 Stripe.

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

我如何在我的 nuxt 项目中使用这些组件?

How I use those components in my nuxt project?

推荐答案

安装stripe模块

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()
  },
}

此示例正在初始化 IBAN 元素,但您几乎明白了这一点,可以使用此处提供的所有方法:https://stripe.com/docs/js/elements_object/create_element?type=iban

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

这篇关于在 Nuxt Js 中集成 Stripe 元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆