5分钟搞定React Native支付集成:Stripe与PayPal双方案实战
【免费下载链接】create-react-native-app 项目地址: https://gitcode.com/gh_mirrors/cre/create-react-native-app
你还在为React Native应用集成支付功能头疼吗?iOS和Android平台适配复杂?支付流程繁琐易出错?本文将带你用create-react-native-app快速实现Stripe和PayPal支付功能,无需原生开发经验,零基础也能上手。
读完本文你将获得:
- 两种主流支付方案的完整集成步骤
- 跨平台支付界面的实现方法
- 支付状态管理的最佳实践
- 真实项目中的常见问题解决方案
准备工作
首先确保你已安装create-react-native-app工具,如未安装,执行以下命令:
npm install -g create-react-native-app
创建新项目:
create-react-native-app MyPaymentApp
cd MyPaymentApp
方案一:Stripe支付集成
安装依赖
npm install @stripe/stripe-react-native @stripe/stripe-js
基本支付组件实现
创建src/components/StripePayment.tsx文件:
import React, { useState } from 'react';
import { View, Button, Alert, Text } from 'react-native';
import { CardField, useStripe } from '@stripe/stripe-react-native';
const StripePayment = ({ amount }) => {
const [loading, setLoading] = useState(false);
const { confirmCardPayment } = useStripe();
const handlePayPress = async () => {
setLoading(true);
// 1. 创建支付意向 (实际项目中应通过后端API创建)
const paymentIntentClientSecret = await fetchPaymentIntent(amount);
// 2. 确认支付
const { error, paymentIntent } = await confirmCardPayment(paymentIntentClientSecret, {
paymentMethod: {
card: cardDetails,
billingDetails: {
name: 'Customer Name',
},
},
});
setLoading(false);
if (error) {
Alert.alert('支付失败', error.message);
} else if (paymentIntent.status === 'succeeded') {
Alert.alert('支付成功', '感谢您的购买!');
}
};
return (
<View style={{ padding: 20 }}>
<Text>支付金额: ¥{amount}</Text>
<CardField
postalCodeEnabled={false}
placeholder={{
number: '4242 4242 4242 4242',
}}
style={{ width: '100%', height: 50, marginVertical: 20 }}
onCardChange={(cardDetails) => {
setCardDetails(cardDetails);
}}
/>
<Button
title={loading ? '处理中...' : `支付 ¥${amount}`}
onPress={handlePayPress}
disabled={!cardDetails?.complete || loading}
/>
</View>
);
};
export default StripePayment;
方案二:PayPal支付集成
安装依赖
npm install react-native-paypal
配置PayPal
在src/config/PayPalConfig.ts中添加配置:
export const PayPalConfig = {
clientId: 'YOUR_PAYPAL_CLIENT_ID',
environment: 'sandbox', // 生产环境使用 'production'
currency: 'CNY',
};
PayPal支付组件实现
创建src/components/PayPalPayment.tsx文件:
import React, { useState } from 'react';
import { View, Button, Alert, Text } from 'react-native';
import PayPal from 'react-native-paypal';
import { PayPalConfig } from '../config/PayPalConfig';
const PayPalPayment = ({ amount }) => {
const [loading, setLoading] = useState(false);
const handlePayPress = async () => {
setLoading(true);
try {
// 初始化PayPal
await PayPal.initialize(PayPalConfig.clientId, PayPalConfig.environment);
// 创建支付
const payment = await PayPal.renderSinglePaymentUI({
amount: amount.toString(),
currency: PayPalConfig.currency,
description: '商品购买',
});
if (payment.status === 'success') {
Alert.alert('支付成功', `交易ID: ${payment.transactionID}`);
// 这里可以添加订单确认逻辑
} else {
Alert.alert('支付取消', '您已取消支付');
}
} catch (error) {
Alert.alert('支付失败', error.message);
} finally {
setLoading(false);
}
};
return (
<View style={{ padding: 20 }}>
<Text>支付金额: ¥{amount}</Text>
<Button
title={loading ? '处理中...' : `通过PayPal支付 ¥${amount}`}
onPress={handlePayPress}
disabled={loading}
style={{ marginTop: 20 }}
/>
</View>
);
};
export default PayPalPayment;
支付状态管理
创建src/context/PaymentContext.tsx统一管理支付状态:
import React, { createContext, useContext, useState, ReactNode } from 'react';
type PaymentContextType = {
paymentMethod: 'stripe' | 'paypal';
setPaymentMethod: (method: 'stripe' | 'paypal') => void;
amount: number;
setAmount: (amount: number) => void;
paymentStatus: 'idle' | 'processing' | 'success' | 'failed';
setPaymentStatus: (status: 'idle' | 'processing' | 'success' | 'failed') => void;
};
const PaymentContext = createContext<PaymentContextType | undefined>(undefined);
export const PaymentProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
const [paymentMethod, setPaymentMethod] = useState<'stripe' | 'paypal'>('stripe');
const [amount, setAmount] = useState<number>(99);
const [paymentStatus, setPaymentStatus] = useState<'idle' | 'processing' | 'success' | 'failed'>('idle');
return (
<PaymentContext.Provider value={{
paymentMethod,
setPaymentMethod,
amount,
setAmount,
paymentStatus,
setPaymentStatus
}}>
{children}
</PaymentContext.Provider>
);
};
export const usePayment = () => {
const context = useContext(PaymentContext);
if (context === undefined) {
throw new Error('usePayment must be used within a PaymentProvider');
}
return context;
};
主应用集成
修改App.tsx,集成支付组件:
import React from 'react';
import { View, Text, Switch, StyleSheet } from 'react-native';
import { PaymentProvider, usePayment } from './src/context/PaymentContext';
import StripePayment from './src/components/StripePayment';
import PayPalPayment from './src/components/PayPalPayment';
const PaymentScreen = () => {
const { paymentMethod, setPaymentMethod, amount, setAmount } = usePayment();
return (
<View style={styles.container}>
<Text style={styles.title}>选择支付方式</Text>
<View style={styles.optionContainer}>
<Text>Stripe支付</Text>
<Switch
value={paymentMethod === 'stripe'}
onValueChange={() => setPaymentMethod('stripe')}
/>
</View>
<View style={styles.optionContainer}>
<Text>PayPal支付</Text>
<Switch
value={paymentMethod === 'paypal'}
onValueChange={() => setPaymentMethod('paypal')}
/>
</View>
<View style={styles.amountContainer}>
<Text>支付金额: ¥{amount}</Text>
<Button
title="增加金额"
onPress={() => setAmount(prev => Math.min(prev + 10, 1000))}
/>
<Button
title="减少金额"
onPress={() => setAmount(prev => Math.max(prev - 10, 10))}
/>
</View>
{paymentMethod === 'stripe' ? (
<StripePayment amount={amount} />
) : (
<PayPalPayment amount={amount} />
)}
</View>
);
};
const App = () => {
return (
<PaymentProvider>
<PaymentScreen />
</PaymentProvider>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 20,
marginTop: 50,
},
title: {
fontSize: 20,
fontWeight: 'bold',
marginBottom: 20,
},
optionContainer: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
marginVertical: 10,
},
amountContainer: {
marginVertical: 20,
alignItems: 'center',
},
});
export default App;
测试与部署
运行应用
npm start
使用Expo Go扫描二维码,或运行:
# iOS
npm run ios
# Android
npm run android
常见问题解决
-
支付组件不显示:确保已正确安装依赖并链接原生模块,可运行
npx pod-install修复iOS依赖问题。 -
支付失败:检查API密钥是否正确,网络连接是否正常,支付账户是否有足够余额。
-
跨平台兼容性:使用src/Template.ts中的工具函数处理平台差异。
总结与展望
本文介绍了如何使用create-react-native-app快速集成Stripe和PayPal支付功能,通过上下文管理实现了支付状态的统一管理,并提供了完整的UI实现。实际项目中,建议:
- 将支付逻辑移至专门的服务层,如创建
src/services/PaymentService.ts - 添加订单记录和支付状态持久化,可使用AsyncStorage或数据库
- 完善错误处理和用户反馈机制
通过这种方式,你可以在React Native应用中轻松实现专业的支付功能,为用户提供流畅的购买体验。
喜欢本文请点赞收藏,关注获取更多React Native实战教程!下期将带来"支付安全最佳实践",敬请期待。
【免费下载链接】create-react-native-app 项目地址: https://gitcode.com/gh_mirrors/cre/create-react-native-app
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考



