PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, November 11, 2022

[FIXED] How to render the paypal smart buttons through code?

 November 11, 2022     html, javascript, payment-gateway, paypal, paypal-sandbox     No comments   

Issue

This is the code to render the paypal smart buttons:

<script src="https://www.paypal.com/sdk/js?client-id=test"></script> 
<script>paypal.Buttons().render('body');</script>

But I want to render them through code, so I tried to do this:

document.body.innerHTML='<script src="https://www.paypal.com/sdk/js?client-id=test"></script>';
paypal.Buttons().render('body');

But it didn't work, how do I achieve this?


Solution

Adding script elements to the DOM will cause them to load asynchronously, not in time for code that immediately follows to make use of them. You need to use a callback function for the script's onload event. Here is an example helper function that does so.

//Helper function

function loadAsync(url, callback) {
  var s = document.createElement('script');
  s.setAttribute('src', url); s.onload = callback;
  document.head.insertBefore(s, document.head.firstElementChild);
}

// Usage -- callback is inlined here, but could be a named function

loadAsync('https://www.paypal.com/sdk/js?client-id=test&currency=USD', function() {
  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) {
           //...
        });
    }

  }).render('body');
});


Answered By - Preston PHX
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing