问题描述
我正在为非营利组织构建捐赠表格,并且正在努力更新发送到我的Node.js Stripe后端的更新付款金额。
前端是React,我正在使用useEffect()钩子创建我的paymentIntent。看来,使用新的Stripe API,返回clientSecret所需的金额。否则,我想在用户选择捐赠金额之后创建paymentIntent(就像我对类似实现所做的那样)。
我正在使用方法“ stripe.paymentIntents.update()”来更新金额。这显示在console.log中已更新,但未更新发送到Stripe的paymentIntent。
我该如何更新要发送的PaymentIntent以确认ConfirmCardPayment()?
server.js
app.post("/create-payment-intent",async (req,res) => {
let amount = req.body.amount;
const name = req.body.name;
const options = {
description: 'Teton Valley Aquatics Donation',amount,currency: "USD",name: name,};
console.log(req.body.amount) //returns my default amount {1000}
try {
const paymentIntent = await stripe.paymentIntents.create(options);
res.json(paymentIntent);
}
catch (err) {
res.json(err);
}
app.post("/create-payment-intent/update-amount",res) => {
const amount = req.body;
console.log(req.body) //returns {amount: 25}
try {
const paymentIntent = await stripe.paymentIntents.update(amount,{
amount,});
console.log(`Updated amount: ${amount}`);
res.json(paymentIntent);
}
catch (err) {
res.json(err)
}
})
});
CheckoutForm.jsx
useEffect(() => {
api
.createPaymentIntent({
amount
})
.then((clientSecret) => {
setClientSecret(clientSecret);
})
.catch((err) => {
setError(err.message);
});
console.log(`Amount: ${amount}`)
},[]);
const handleSubmit = async (ev) => {
ev.preventDefault();
setProcessing(true);
api
.updatePaymentIntent({
amount,})
.catch((err) => {
setError(err.message);
});
const payload = await stripe.confirmCardPayment(clientSecret,{
payment_method: {
card: elements.getElement(CardElement),billing_details: {
name: ev.target.name.value,email: ev.target.email.value
},},});
if (payload.error) {
setError(`Payment Failed: ${payload.error.message}`);
setProcessing(false);
console.log("[error]",payload.error);
} else {
setError(null);
setSucceeded(true);
setProcessing(false);
setMetadata(payload.paymentIntent);
console.log("[PaymentIntent]",payload.paymentIntent);
}
};
api函数
const createPaymentIntent = options => {
return window
.fetch(`http://localhost:4242/create-payment-intent`,{
method: "POST",headers: {
"Content-Type": "application/json"
},body: JSON.stringify(options)
})
.then(res => {
if (res.status === 200) {
return res.json();
} else {
return null;
}
})
.then(data => {
if (!data || data.error) {
console.log("API error:",{ data });
throw new Error("PaymentIntent API Error");
} else {
return data.client_secret;
}
});
};
const updatePaymentIntent = options => {
return window
.fetch(`http://localhost:4242/create-payment-intent/update-amount`,{ data });
throw new Error("PaymentIntent API Error");
} else {
return data.client_secret;
}
});
}
解决方法
update
的第一个参数应该是付款意向ID。看来您有错别字/错误,将amount
放入了两次:
const paymentIntent = await stripe.paymentIntents.update(**amount**,{
amount,});
应为:
const paymentIntent = await stripe.paymentIntents.update(**paymentIntentId**,});
在此处查看代码段:https://stripe.com/docs/api/payment_intents/update?lang=node