繁体   English   中英

如何通过代码渲染 paypal 智能按钮?

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

这是呈现 paypal 智能按钮的代码:

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

但我想通过代码呈现它们,所以我尝试这样做:

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

但它没有用,我该如何实现呢?

将脚本元素添加到 DOM 将导致它们异步加载,而不是及时为紧随其后的代码使用它们。 您需要为脚本的onload事件使用回调 function。 这是一个示例助手 function 这样做。

//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');
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM