如何在 NuxtJs 中集成 PayPal 智能支付按钮?

时间:2021-04-20 09:53:44

标签: paypal nuxt.js

我目前的工作解决方案。

<template>
  <div>
    <div ref="paypal"></div>     
  </div>
</template>

<script>
export default {
  mounted: function () {
    const script = document.createElement("script");
    script.src = "https://www.paypal.com/sdk/js?client-id=SECRET";
    script.addEventListener("load", this.setLoaded);
    document.body.appendChild(script);
  },

  methods: {
    openPaymentAmountModal() {
      this.isPaymentAmountModalVisible = true;
    },
    closePaymentAmountModal() {
      this.isPaymentAmountModalVisible = false;
    },
    setLoaded: function () {
      window.paypal.Buttons({
        createOrder: function (data, actions) {
          // This function sets up the details of the transaction, including the amount and line item details.
          return actions.order.create({
            purchase_units: [{
              amount: {
                value: '0.01'
              }
            }]
          });
        },
        onApprove: function (data, actions) {
          // This function captures the funds from the transaction.
          return actions.order.capture().then(function (details) {
            // This function shows a transaction success message to your buyer.
            alert('Transaction completed by ' + details.payer.name.given_name);
          });
        }
      }).render(this.$refs.paypal);
    }
  }
}
</script>

在模态中,我不得不再次加载脚本。

如何在组件或页面级别的 NuxtJs 应用程序中全局加载此 Paypal 脚本?

2 个答案:

答案 0 :(得分:3)

我在我的项目中有相同的集成,并在我的页面中导入脚本:

head() {
    return {
        script: [{
            src: 'https://www.paypal.com/sdk/js?client-id=<CLIENT_ID>'
        }],
    }
},

然后将 PayPal 的 .render() 方法放在 mounted() 中。

答案 1 :(得分:1)

您始终可以在 SPA index.htm 中将脚本添加到头部 - 这意味着它将始终可用,您无需等待加载。

这意味着您可以随时针对已知的 div 元素调用按钮创建。如果它在模态中,同样适用,尽管您可能希望调整渲染目标。