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

How to integrate PayPal Smart Payment buttons in NuxtJs?

我目前的工作解决方案。

<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 脚本?

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

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

然后把PayPal的.render()方法放在mounted().

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

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

您还可以将脚本放入 nuxt.config.js 中的脚本数组中,这样脚本就可以在您的应用程序中全局使用。 像这样:

script: [
      {
        src: 'ttps://www.paypal.com/sdk/js?client-id=<CLIENT_ID>',
        async: true
      }
    ]