Tips for modifying string in key-value pairs on the client side (example using Paypal checkout demo)

Looking to integrate an online payment system into my small online business, I have decided on using PayPal. Their solution is user-friendly and can be found here: https://developer.paypal.com/demo/checkout/#/pattern/client

However, I am facing an issue where the end user is restricted to only paying a fixed amount (currently set at 1 cent). I want to allow users to input their desired payment amount.

The provided code snippet from PayPal looks like this:

<div class='uk-section'>
            <!-- Set up a container element for the button -->
            <div id="paypal-button-container"></div>

            <!-- Include the PayPal JavaScript SDK -->
            <script src="https://www.paypal.com/sdk/js?client-id=sd=USD"></script>

            <script>
                // Render the PayPal button into #paypal-button-container
                paypal.Buttons({

                    // Set up the transaction
                    createOrder: function(data, actions) {
                        return actions.order.create({
                            purchase_units: [{
                                amount: {
                                    value: '0.01'
                                }
                            }]
                        });
                    },

                    // Finalize the transaction
                    onApprove: function(data, actions) {
                        return actions.order.capture().then(function(details) {
                            // Show a success message to the buyer
                            alert('Transaction completed by ' + details.payer.name.given_name + '!');
                        });
                    }


                }).render('#paypal-button-container');
            </script>
        </div>

The hardcoded value in the code prevents users from selecting their own payment amount easily. Any tips or solutions on how to make this dynamic would be highly appreciated.

Answer №1

Allow users to input the desired amount in a designated field, which will then be used for transferring funds via the PayPal API. Utilize HTML with an Input field to facilitate user interaction.

// Integrate the PayPal button within #paypal-button-container
// Leveraging REST API V2 CLIENT SIDE CODE using JavaScript and Jquery
paypal
  .Buttons({
    style: {
      layout: 'horizontal',
      color: 'gold',
      shape: 'pill',
      label: 'checkout',
      size: 'responsive',
      tagline: 'true',
    },
    // Setting up the transaction
    createOrder: function(data, actions) {
      $('#paypalmsg').hide();
      $('#transmsg').html('<b>'+'WAITING ON AUTHORIZATION...'+'</b>');
      $('#chkoutmsg').hide()
      return actions.order.create({
        purchase_units: [{
          description: 'GnG Order',
          amount: {
            value: cartTotal (HERE IS WHERE YOUR USER INPUT AMOUNT WOULD GO AS 
            A VARIABLE, you will have to make it a VAR using JavaScript or 
            Jquery, I.E. UserVal = $(USERSelect).val();)
          }
        }],
        application_context: {
          shipping_preference: 'NO_SHIPPING'
        }
      });
    },
    // Finalizing the transaction
    onApprove: function(data, actions) {
      return actions.order.get().then(function(orderDetails) {
        // Display success message to the buyer
        $('#transmsg').html('<b>' + 'AUTHORIZED...' + '</b>');
        $('#transmsg').append('<br>'+'Transaction completed by: ' + 
          orderDetails.payer.name.given_name +' '+ 
          orderDetails.payer.name.surname + '<br>' + "Order Id: " + 
          orderDetails.id + '<br>' + 'Status: ' + orderDetails.status+'!' + 
          '<br>'+ 'Thank You For Your Order'+ '<br>');
        
        if (orderDetails.status === "APPROVED") {
          // Implement necessary processing steps post transaction approval
          // Submit form after adding relevant data like transaction ID and status
          $('#transid').val(orderDetails.id);
          $('#orderstat').val(orderDetails.status);
          $('#orderform').submit();
        } 
      });

      if (details.error === 'INSTRUMENT_DECLINED') {
        // Handle case of declined transaction
        $('#transmsg').html('<b>' + 'TRANSACTION WAS DECLINED'+'</b>');
        $('#transmsg').fadeIn('slow').delay(3000).fadeOut('slow', function() {
          $('#paypalmsg').show();
          $('#chkoutmsg').show();
          $('#transmsg').empty();
        });
  
        return actions.restart();
      };
    },
    onCancel: function(data) {
      // Notify user about cancelled transaction
      $('#transmsg').html('<b>' + 'YOUR TRANSACTION WAS CANCELLED' + '</b>');
      $('#transmsg').fadeIn('slow').delay(3000).fadeOut('slow', function() {
        $('#paypalmsg').show();
        $('#chkoutmsg').show();
        $('#transmsg').empty();
      });
    }
  }).render('#paypal-button-container');

Feel free to reach out if you need further guidance.

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

Implementing dynamic component swapping in Vue 3 using components from another component

