Mastering the Integration of Paypal Checkout with Vue.JS 3

I am currently working on implementing Paypal Checkout with Vue.JS 3 (using the loader)

So far, this is what I have achieved:

setPaypal() {
        const script = document.createElement('script');
        script.src = 'https://www.paypal.com/sdk/js?client-id=AdlvqGHWrrwVpGXreZuf5VHBXjIeUWGLHBJmDzbI44Ib2w1MMN7P-UJysCHFb_W7BWTvpz0ofji0SiYB';
        document.body.appendChild(script);
        script.addEventListener('load', this.setLoaded())
    }

This setPaypal() function is invoked in the mounted() lifecycle hook and adds the script tag to my page.

setLoaded() {
        window.paypal.Buttons({
            createOrder: (actions) => {
                return actions.order.create({
                    purchase_units: [
                        {
                            description: this.prestation.courtedescription,
                            amount: {
                                currency_code: "EUR",
                                value: this.total
                            }
                        }
                    ]
                });
            },
            onApprove: async () => {
                this.paidFor = true;
                this.loading = false;
            },
            onError: err => {
                console.log(err)
            }
        })
        .render(this.$refs.paypal)
    }

This is the setLoaded() function which is executed when the script is fully loaded.

However, it seems that window.paypal is undefined

I followed the official documentation instructions, but encountered issues. They recommend:

const PayPalButton = paypal.Buttons.driver("vue", window.Vue);

Yet, paypal is not defined

For more details, refer to the official documentation

  1. Add the SDK
    <script src="https://www.paypal.com/sdk/js?client-id=YOUR_CLIENT_ID"></script>
  2. Vue integration
<div id="container">
  <app></app>
</div>
<script>
  const PayPalButton = paypal.Buttons.driver("vue", window.Vue);
  Vue.component("app", {
    template: `
      <paypal-buttons :on-approve="onApprove" :create-order="createOrder" />
    `,
    components: {
      "paypal-buttons": PayPalButton,
    },
    computed: {
      createOrder: function () {
        return (data, actions) => {
          return actions.order.create({
            purchase_units: [
              {
                amount: {
                  value: "10",
                },
              },
            ],
          });
        }
      },
      onApprove: function () {
        return (data, actions) => {
          return actions.order.capture();
        }
      },
    },
  });
  const vm = new Vue({
    el: "#container",
  });
</script>

Answer №1

For your setPaypal() function, it's recommended to make this adjustment:

script.addEventListener('load', this.setLoaded())

Instead, opt for the following approach:

script.addEventListener('load', () => this.setLoaded())

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JavaScript makes it possible to access subnodes in XML by utilizing specific methods and

