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

The Nuxt image keeps disappearing every time I navigate to a new page

Whenever I have an image displayed on my Nuxt page and then navigate away from it, the image breaks and I can't figure out why. This is what my code looks like: <img :src="baseUrl + 'storage/'+ front.featured_image" alt="p ...

Success/Fail Page for Form Redirect

I've been struggling to figure out how to redirect my form to a success or fail page. I've scoured the internet for solutions, looking into traditional form redirects and even JavaScript onClick redirects. Can someone guide me on adding a redirec ...

What could be causing the slow build time for npm run serve on a Vue.js project?

My Vue.js project was running smoothly until about an hour ago when I noticed that it is now taking a very long time to build. Specifically, it gets stuck at 32% for more than 5 minutes. Does anyone have any suggestions on how to fix this issue? I'm n ...

Replace specific text with a span element around it?

I am working with the following HTML code: <p class="get">This is some content.</p>. My goal is to modify it so that it looks like this: <p class="get">This is <span>some</span> content.</p>. To achieve this, I have ...

What is the best way to showcase a chart using jquery?

Is there a way to incorporate trendlines or target lines in highcharts similar to fusion chart? I have been able to draw them successfully in fusion charts. Check out this fiddle link: http://jsfiddle.net/Tu57h/139/ I attempted to recreate the same in hi ...

Calculating the number of rows in a dynamic jQuery table

I have a table structured like this: <div class="row"> <input type="button" id="btnAddGatePass" value="Add Gate Pass Requester" /> <div class="table-responsive"> <table id="gatePass" class="table table-striped table-ho ...

Is there a way to insert a value into the input field using JQuery or JavaScript?

After reading my previous post on posting values into an input box, a commenter suggested using JQuery or Javascript. For more code and information, please refer to the link provided above. <label>Date</label>:&nbsp&nbsp <input sty ...

Determine the index of a specific character within a string using a "for of" loop

How can I obtain the position of a character in a string when it has been separated programmatically using a for...of loop? For instance, if I wish to display the position of each character in a string with the following loop: for (let c of myString) { ...

Tips on manually refreshing AngularJS view using ControllerAs syntax?

As I work on creating a user-friendly dashboard with widgets that can be sorted, docked, and floated, I encountered an issue. The controls I am using generate floating widgets as HTML at the bottom of the DOM, outside the controller scope where they were c ...

The functionality of a div element appears to be impaired when attempting to include a newline character

I have a div element <div id="testResult" style="padding-left: 120px;"> My goal is to include text with newline character '\n' inside the div. However, when I view my html page, the text does not respect the newline character. $( ...

Sending an array input to PHP

I am having trouble sending an array input to PHP via JavaScript. The posted array does not seem to be showing up in the controller when I try to print it. Here is the relevant code snippet: submitHandler: function(form) { $('input[name="val_prof ...

Place the retrieved data from the API directly into the editor

I've integrated the LineControl Editor into my app and everything is functioning perfectly, except for when I attempt to insert text into the editor. Here's the link to the LineControl GitHub page: https://github.com/suyati/line-control/wiki Fo ...

Converting UTC Date Time to Full Date Using ES6

Is there a way to transform the date 2021-01-10 12:47:29 UTC into January 10, 2021? I've been attempting to achieve this using moment.js code below, but it seems to be functioning in all browsers except Safari. {moment(video?.createdAt).format(' ...

How to remove the horizontal scrollbar from material-ui's Drawer element

My drawer is displaying a horizontal scroll, despite my efforts to prevent it. I've tried adjusting the max-width and width settings in Menu and MenuItems, as well as using box-sizing: border-box. I also attempted setting overflow: hidden on the Drawe ...

Click on the form to initiate when the action is set to "javascript:void(0)"

I am working on an HTML step form that needs to be submitted after passing validation and ensuring all fields are filled. The form currently has an action controller called register.php, but also includes action="javascript:void(0);" in the HTML form. What ...

In JavaScript, what is the best way to target the initial option element in HTML?

As a newcomer to javascript, I'm wondering how to target the first option in the HTML <option value="">Choose an image...</option> without altering the HTML itself? My thought is: memeForm.getElementById('meme-image').getElement ...

Transferring an array from PHP to JavaScript via an Ajax response

Welcome to my first post on stackoverflow. I usually find answers from existing posts, but this time I'm facing a problem that none of the suggested solutions have been able to fix. Currently, I have a JavaScript function that makes an AJAX request t ...

Executing functions and setting element values upon loading in Javascript

I am currently working on updating a small Javascript function that assigns an active class to the parent <div> of a group of radio buttons when the page loads and also when there's a change event. The existing function looks like this: functi ...

Is there a way to identify the specific button that was clicked within an Angular Material dialog?

import {Component, Inject} from '@angular/core'; import {MdDialog, MdDialogRef, MD_DIALOG_DATA} from '@angular/material'; /** * @title Dialog Overview Example with Angular Material */ @Component({ selector: 'dialog-overview-ex ...

In order to ensure a valid JSON for parsing in JavaScript, one must reverse the usage of single quotes and double quotes. This adjustment

Received an API response structured like this: [{'name': 'men', 'slug': 'men'}, {'name': 'women', 'slug': 'women'}] After stringifying: const data = JSON.stringify(resp) " ...