React Native集成Stripe报错:You must provide paymentMethodType求助
解决React Native集成Stripe时"You must provide paymentMethodType"错误
问题原因
调用confirmPayment时存在两个关键问题:
- 参数名使用错误:当前代码中
type: 'Card'不符合Stripe React Native SDK要求,正确参数应为paymentMethodType - 缺少支付方式信息:未传入实际的支付方式标识(如
paymentMethodId),也未配置卡片输入组件让SDK自动获取卡片信息
修复方案
方案1:手动创建PaymentMethod后确认支付
先通过createPaymentMethod生成支付方式,再传入confirmPayment完成支付流程:
import { CardField, useStripe, useConfirmPayment } from '@stripe/stripe-react-native'; // 组件内逻辑 const { createPaymentMethod } = useStripe(); const { confirmPayment, loading } = useConfirmPayment(); const fetchPaymentIntentClientSecret = async () => { const response = await fetch(`https://api.click-n.com/create-payment-intent-native`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ currency: 'CAD', amount: totalPrice, }), }); const { clientSecret } = await response.json(); return clientSecret; }; const handlePayPress = async () => { const clientSecret = await fetchPaymentIntentClientSecret(); // 1. 创建PaymentMethod const { error: pmError, paymentMethod } = await createPaymentMethod({ type: 'Card', billingDetails: { email: 'email@stripe.com', phone: '+48888000888', address: { city: 'Houston', country: 'US', line1: '1459 Circle Drive', line2: 'Texas', postalCode: '77063', }, }, }); if (pmError) { console.log('支付方式创建失败:', pmError); return; } // 2. 确认支付 const { error, paymentIntent } = await confirmPayment(clientSecret, { paymentMethodId: paymentMethod.id, }); if (error) { console.log(error); } else if (paymentIntent) { console.log(paymentIntent); } }; // 渲染卡片输入组件 return ( <> <CardField postalCodeEnabled={true} placeholder={{ number: '4242 4242 4242 4242', expiry: 'MM/YY', cvc: 'CVC', }} style={{ width: '100%', height: 50, marginVertical: 30, }} /> <Button onPress={handlePayPress} disabled={loading} title="支付" /> </> );
方案2:让SDK自动处理卡片收集
只需修正confirmPayment的参数名,并确保页面已渲染CardField组件:
const handlePayPress = async () => { const clientSecret = await fetchPaymentIntentClientSecret(); const billingDetails = { email: 'email@stripe.com', phone: '+48888000888', address: { city: 'Houston', country: 'US', line1: '1459 Circle Drive', line2: 'Texas', postalCode: '77063', }, }; // 修正参数名:用paymentMethodType代替type const { error, paymentIntent } = await confirmPayment(clientSecret, { paymentMethodType: 'Card', billingDetails, }); if (error) { console.log(error); } else if (paymentIntent) { console.log(paymentIntent); } };
后端代码验证
你的后端代码已正确设置payment_method_types=['card'],无需修改,确保amount转换为分的逻辑(int(data["amount"]* 100))正确即可。
内容的提问来源于stack exchange,提问作者ons jannet
相关产品推荐
相关产品推荐

