如何在React Native中接入CCavenue支付网关?求相关文档及操作步骤
React Native 接入 CCavenue 支付网关完整步骤
一、前期准备
- 从CCavenue商户后台获取三个核心凭证:
Merchant ID(商户ID)、Working Key(工作密钥)、Access Code(访问代码) - 确认你的React Native项目环境正常运行(Android/iOS基础配置已完成)
二、集成方案选择
React Native中接入CCavenue主要有两种方案:
- WebView嵌入支付页面:更推荐,适配性强、维护成本低,无需处理原生SDK的版本兼容问题
- 原生SDK集成:适合高度定制场景,但配置复杂、需要维护双端原生代码
以下重点讲解WebView方案的实现步骤。
三、WebView方案具体实现
1. 安装WebView依赖
如果项目未安装react-native-webview,执行安装命令:
npm install react-native-webview --save # 或使用yarn yarn add react-native-webview
RN 0.60+版本支持自动链接,无需额外配置;低于0.60版本需手动执行react-native link react-native-webview。
2. 后端生成支付签名(核心步骤)
CCavenue要求支付请求必须携带签名,签名必须在后端生成(避免前端暴露Working Key导致安全风险)。
签名生成规则:
将
Access Code + Merchant ID + Order ID + Amount + Redirect URL按顺序拼接成字符串,使用Working Key进行AES加密(模式CBC、填充PKCS5Padding、密钥长度128位),最后转成Base64编码。
后端示例(Node.js):
const crypto = require('crypto'); function generateCcavenueSignature(accessCode, merchantId, orderId, amount, redirectUrl, workingKey) { const rawData = `${accessCode}${merchantId}${orderId}${amount}${redirectUrl}`; // 初始化加密器,IV取Working Key前16位 const cipher = crypto.createCipheriv('aes-128-cbc', Buffer.from(workingKey, 'utf8'), Buffer.from(workingKey.substring(0, 16), 'utf8')); let encryptedData = cipher.update(rawData, 'utf8', 'base64'); encryptedData += cipher.final('base64'); return encryptedData; }
3. 前端支付页面组件实现
创建CcavenuePayment.js组件,自动提交表单到CCavenue支付页面,并处理回调:
import React, { useState } from 'react'; import { View, ActivityIndicator, StyleSheet } from 'react-native'; import { WebView } from 'react-native-webview'; const CcavenuePayment = ({ route, navigation }) => { const { orderId, amount, redirectUrl, merchantId, accessCode, signature } = route.params; const [isLoading, setIsLoading] = useState(true); // 生成自动提交的支付表单HTML const getPaymentForm = () => { return ` <html> <body onload="document.forms['ccavenueForm'].submit()"> <form name="ccavenueForm" method="POST" action="https://secure.ccavenue.com/transaction/transaction.do?command=initiateTransaction"> <input type="hidden" name="merchant_id" value="${merchantId}"> <input type="hidden" name="order_id" value="${orderId}"> <input type="hidden" name="amount" value="${amount}"> <input type="hidden" name="redirect_url" value="${redirectUrl}"> <input type="hidden" name="cancel_url" value="${redirectUrl}"> <input type="hidden" name="access_code" value="${accessCode}"> <input type="hidden" name="signature" value="${signature}"> <!-- 以下为必填的账单信息,可根据实际业务动态传入 --> <input type="hidden" name="billing_name" value="Test User"> <input type="hidden" name="billing_address" value="Test Address"> <input type="hidden" name="billing_city" value="Test City"> <input type="hidden" name="billing_state" value="Test State"> <input type="hidden" name="billing_zip" value="12345"> <input type="hidden" name="billing_country" value="India"> <input type="hidden" name="billing_tel" value="9876543210"> <input type="hidden" name="billing_email" value="test@example.com"> </form> </body> </html> `; }; // 监听页面跳转,处理支付回调 const handleNavigationChange = (navState) => { if (navState.url.startsWith(redirectUrl)) { // 解析回调参数 const urlParams = new URLSearchParams(navState.url.split('?')[1]); const paymentStatus = urlParams.get('order_status'); const respOrderId = urlParams.get('order_id'); // 关闭支付页面,返回支付结果 navigation.goBack(); console.log('支付结果:', paymentStatus, '订单ID:', respOrderId); // 这里可添加业务逻辑,比如更新订单状态 } }; return ( <View style={styles.container}> {isLoading && <ActivityIndicator style={styles.loader} size="large" />} <WebView source={{ html: getPaymentForm() }} onLoadStart={() => setIsLoading(true)} onLoadEnd={() => setIsLoading(false)} onNavigationStateChange={handleNavigationChange} javaScriptEnabled={true} domStorageEnabled={true} style={styles.webview} /> </View> ); }; const styles = StyleSheet.create({ container: { flex: 1 }, loader: { position: 'absolute', top: '50%', left: '50%', marginLeft: -25 }, webview: { flex: 1 } }); export default CcavenuePayment;
4. 发起支付请求
在需要触发支付的页面,先调用后端接口获取签名,再跳转到支付组件:
const triggerPayment = async () => { // 从后端获取签名 const resp = await fetch('你的后端接口地址/generate-ccavenue-signature', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ orderId: 'ORDER_20240501_001', amount: '299.00', redirectUrl: 'https://your-domain.com/payment-callback' // 或自定义App Scheme,如yourapp://payment-callback }) }); const { signature } = await resp.json(); // 跳转到支付页面 navigation.navigate('CcavenuePayment', { orderId: 'ORDER_20240501_001', amount: '299.00', redirectUrl: 'https://your-domain.com/payment-callback', merchantId: '你的商户ID', accessCode: '你的访问代码', signature }); };
5. 配置App Scheme回调(可选)
如果希望支付完成后直接跳回App而非Web页面,可配置自定义Scheme:
- Android:在
AndroidManifest.xml的MainActivity中添加intent-filter:
<activity android:name=".MainActivity" android:launchMode="singleTask"> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <data android:scheme="yourapp" android:host="payment-callback" /> </intent-filter> </activity>
- iOS:在
Info.plist中添加URL Scheme配置:
<key>CFBundleURLTypes</key> <array> <dict> <key>CFBundleURLSchemes</key> <array> <string>yourapp</string> </array> <key>CFBundleURLName</key> <string>payment-callback</string> </dict> </array>
之后将redirectUrl改为yourapp://payment-callback,并在App中监听Scheme跳转获取支付参数。
四、测试与生产切换
- 测试环境:使用CCavenue提供的测试凭证和测试卡片(如卡号:4111 1111 1111 1111,有效期:任意未来日期,CVV:123)
- 生产环境:切换为正式商户凭证,确保后端使用正式Working Key生成签名,支付接口地址使用正式环境地址(
https://secure.ccavenue.com/transaction/transaction.do)
内容的提问来源于stack exchange,提问作者Gohel Meet
相关产品推荐
相关产品推荐

