React+Node.js集成Stripe订阅成功但无确认提示问题求助
React集成Stripe订阅异常:付款成功但前端无确认提示、请求Pending
问题现象
付款已在Stripe控制台显示成功,但前端无法触发确认提示,Chrome网络面板中create-sub请求持续处于pending状态,后端无报错日志,已确认ClientSecret和SubscriptionId在后端正常生成。
前端代码
const createSubscription = async (e) => { try { e.preventDefault(); const {error, paymentMethod} = await stripe.createPaymentMethod({ type: "card", card: elements.getElement(CardElement), billing_details: { name, email, }, }); const response = await axios.post("http://localhost:8800/create-sub", { paymentMethod: paymentMethod.id, name, email, priceId, }).then((res) => res.json) console.log('------------------'); const confirmPayment = await stripe.confirmCardPayment( response.clientSecret ); if (confirmPayment.error) { alert(confirmPayment.error.message); } else { alert("Success! Check your email for the invoice."); } } catch (error) { console.log(error); }
后端代码
app.post("/create-sub", (req, res) => { createSubscription(req); }); async function createSubscription(reqq){ let { paymentMethod, name, email, priceIdxx } = reqq.body const customer = await stripe.customers.create({ name: name, email: email, payment_method: paymentMethod, invoice_settings: { default_payment_method: paymentMethod } }); const priceId = 'price_1LmWAuEmOCxfDzgdORMhUQZD'; const subscription = await stripe.subscriptions.create({ customer: customer.id, items: [{price: priceId}], payment_settings: { payment_method_options: { card: { request_three_d_secure: 'automatic', }, }, }, expand: ['latest_invoice.payment_intent'] }); return { clientSecret: subscription.latest_invoice.payment_intent.client_secret, subscriptionId: subscription.id, }; };
问题根源
- 后端路由未处理异步响应:
/create-sub路由直接调用async函数createSubscription但未使用await,也未向客户端返回响应,导致请求一直处于pending状态,前端无法获取后续数据。 - 前端axios处理错误:
axios.post的then回调中使用res.json而非res.json(),导致拿到的是json方法本身而非接口返回数据。 - 多余的支付确认步骤:创建订阅时Stripe已自动完成支付流程,额外调用
stripe.confirmCardPayment属于冗余操作,可能引发逻辑冲突。
修复方案
后端修复
修改路由处理函数,确保异步执行并返回响应:
app.post("/create-sub", async (req, res) => { try { const subscriptionResult = await createSubscription(req); res.json(subscriptionResult); } catch (error) { res.status(500).json({ error: error.message }); } });
前端修复
- 修正axios的响应处理逻辑:
// 直接用await获取响应数据 const response = await axios.post("http://localhost:8800/create-sub", { paymentMethod: paymentMethod.id, name, email, priceId, }); const { clientSecret } = response.data;
- 移除多余的支付确认步骤,直接提示用户:
// 替换原有的confirmPayment逻辑 alert("Success! Check your email for the invoice.");
额外优化(可选)
后端参数解构中priceIdxx与前端传入的priceId不匹配,若需动态使用前端传入的价格ID,修正为:
let { paymentMethod, name, email, priceId } = reqq.body // 后续使用priceId而非硬编码值 const subscription = await stripe.subscriptions.create({ customer: customer.id, items: [{price: priceId}], // ...其他配置 });
内容的提问来源于stack exchange,提问作者Peter Double U
相关产品推荐
相关产品推荐

