【问题标题】:How to render the paypal smart buttons through code?如何通过代码渲染paypal智能按钮?
【发布时间】:2022-01-04 21:49:42
【问题描述】:

这是渲染 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');

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

【问题讨论】:

    标签: javascript html paypal payment-gateway paypal-sandbox


    【解决方案1】:

    将脚本元素添加到 DOM 将导致它们异步加载,而不是及时让紧随其后的代码使用它们。您需要为脚本的onload 事件使用回调函数。这是一个执行此操作的示例帮助函数。

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

    【讨论】:

    • 谢谢,它成功了。但在我的一个页面上,它给出了这个错误:拒绝加载脚本'paypal.com/sdk/js?client-id=test&currency=USD',因为它违反了以下内容安全策略指令:“script-src'self''unsafe-eval'blob 你知道我是怎么做到的吗?可以修吗?
    • 更改该页面提供的 script-src HTTP 标头
    • 对不起,怎么办?
    • 取决于您提供该页面的方式
    • 我的代码位于页面上的用户脚本管理器上运行的用户脚本上。我不知道如何实现,你能告诉我吗?
    猜你喜欢
    • 1970-01-01
    • 2021-01-04
    • 1970-01-01
    • 2020-10-19
    • 2020-06-28
    • 2021-10-31
    • 2021-04-16
    • 2020-10-10
    • 2020-06-20
    相关资源
    最近更新 更多