我想為我的網站制作一個捐贈頁面,這樣人們就可以捐贈和接收捐贈禮物,我發現了 PayPal API,然后在客戶端上會出現按鈕,如果您點擊它們,您可以使用 PayPal 或信用卡付款,但我的問題是我還沒有弄清楚如何在服務器上處理成功的付款。
在客戶端上,我可以通過添加.then(details)after來處理成功的付款return actions.order.capture(),但是對我來說處理客戶端上的東西太不安全了。
客戶端代碼:
paypal.Buttons({
createOrder: function () {
return fetch('/create-order', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
items: [{
id: 2,
quantity: 1
}],
})
}).then((res) => {
if (res.ok) return res.json()
return res.json().then(json => Promise.reject(json))
}).then(({ id }) => {
return id
}).catch((err) => {
console.error(err)
})
},
onApprove: function (data, actions) {
return actions.order.capture().then((details) => {
alert('Transaction completed by ' details.payer.name.given_name)
console.log(details)
})
},
}).render("#paypal")
服務器代碼:
// Add a little percentage for the USD to EUR conversition rate
const storeItems = new Map([
[1, { price: Math.round(50 * 1.1), name: '50€ Donation', }],
[2, { price: Math.round(25 * 1.1), name: '25€ Donation' }],
[3, { price: Math.round(10 * 1.1), name: '10€ Donation' }],
[4, { price: Math.round(5 * 1.1), name: '5€ Donation' }],
])
app.get('/', (req, res) => {
res.render('index', { clientId: process.env.PAYPAL_CLIENT_ID })
})
app.post('/create-order', async (req, res) => {
const request = new paypal.orders.OrdersCreateRequest()
const total = req.body.items.reduce((sum, item) => {
return sum storeItems.get(item.id).price * item.quantity
}, 0)
request.prefer('return=representation')
request.requestBody({
intent: "CAPTURE",
purchase_units: [
{
amount: {
currency_code: "USD",
value: total,
breakdown: {
item_total: {
currency_code: "USD",
value: total,
},
},
},
items: req.body.items.map(item => {
const storeItem = storeItems.get(item.id)
return {
name: storeItem.name,
unit_amount: {
currency_code: "USD",
value: storeItem.price,
},
quantity: item.quantity,
}
}),
},
],
})
try {
const order = await paypalClient.execute(request)
res.json({ id: order.result.id })
} catch (err) {
res.status(500).json({ error: err.message })
console.error(err.message)
}
})
uj5u.com熱心網友回復:
actions.order.capture() 和 actions.order.create() 都是客戶端代碼。
請勿將任一功能用于服務器集成。創建和捕獲都應該在同一個地方完成。
您的onApprove函式需要呼叫服務器上的路由來執行捕獲。在解釋服務器集成的“添加和修改代碼”部分中,設定標準支付中有詳細資訊和示例代碼的鏈接。特別是這個演示模式的鏈接,它顯示了在服務器上捕獲時正確的客戶端錯誤處理。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/350388.html
標籤:javascript 节点.js 贝宝