I am looking to utilize javascript to extract data from an XML file that has been loaded into a webpage. Below is the XML file (a.xml) that I am working with. a.xml <?xml version="1.0"?> <Step rID="T6"> <Obj ><![CDATA[Get Data Ta ...

retrieving the site's favicon icon

Currently, I am attempting to extract favicons from website URLs using the HtmlAgilityPack library. While I have been successful in retrieving some favicons, there are still some that remain elusive. I suspect that the inconsistency lies in the implementat ...

Manipulate the timing of css animations using javascript

I am currently working with a progress bar that I need to manipulate using JavaScript. The demo of the progress bar has a smooth animation, but when I try to adjust its width using jQuery $($0).css({'width': '80%'}), the animation disap ...

Printing the string only if the value is absent or null

I am currently working on a project that involves scraping a name database and displaying the values based on certain conditions defined in the code. However, when an element in the data is null or not present, I want to display "-" instead of showing "n ...

Adjust the styling of elements when they are positioned 300 pixels from the top of the viewport

Hey there, I don't have much experience with JavaScript, but I gave it a shot. I managed to create a script that changes the properties of an element based on its position relative to the viewport of the browser. It took me a couple of days to get it ...

In Vue.js, it is not possible to modify a component variable within a callback function

I have implemented a custom Login.vue component using vue.js to allow users to log in to my application through AWS Cognito. The authentication process is handled by the ___.authenticateUser() method, which initiates a session with Cognito. Below is the co ...

Which types of characters am I allowed to include in an HTTP response body while using NodeJS and Express?

I am currently developing a node express app that responds to an AJAX post from the client browser. I am curious about what characters would be considered invalid to include in the HTTP response body. My response header specifies the use of charset=utf-8, ...

Obtain the value of the selected item from a dropdown list that has been dynamically populated

Hello, I have successfully populated a list of items into an asp:DropDownList using JavaScript. Here is the code snippet: if (document.getElementById("<%=gdview.ClientID %>")!=null) { var rows = document.getElementById("<%=gdview.ClientI ...

Utilizing ng-if within ng-repeat for dynamically generated option tags in HTML and AngularJS

I am using AngularJS to create a dropdown menu with select and option tags. The menu is referencing a model and looks like this: <select id="edit-location" class="" ng-model="packageLoc"> <option ng-repeat="x in loc" value="{{ x.locationId }} ...

Guide on how to swap a string with a component in Vue

I have a string that contains placeholders ### and I want to replace them with values from an array. I created a component, but I'm not sure how to incorporate it into the string since the number of placeholders can vary. For instance, if there are 2 ...

Is it possible to use CSS to create a gap between the cursor and the placeholder text within an input field?

Could you please assist me with a bug I have encountered on an older version of Firefox for OSX (37.0.2)? I have included a screenshot of the issue here: https://i.sstatic.net/dzK0G.png Is there a way to use css to move the first character of the placehol ...

Update the image path in Vue depending on the size of the screen

I'm looking to dynamically change the image src based on screen size in my Nuxt project. The current code I have is as follows: <div v-for="(item, index) in aside" :key="index""> <img :src="item.svgIconDark.fi ...

"Using Vue to compute the sum or calculate values within an array - a step-by

Having a data array like this "item_tabel": [ { "method": { "select_method": 6, }, "innovation": { "select_innovation": 2, }, } ], How do I calculate the sum? This i ...

Verify the presence of a GET parameter in the URL

Working on a simple log in form for my website using Jade and ExpressJS. Everything is functioning correctly, except for one issue - handling incorrect log in details. When users input wrong information, they are redirected back to the log in page with a p ...

Unique Timer with progress bar that resets only when the page is refreshed

We're currently developing a screening tool with a section for questions. Beneath each question, there is a progress bar displaying the time remaining. However, the progress bar only updates when the page is reloaded. Here is the code snippet: publi ...

What is the reason that the variable is not accessible after the switch block?

While working on my code, I encountered a dilemma. I needed to print the value of the 'text' variable after a switch block. However, I mistakenly did not include an expression in the switch statement which caused it to skip the default case and t ...

Learn how to make a mesh in Three Js React refract its environment while keeping the background hidden from the camera

I've been grappling with this challenge for quite some time now, so any assistance would be highly valued! My aim is to create the illusion of an image being confined within a mesh structure. My initial idea was to utilize a mesh with defined thickne ...

Unable to get Mongoose's Required field to work in conjunction with Enum validation

Encountering issues with Mongoose Required true and Enum validation when using updateone await MonthlyTarget.updateOne({website: req.body.website, year: req.body.year, month: req.body.month}, req.body, {upsert: true}); Model 'use strict'; import ...

Shrink video size directly in the browser using JavaScript and HTML5 before storing or sharing it

Is there an optimal method for resizing and potentially trimming a video using Javascript, HTML5 or Webassembly in modern browsers before saving it to the Filesystem? What is the most effective way to edit a video within the browser? Here are some differe ...

Leveraging the power of $lookup and $mergeObjects in aggregation

I'm looking to join a collection. Previously, I used only lookup to get separated fields that are joined, but now I need the results similar to MySQL join. I have tried using $lookup and $mergeObjects for this action, but they are not working well. H ...