我遵循了有关如何使用SDK API从PayPal(https://developer.paypal.com/docs/checkout/integrate/)添加智能支付按钮的说明。一切正常,除了付款后我无法重定向买方。
HTML页面中的JS代码看起来像这样:
paypal.Buttons({
createOrder: function (data, actions) {
return actions.order.create({
purchase_units: [{
amount: {
value: price
}
}]
});
},
onApprove: async function (data, actions) {
return actions.order.capture().then(function (details) {
alert('success!');
return fetch('/paypal-transaction-complete', {
method: 'post',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({
orderID: data.orderID,
})
});
});
}
}).render('#paypal-button-container');
在服务器端,我使用异步功能执行它,并通过使用箭头功能等待promise:
app.post('/paypal-transaction-complete', function (req, res) {
paypalRequestHandler.handleRequest(req, res)
.then(() => {
res.redirect('/'); // not working
}).catch(err => {
console.log(err);
res.sendStatus(500);
});
});
[我想知道为什么它不重定向,我可以做类似console.log()的事情,但它不会重定向买方。
要回答我自己的问题:在服务器端获得承诺后,应将响应代码返回给客户端,然后在客户端上可以更改页面的位置。因此,就我而言,在服务器端看起来像这样:
app.post('/paypal-transaction-complete', function (req, res) {
paypalRequestHandler.handleRequest(req, res)
.then(() => {
res.sendStatus(200);
}).catch(err => {
console.log(err);
res.sendStatus(500);
});
});
在客户端:
paypal.Buttons({
createOrder: function (data, actions) {
return actions.order.create({
purchase_units: [{
amount: {
value: price
}
}]
});
},
onApprove: async function (data, actions) {
return actions.order.capture().then(function (details) {
alert('success!');
const responsePromise = fetch('/paypal-transaction-complete', {
method: 'post',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({
orderID: data.orderID,
})
});
responsePromise.then(function (responseFromServer) {
if(responseFromServer.status === 200) {
location.href = 'success_page';
} else {
alert('smth went wrong');
location.href = '/';
})
}
});
});
}
}).render('#paypal-button-container');