使用React+Stripe Express Elements确认支付时无法获取charges数据
解决Stripe confirmPayment扩展charges数据不显示的问题
1. 修正expand参数路径
你当前使用的expand: ['charges.data']不符合Stripe的expand语法规则,需要直接指定顶层关联对象charges:
const {paymentIntent, error} = await stripe.confirmPayment({ elements, clientSecret, confirmParams: { return_url: PAGE_URL, expand: ['charges'], // 修正此处 }, redirect: "if_required", });
修正后可通过paymentIntent.charges.data访问具体的charge列表。
2. 处理重定向场景
当设置redirect: "if_required"时,若支付触发3DS等需重定向的验证步骤,confirmPayment不会立即返回完整的PaymentIntent对象。需在return_url指定的返回页中,通过stripe.retrievePaymentIntent获取数据并携带expand参数:
// 返回页组件中 import { loadStripe } from '@stripe/stripe-js'; const stripe = await loadStripe('你的公钥'); const clientSecret = new URLSearchParams(window.location.search).get('payment_intent_client_secret'); if (clientSecret) { const { paymentIntent } = await stripe.retrievePaymentIntent(clientSecret, { expand: ['charges'], }); console.log(paymentIntent.charges.data); // 在此处获取charges数据 }
3. 检查Stripe依赖版本
确保@stripe/react-stripe-js和@stripe/stripe-js为最新版本,旧版本可能不支持confirmPayment中的expand功能。执行以下命令更新:
npm update @stripe/react-stripe-js @stripe/stripe-js # 或使用yarn yarn upgrade @stripe/react-stripe-js @stripe/stripe-js
4. 验证PaymentIntent状态
仅当PaymentIntent处于succeeded状态时才会生成对应charges。可先打印paymentIntent.status确认状态,若为requires_action或processing,需等待流程完成后再获取charges数据。
内容的提问来源于stack exchange,提问作者Rutnet
相关产品推荐
相关产品推荐

