Ale*_*ñez 5 javascript paypal paypal-subscriptions paypal-buttons
当尝试将 PayPal 订阅按钮和用于一次性付款的捕获/订购按钮添加到同一页面时,您需要使用不同的参数导入 PayPal 的 Javascript 文件两次(intent=subscription&vault=true而不是仅导入intent=capture)
如果您尝试导入两个按钮将不会呈现。
如何在同一页面上同时显示 PayPal 订阅和 PayPal 一次性付款智能按钮?
重现问题的示例代码:
<script src="https://www.paypal.com/sdk/js?client-id={{YOUR CLIENT ID}}¤cy=USD"></script>
<script src="https://www.paypal.com/sdk/js?client-id={{YOUR CLIENT ID}}¤cy=USD&intent=subscription&vault=true"></script>
<div id="some-container"></div>
<div id="some-subscription-container"></div>
<script>
paypal.Buttons().render('#some-container');
paypal.Buttons().render('#some-subscription-container');
</script>
Run Code Online (Sandbox Code Playgroud)
经过几个小时的努力,我找到了一个解决方案,该解决方案非常适合在同一页面上显示两个按钮(甚至每个按钮中的多个按钮),并希望分享它,这样我就可以减轻其他人的痛苦。
第一个问题是如何使用不同的参数同时导入两个 PayPal Javascript 文件。解决方案是data-namespace在脚本标签上使用如下所示:
<script src="https://www.paypal.com/sdk/js?client-id={{YOUR CLIENT ID}}¤cy=USD" data-namespace="paypal_one_time"></script>
<script src="https://www.paypal.com/sdk/js?client-id={{YOUR CLIENT ID}}¤cy=USD&intent=subscription&vault=true" data-namespace="paypal_subscriptions"></script>
Run Code Online (Sandbox Code Playgroud)
现在要呈现按钮,您需要使用这些命名空间而不是变量paypal。例如:
paypal_one_time.Buttons().render('#some-container');
paypal_subscriptions.Buttons().render('#some-subscription-container');
Run Code Online (Sandbox Code Playgroud)
您会发现的最后一个问题是,单击一次性付款按钮会破坏订阅按钮。如果您尝试点击一次性按钮后的订阅,它将不起作用(说您没有足够的授权并关闭弹出窗口)。
要解决此问题,最简单的方法是每次一次性付款流程完成时在页面上重新呈现订阅按钮(在一次性付款按钮的 Buttons() 选项内的 onApproved/onCancelled/onError 方法中) 。
onApprove: function(data, actions) {
return actions.order.capture().then(function(orderData) {
// process your one time payment
// re-render subscription buttons because now they are broken!
reRenderSubscriptionButtons();
});
},
onCancel: function(data) {
reRenderSubscriptionButtons();
},
Run Code Online (Sandbox Code Playgroud)
对于 one_time_button 中的这些事件,只需调用执行以下操作的函数即可:
function reRenderSubscriptionButtons() {
// remove everything from the container
document.getElementById("some-subscription-container").innerHTML='';
// render the subscription buttons again (you can call the same function you use to render it the first time too)
paypal_subscriptions.Buttons().render('#some-subscription-container');
}
Run Code Online (Sandbox Code Playgroud)