You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native集成Stripe支付报错:Network request failed及数组越界求助

核心原因分析

  1. 本地网络访问异常:React Native中localhost指向设备自身,而非运行后端的电脑,导致真机/模拟器无法访问后端接口,触发Network request failed,进而导致clientSecret为空,调用confirmPayment时抛出length=0; index=0错误。
  2. 缺少错误处理:前端fetch请求未处理失败场景,若接口调用失败,key会保持空字符串,直接调用confirmPayment会引发参数错误。
  3. 可能缺失StripeProvider配置:未在根组件用StripeProvider包裹,导致useStripe无法正常初始化Stripe服务。

解决方案

1. 修复后端访问地址

  • 替换fetch中的http://localhost:3000为电脑的局域网IP(可通过ifconfig/ipconfig查看),例如http://192.168.1.100:3000,确保设备和电脑处于同一WiFi网络。
  • 后端添加跨域支持:安装cors中间件
    npm install cors
    
    修改后端代码:
    import cors from 'cors';
    app.use(cors());
    

2. 完善fetch错误处理

避免因接口调用失败导致clientSecret为空:

useEffect(() => {
  fetch('http://你的局域网IP:3000/create-payment-intent', { method: 'POST' })
    .then(res => {
      if (!res.ok) throw new Error('Failed to get payment intent');
      return res.json();
    })
    .then(res => {
      setKey(res.clientSecret);
    })
    .catch(err => {
      console.error('Fetch error:', err);
      Alert.alert('Error', 'Failed to initialize payment.');
    });
}, []);

3. 校验clientSecret后再发起支付

防止空值调用confirmPayment:

const handlePayment = async () => {
  if (!key) {
    Alert.alert('Error', 'Payment not ready. Please try again later.');
    return;
  }
  try {
    const { error } = await confirmPayment(key, {
      paymentMethodType: 'Card',
    });
    if (error) {
      Alert.alert('Error', error.message);
    } else {
      Alert.alert('Payment successful!');
    }
  } catch (error) {
    console.error('Payment error:', error);
    Alert.alert('Error', 'Payment failed. Check your network connection.');
  }
};

4. 配置根组件StripeProvider

确保Stripe服务初始化正确:

import { StripeProvider } from '@stripe/stripe-react-native';
import PaymentScreen from './PaymentScreen';

export default function App() {
  return (
    <StripeProvider
      publishableKey="pk_test_XXX" // 替换为你的Stripe测试公钥
      merchantIdentifier="merchant.com.your-app-id" // 测试环境可随便填写
    >
      <PaymentScreen />
    </StripeProvider>
  );
}

内容的提问来源于stack exchange,提问作者Nico

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 05:16:05