PayPal Checkout JavaScript:无需重定向或刷新页面即可更改货币

问题描述:

我们的网站有一个结账流程,如果重定向到 PayPal 进行审批,该流程就会中断.此外,我们有不同的货币,因此 PayPal SDK 不适用于我们的目的,因为您需要重新加载才能更改货币.

Our website has a checkout flow that would break if redirecting to PayPal for approval. Also we have different currencies so the PayPal SDK will not work for our purposes, since you need to reload to change the currency.

我们是否可以构建自己的结账集成,在新窗口中打开从 API 端收到的 URL,或者是我们使用他们的 SDK 的唯一选择?

Can we build our own checkout integration opening the URL received from the API side in a new window, or is our only option to use their SDK?

更改币种需要重新加载JS SDK,但不需要刷新页面.这是一个简短的香草 JS 函数和示例使用:

You need to reload the JS SDK to change the currency, but you don't need to refresh the page. Here's a short vanilla JS function and example use:

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

loadAsync('https://www.paypal.com/sdk/js?client-id=sb&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) {
            // Show a success message to the buyer
            alert('Transaction completed by ' + details.payer.name.given_name);
        });
    }

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

或者,paypal-js 软件包最近发布,并且执行的功能大致相同

Alternatively, the paypal-js package was recently released and does much the same thing

既然您提到了服务器端 API 集成,您将需要使用 https://developer.paypal.com/demo/checkout/#/pattern/server 并将其与服务器上的两条路由配对,一条用于创建订单",另一条用于捕获订单",记录在 https://developer.paypal.com/docs/business/checkout/server-side-api-calls/#server-side-api-calls .这些路由应该只输出 JSON 数据(没有 HTML 或文本)

Since you mentioned having a server-side API integration, you'll want to use the front-end code of https://developer.paypal.com/demo/checkout/#/pattern/server and pair it with two routes on your server, one for 'Create Order' and one for 'Capture Order', documented at https://developer.paypal.com/docs/business/checkout/server-side-api-calls/#server-side-api-calls . These routes should output only JSON data (no HTML or text)