I encountered an error stating that "paypal is not defined" while configuring PayPal Checkout with vue.js

Recently, I created a component called PaypalButton.vue. I followed the instructions provided here to implement the button: https://developer.paypal.com/docs/checkout/integrate/#

<template>
  <div>
    <div id="paypal-button-container"></div>
  </div>
</template>
    <script src="https://www.paypal.com/sdk/js?client-id=AZy2xQtNMcibA3BneS56WHoq1oqLhWdM7nsP3pwS02lr_1TOpC9Lnpp-IGbZQDS8K_xvMH5ssRmNPoDT" >
      // Required. Replace SB_CLIENT_ID with your sandbox client ID.
    </script>


<script>
import JQuery from 'jquery'
let $ = JQuery

var checkExist = setInterval(function() {
   if ($('#paypal-button-container').length) {
      console.log("Exists!");
      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("#paypal-button-container");
//This function displays Smart Payment Buttons on your web page.

      clearInterval(checkExist);
   }
}, 100); // check every 100ms


export default {
  data: () => ({
    //
  })
};
</script>



However, I encountered an error. Does anyone have an idea about what could be causing this issue? I even tried importing the Paypal script in index.html but still faced the same problem.

https://i.sstatic.net/ZB0ln.png

Answer №1

When faced with a similar issue of the " 'script' is not defined" error, I found a solution by utilizing a script for a similar purpose. Hopefully, my approach can assist others experiencing the same problem. The key was to utilize the "window" scope and create a new variable to access Vue elements within the "onload" function.

<template>
  <div>
    <h2>Custom Payment</h2>
    <div id="custom-payment"></div>
    <br />
    <button id="pay" disabled>Process Payment</button>
  </div>
</template>
<script>
import { mapActions } from "vuex";
export default {
  name: "Payment",
  methods: {
    ...mapActions(["aVueAction"])
  },
  created() {
    let customScript = document.createElement("script");
    let self = this;
    customScript.onload = () => {
      // call to Vuex action.
      self.aVueAction();
      // call to custom script function
      window.customPayment.customScriptFunction();
    };
    // customScript.async = true;
    customScript.setAttribute(
      "src",
     "https://api.custompayment.com/rest/v1/custom.js"
    );
    document.body.appendChild(customScript);
  }
};
</script>

This solution was tested with Vue 2.6.

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

Having trouble importing my function component into a router in reactjs. Need some guidance on how to properly set it up

I am working on a Slider component function called export default Slider. In my App.js file, I have the following code: function App() { return ( <Router> <Routes> <Route exact path='/' element={<Home />} /> ...

Using Vue.js to set both v-model and v-bind:value on one input element

I have a React component that has a form for submitting user information. The main issue I'm facing is setting a default value in the input field. When the page loads, I want the input field to display the user's existing email address by defaul ...

What is the best way to insert an <image> tag into the SVG DOM?

Currently, I am facing an issue with adding a background image to the generated SVG DOM in my web page. The user interacts by drawing an SVG doodle on top of a jpg image using Raphael. After the user is done with their drawing, I want to enable them to sa ...

The 3-way data binding in angularFire does not update a function

My issue involves a firebaseObject (MyFirebaseService.getCurrentUser()) being bound to $scope.user. Once successfully bound, I iterate through the object to check if it contains an "associatedCourseId" equal to a specific value ($stateParams.id). If it doe ...

Displaying sorted objects from Angular serviceIn Angular 8, let's retrieve an object

In my Angular8 application, I am running a query that fetches a data object. My goal is to sort this data object based on the order value and then display each product item on the browser. For example, here is an example of how the output should look like ...

Adding the most recent version of jquery causes the webpage to malfunction

Currently, I am facing a challenge on a website that has an outdated version of jQuery (1.7.2) included in the header. In order to use a plugin that requires the latest version of jQuery, I tried linking the newer version (2.1.3) in the footer. However, j ...

Choose a navigation item from the list containing a nested span element

I've implemented selectnav from GitHub and it's functioning perfectly. However, my menu consists of list items with a description span inside each one, resulting in menu items structured as shown below: <li><a href="somelink.html">Ch ...

What could be the reason for the list being undefined even though I explicitly defined it within the <script setup> section of my Nuxt 3 Project?

I am currently working on a Nuxt 3 Project and have created a component that generates a variable amount of elements. When calling the element, it is passed an array as a parameter. In the script setup, I define this array as 'list' and intend to ...

Encountering a 500 error in Angular while utilizing forkJoin for calling API services

In my Angular 7 project, I have implemented a call in the ngOnInit method to two different API routes to fetch some data using forkJoin. Here is how I have set it up: ngOnInit() { debugger this.route.params.pipe( switchMap(params => for ...

Reset input field when checkbox is deselected in React

How can I bind value={this.state.grade} to clear the input text when the checkbox is unchecked? The issue is that I am unable to modify the input field. If I were to use defaultValue, how would I go about clearing the input box? http://jsbin.com/lukewahud ...

Receiving undefined properties in functional React components

Is it possible to pass the {requests} prop to the RequestRow component correctly, especially after the setRequests function is executed? The issue seems to be that when requests are initialized as undefined initially and then set with an asynchronously cal ...

Validate the array with AJAX and display an error message

Need assistance validating arrays using FormRequest validation. The error message for the 'name' field can be accessed as data.responseJSON.error.name[0] and displayed to the user. error: function(data, xhr, errmsg, err){ console.log(" ...

Need a jQuery function that updates the 'id' after clicking on a specific div? Here's how to do it!

I need help simplifying my current situation. Step 1: I want to increment the variable "count" by 1 every time a specific div is clicked. Step 2: After updating "count", I want to utilize it in another function. This function involves copying the value f ...

Having difficulty with printing a particular div

I need help with printing a specific div containing checkboxes using jQuery. The checkboxes are initially checked based on data from a database, but when I try to print the div, the checkboxes remain unchecked in the print view. Below is the code snippet ...

Packages and Digital Routes

Currently in the process of creating a new website utilizing angular, MVC, and Web API. The plan is to keep the static content (js, css, images, etc) in Site A, the MVC site in Site B, and the api in Site C. These will be separate sites, not virtual direct ...

Incorporating Sentry DSN and tracking codes within vite/Vue applications

What is the most effective method for embedding the Sentry DSN or other tracking codes in Vite/Vue front-end code? From my perspective, it seems like it can either be integrated into the transpiled JS during build time (and included in the Docker image) o ...

Adapting imports in Typescript for seamless npm distribution

Currently, I'm facing an issue with module resolution while compiling my NPM package written in Typescript for publishing. In my project, I've been using non-relative imports to avoid the hassle of excessive ../../../. However, according to TypeS ...

Why do React JS array objects reset when being updated?

I am working with an array of objects that contain IDs and prices. Whenever the onClick event is triggered, it updates the price of a specific object. However, upon clicking the event again, I noticed that the previously updated item's price gets rese ...

Avoid working on the script for the element in the partial view during the event

In my index.cshtml view, I have a script that triggers an AJAX call when the SearchingManagerId2 element is changed. $("#SearchingManagerId2").on("change", function () { var valueForSearch = $(this).val(); $.ajax({ ...

Loading Images in Advance with jQuery, Native JavaScript, and CSS

After successfully implementing a method to hover on a small image and load an additional image to the right side of the page, I am now looking to enhance user experience by preloading images. Is there a way to preload an image using JQuery, allowing it t ...