gpt4 book ai didi

node.js - 如何在执行 Paypal 付款后重定向?

转载 作者:行者123 更新时间:2023-12-04 15:39:41 24 4
gpt4 key购买 nike

我按照有关如何使用 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() 之类的操作,但它不会重定向买家。

最佳答案

回答我自己的问题:在服务器端得到promise后,应该向客户端返回一个响应码,然后在客户端可以更改页面的位置。所以就我而言,它在服务器端看起来像这样:

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

关于node.js - 如何在执行 Paypal 付款后重定向?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58274818/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com