I currently have a display component called app-display, which contains a dynamic component inside (by default, it is set to app-empty): app.component('appDisplay', { template: `<component :is="currentComponent"></c ...

Incorporate a map (using leafletjs or Google Maps) as a subtle backdrop

I am currently working on a one-page website and I would like to include a map as a background behind the "contact" section. The map can be set to float, draggable, or positioned at the back. I have experience using both the Google Maps API and LeafletJS, ...

Creating a scheduled redirect button using JavaScript and another button to cancel it

I'm facing an issue with my code. When the first button is clicked, it redirects the user to a different URL after 10 seconds. However, I'm struggling to make the second button cancel the redirect if pressed before the 10 seconds are up. Despite ...

Sending arguments from an NPM script to a NodeJS script

In my main script (publish-all.js), I am trying to call the npm publish script of an Angular project. This Angular project also has a sub-script (publish.js) that performs various tasks (creating folders, copying files, moving folders...) after running ng ...

Encountering a problem with the persistent JavaScript script

I have implemented a plugin/code from on my website: Upon visiting my website and scrolling down, you will notice that the right hand sidebar also scrolls seamlessly. However, when at the top of the screen, clicking on any links becomes impossible unless ...

Showing Predefined Date on an HTML Form in an iOS Application

Is there a method to dynamically show the current date within the button that triggers the date picker in an HTML form on an iOS device? This is what currently appears: This is what I want it to automatically display: Below is the code I have implemente ...

Swap the text within the curly braces with the div element containing the specified text

I have an input and a textarea. Using Vue, I am currently setting the textarea's text to match what's in the input field. However, now I want to be able to change the color of specific text by typing something like {#123123}text{/#}. At this poin ...

The success $scope variable in AngularJs nested is not defined

I am encountering an issue with my nested $http.get and for loop. Why is it that my $scope variable ends up becoming undefined? $http.get('source') .success(function(res){ $scope.myObject = res; for (var ctr=0; ctr< $scope.myObject. ...

Is there a way to compare data before and after revalidation using useSWR?

With the use of Next.js and through the implementation of useSWR, data is fetched from an endpoint every 30 seconds using an automatic revalidation interval (https://swr.vercel.app/docs/revalidation#revalidate-on-interval). Within the retrieved data, there ...

Adding static files to your HTML page with node.js

This is not a question about using express.static() In my application, I have multiple pages that share the same JS and CSS dependencies. Instead of adding <script> or <link> tags to every single page, I'm looking for a way to include the ...

Display the JSON response received from a post request by showing each result in a separate div on the webpage

I am currently dealing with a post request to an API that returns Json data. I am looking for guidance on how to parse this json payload as it is in array format. My goal is to display each element of the array (result.payload) and have it displayed within ...

Tips for concealing validation errors in React Js when modifying the input field

I have recently started working with ReactJs, and I've implemented form validation using react-hook-form. After submitting the form, the errors are displayed correctly. However, the issue arises when I try to update the input fields as the error messa ...

Unable to fetch permissions for user:email via GitHub API

Currently, I am utilizing node-fetch to fetch an OAuth2 token from an OAuth2 GitHub App. The obtained token allows me to successfully retrieve user information from "https://api.github.com/user". However, I also require the email address, which necessitate ...

Consistent user interface experience for both Electron and browser users

Can the same index.html file be used by both an Electron process and a browser like Chrome? I have created an app that has its own Hapi server to handle HTTP requests to a database, which is working fine. However, when I try to serve the index.html file f ...

Encountering a deployment issue on Vercel while building with NextJS

I'm facing issues while attempting to deploy my Nextjs app on Vercel: Error occurred prerendering page "/". Read more: https://nextjs.org/docs/messages/prerender-error TypeError: (0 , react_development_.useState) is not a function or its ret ...

Unresolved promise rejection on Repl.it

I decided to add a basic leaderboard feature to my game on Repl.it, so I set up a node.js backend for it. Here's the code snippet for the backend: const express = require('express'); const Client = require('@replit/database'); cons ...

Trying out the fetch api with Jest in a React Component: A step-by-step guide

As a newcomer to test driven development, I stumbled upon a section that talked about testing/mocking a fetch API. However, I am facing issues while trying to write my own test. In order to practice this concept, I created a simple weather app where I atte ...

Vue.js application failing to display images fetched from the server

When I'm running my Vue.js app locally, the images are loading fine from the "src/assets" folder. However, when I deploy the app to Firebase, the images are not displaying and I get a 404 error. What could be causing this issue? I have tried using: ...

The jQuery code functions smoothly on computers, but experiences delays when running on an iPhone

I was working on my website and trying to add a div that sticks to the top of the browser when it scrolls out of view. I found a script that works well on desktop, but when testing it on iPhone, there is a slight delay before the div pops back up in the ri ...

Assign a value to a hash object based on a specific location stored within an array

I'm struggling to figure out how to retrieve the original JSON data when its structure is variable. var jsonData = { "parent": { "child": "foo" } }; fu ...