How to integrate PayPal Smart Payment buttons in NuxtJs?

Viewed 1381

My current working solution.

<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>

In modals, I had to load the script again.

How to load this Paypal script globally in the NuxtJs application on components or pages level?

3 Answers

I had the same integration in my project, and import the script in my page:

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

Then put PayPal's .render() method in the mounted().

You can always add the script to the head, in the SPA index.htm - this means it will always be available and you do not need to wait for the load.

This means you can call the button creation against a known div element anytime. If it is in a modal, the same would apply, although you might wish to adjust the render target then.

you can also put the script in the script array in nuxt.config.js, by doing this the script is made available globally in your application. Like this:

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