javascript - 如何仅在交易完成后重定向?
问题描述
在我使用贝宝签出的示例代码中,有一个重定向请求到路由purchase/complete
。我想确保仅在发布请求/paypal/purchase/complete
完成后才请求此路由,以便我可以orderID
在服务器端获取创建并将其作为 get 参数传递给purchase/complete
路由,使其类似于purchase/complete?orderId=XXXX
. XXXX 这里将是收到的data.orderID
客户端:
// Render the PayPal button into #paypal-button-container
paypal.Buttons({
// Set up the transaction
createOrder: function(data, actions) {
var payableAmount = $("#finalAmountTotalOrders").attr("amountData");
return actions.order.create({
purchase_units: [{
amount: {
value: payableAmount
}
}]
});
},
// Finalize the transaction
onApprove: function(data, actions) {
return actions.order.capture().then(function(details) {
//will redirect user to custom page change values as desired
window.location.replace("/purchase/complete");
// Call your server to save the transaction
return fetch('/paypal/purchase/complete', {
method: 'post',
headers: {
'content-type': 'application/json',
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
body: JSON.stringify({
orderID: data.orderID,
details: details
})
});
});
}
}).render('#paypal-button-container');
编辑:
我想这样做的原因是,虽然我能够创建一个订单并将其存储在我的数据库中,一旦/paypal/purchase/complete
发出发布请求,我不确定什么时候我会做一些事情,比如通过电子邮件向客户和商家发送我刚刚创建的订单(数据库行)的 ID。尝试在 post 请求中执行此操作会引发错误,因此如果我可以在/purchase/complete
路线上获取 ID,我可以查询数据库并获取订单详细信息并通过电子邮件发送。任何其他方法都会对我有用。
解决方案
我发现您可以.then
在第一个块之后立即链接另一个actions.order.capture().then
块
onApprove: function(data, actions) {
return actions.order.capture().then(function(details) {
//will redirect user to custom page change values as desired
// Call your server to save the transaction
return fetch('/paypal/purchase/complete', {
method: 'post',
headers: {
'content-type': 'application/json',
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
body: JSON.stringify({
orderID: data.orderID,
details:details
})
}).then((response) => {
window.location.replace("/purchase/complete?paypalOrderId="+data.orderID);
});
});
}
推荐阅读
- python - 在BeautifulSoup抓取之后从Python列表中提取数据并创建Pandas表
- r - 预测锯齿中的新值(混合模型)
- r - 错误后在 R 中改进我的热图。(速查图)
- javascript - 在语义 UI 中的图像上添加文本
- unreal-engine4 - Hololens 2 + Unreal Packaging 仅在设备上失败
- git - 使用 Github 和 VS Code 检查之前的提交
- kubernetes - Istio 无法将请求路由到具有不同目标端口的工作负载
- amazon-web-services - 将 S3 存储桶从一个 AWS 账户复制到另一个 AWS 账户在传输过程中是否安全?
- azure - 每小时对 API 进行 REST 调用并将结果保存到 Azure SQL
- java - Android应用开发中的条件弹出消息