反应本地 Khalti 退出
Khalti 支付网关的本地/ Expo SDK 反应
在您的博览会应用程序中接受 Khalti 钱包、 eBanking 、 移动银行和卡片的支付 .
QQ 快速启动
以下是如何让 Khalti 付款在您的博览会应用中工作:
1. 安装
npx expo install @bishaldahal/react-native-khalti-checkout
2. 建设发展客户端
重要吗: 此软件包需要本地代码和 不与 Expo Go 合作。 。 。 .
# Create development build
eas build --profile development --platform android
# Or build locally
npx expo run:android
3. 基本用途
import KhaltiPaymentSdk from "@bishaldahal/react-native-khalti-checkout";
const handlePayment = async () => {
try {
const result = await KhaltiPaymentSdk.startPayment({
publicKey: "your_khalti_public_key",
pidx: "payment_id_from_backend", // Get this from your server
environment: "TEST", // Use "PROD" for production
});
console.log("Payment successful:", result);
} catch (error) {
console.error("Payment failed:", error);
}
};
这就是基本设置. 跳转到详细设置 或者说 参见完整示例。 。 。 .
* 特性
- 相容的博览会 - 全面测试了Expo SDK 52 & 53(可与他人合作)
- QQ 简单整合 - 具有类型脚本支持的简单 API
- 安全可靠( L) - 内置验证和错误处理
- 实时活动 - 立即听取付款情况
- 多环境 - 科学、技术和创新环境
- 原生性能 - 使用Khalti的官方本地SDK
- QQ 记忆安全 - 事件听众的自动清理
· 先决条件
| 项目 | 所需经费 | 链接 |
|---|---|---|
| 平台 | SDK 52+ / 反应原生 0. 72+ | 展览文件 |
| 业务支助 | Android 5.0+ (API 21) & iOS 15.1+ | - 说吧 |
| 节点.js | 版本16或以上 | 下载 |
| Khalti账户 | 带有 API 密钥的 Merchant 账户 | 测试 | 专业 |
| 发展 | 博览会发展建设 | 指南 |
环境变量
| 变量 | 说明 | 示例 | 需求 |
|---|---|---|---|
KHALTI_PUBLIC_KEY | Khalti仪表板上的公用钥匙 | test_public_key_xxxxx | ✅ |
KHALTI_SECRET_KEY | 密钥( 只有后端) | test_secret_key_xxxxx | QQ( 备份) |
设置指南
重要吗: 此 SDK 仅与 博览会开发 (不是博览会 Go) 并被充分测试 展览 SDK 52 & 53。与其他版本兼容,但没有保证.
新项目
# Create new Expo project with latest SDK
npx create-expo-app@latest MyKhaltiApp --template blank-typescript
cd MyKhaltiApp
# Install Khalti SDK
npx expo install @bishaldahal/react-native-khalti-checkout
# Install development build dependencies
npx expo install expo-dev-client
npm install -g @expo/eas-cli
用于现有项目
# Install Khalti SDK
npx expo install @bishaldahal/react-native-khalti-checkout
# Install development build dependencies
npx expo install expo-dev-client
npm install -g @expo/eas-cli
配置您的工程
1. 更新 app.json/app.config.js:
{
"expo": {
"name": "Your App Name",
"slug": "your-app-slug",
"version": "1.0.0",
"platforms": ["android", "ios"],
"android": {
"package": "com.yourcompany.yourapp",
"versionCode": 1,
"compileSdkVersion": 34,
"targetSdkVersion": 34,
"minSdkVersion": 21
},
"ios": {
"bundleIdentifier": "com.yourcompany.yourapp"
},
"plugins": ["expo-dev-client"]
}
}
2. 创建发展大楼:
# Setup EAS (first time only)
eas login
eas init
# Build for Android (recommended for testing)
eas build --profile development --platform android
# Install the APK on your device when build completes
3. 开始开发:
# Start development server
npx expo start --dev-client
# Open on your device with the custom development build
使用量
完成付款执行
以下是事件听众和错误处理的更完整的例子:
import React, { useEffect, useState } from "react";
import { View, Button, Alert, Text } from "react-native";
import KhaltiPaymentSdk from "@bishaldahal/react-native-khalti-checkout";
export default function PaymentScreen() {
const [loading, setLoading] = useState(false);
useEffect(() => {
// Set up event listeners
const successSubscription = KhaltiPaymentSdk.onPaymentSuccess((payload) => {
console.log("Payment successful:", payload);
Alert.alert("Success", `Transaction ID: ${payload.txnId}`);
setLoading(false);
});
const errorSubscription = KhaltiPaymentSdk.onPaymentError((payload) => {
console.log("Payment failed:", payload);
Alert.alert(
"Payment Failed",
payload.error_description || "Unknown error"
);
setLoading(false);
});
const cancelSubscription = KhaltiPaymentSdk.onPaymentCancel((payload) => {
console.log("Payment cancelled:", payload);
Alert.alert("Payment Cancelled", "You cancelled the payment");
setLoading(false);
});
// Cleanup subscriptions
return () => {
successSubscription.remove();
errorSubscription.remove();
cancelSubscription.remove();
};
}, []);
// WARNING: This should be done from your backend in production
const createPaymentInBackend = async (amount: number) => {
// In production, make this API call from your backend server
const response = await fetch("YOUR_BACKEND_URL/create-khalti-payment", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
amount: amount,
orderId: `order-${Date.now()}`, // Unique order ID from the backend
customerInfo: {
name: "John Doe",
email: "[email protected]",
phone: "9800000000",
},
}),
});
const data = await response.json();
return data.pidx;
};
// Alternative: Frontend payment initiation (FOR DEMO/TESTING ONLY)
const createPaymentFromFrontend = async (amount: number) => {
try {
const response = await fetch(
"https://a.khalti.com/api/v2/epayment/initiate/",
{
method: "POST",
headers: {
Authorization: "key test_secret_key_your_secret_key_here", // NEVER do this in production
"Content-Type": "application/json",
},
body: JSON.stringify({
return_url: "https://example.com/payment/",
website_url: "https://example.com/",
amount: amount * 100, // Convert to paisa
purchase_order_id: `order-${Date.now()}`,
purchase_order_name: "Test Product",
customer_info: {
name: "John Doe",
email: "[email protected]",
phone: "9800000000",
},
}),
}
);
const data = await response.json();
if (!response.ok) {
throw new Error(data.detail || "Payment initialization failed");
}
return data.pidx;
} catch (error) {
throw new Error(`Failed to create payment: ${error.message}`);
}
};
const handlePayment = async () => {
setLoading(true);
try {
// Option 1: Get pidx from your backend (RECOMMENDED)
// const pidx = await createPaymentInBackend(100);
// Option 2: Frontend initiation (DEMO ONLY - NOT for production)
const pidx = await createPaymentFromFrontend(100);
// Start payment with Khalti SDK
await KhaltiPaymentSdk.startPayment({
publicKey: "test_public_key_your_key_here",
pidx: pidx,
environment: "TEST", // Use "PROD" for production
});
} catch (error) {
console.error("Payment error:", error);
Alert.alert("Error", error.message);
setLoading(false);
}
};
return (
<View
style={{
flex: 1,
justifyContent: "center",
alignItems: "center",
padding: 20,
}}
>
<Text style={{ fontSize: 18, marginBottom: 20 }}>
Khalti Payment Demo
</Text>
<Button
title={loading ? "Processing..." : "Pay NPR 100"}
onPress={handlePayment}
disabled={loading}
/>
<Text
style={{
marginTop: 20,
fontSize: 12,
color: "gray",
textAlign: "center",
}}
>
Note: This demo includes frontend payment initiation for testing.{"\n"}
In production, always create payments from your backend server.
</Text>
</View>
);
}
配置选项
interface PaymentArgs {
publicKey: string; // Your Khalti public key
pidx: string; // Payment identifier from backend
environment?: "TEST" | "PROD"; // Default: 'TEST'
}
事件应对类型
// Success response
interface PaymentSuccessPayload {
pidx: string;
txnId: string;
amount: number;
mobile: string;
status: string;
timestamp: number;
}
// Error response
interface PaymentErrorPayload {
error_key: string;
error_description: string;
timestamp: number;
}
// Cancel response
interface PaymentCancelPayload {
reason?: string;
timestamp: number;
}
测试
测试证书
在沙盒环境中进行测试时,使用这些:
| 外地 | 数值 | 页:1 |
|---|---|---|
| Khalti 身份证 | 9800000000 改为 9800000005 | 任何测试编号 |
| 马普林 | 1111 | 4位数 PIN |
| 检察官办公室 | 987654 | 6位数核查码 |
共同问题和解决方案
“ 未找到模块” 错误
您需要安装软件包后重建您的开发客户端 :
# Clear cache and rebuild
npx expo start --clear
eas build --profile development --platform android --clear-cache
未开始付款
检查这些共同问题:
- 校验您的公钥正确
- 确定 PIDX 是否有效, 从您的后端
- 检查您的网络连接
- 验证环境设置( TEST vs PROD)
安保最佳做法
做这个
- 仅在移动应用程序中使用公钥
- 从您的后端服务器创建付款
- 验证支付服务器侧
- 对所有 API 通信使用 HTTPS
- 验证后端的付款状态
不要这样
- 绝不在移动应用程序中设置密钥
- 不要只依赖客户端的付款核查
- 不要在本地存储敏感的支付数据
++ 平台支持
| 平台 | 状态 | SDK 版本 | 页:1 |
|---|---|---|---|
| 机器人 | 已完全支持 | API 21+ (英语) | 测试效果最好 |
| iOS系统 | 已完全支持 | iOS 15.1+ (韩语) | 完全本地SDK融合 |
兼容性矩阵
| 曝光 SDK | 原生反应 | 节点.js | 状态 |
|---|---|---|---|
| 第52-53条 | 0.72+ (简体中文) | 16岁以上 | ✅ 已测试 |
| 第49至51条 | 0.70-0.71 (中文(简体) ) | 16岁以上 | 工作时间 |
| < 49号 | < 0.70 (中文(简体) ) | < 16号 | QQ 不支持 |
API 参考
核心方法
| 方法 | 参数 | 回返 | 说明 |
|---|---|---|---|
startPayment(args) | PaymentArgs | Promise<PaymentSuccessPayload> | 启动支付程序 |
onPaymentSuccess(callback) | Function | Subscription | 收听成功的付款 |
onPaymentError(callback) | Function | Subscription | 听取付款错误 |
onPaymentCancel(callback) | Function | Subscription | 监听取消付款 |
closePayment() | 无 | Promise<void> | 关闭当前付款会话 |
方法
// Clean up all event listeners
KhaltiPaymentSdk.removeAllListeners();
// Check if SDK is ready
const isReady = KhaltiPaymentSdk.isReady();
示例应用
看看这个 示例应用程序 以:
- QQ 完整配置设置
- * 执行付款流程
- QQ 错误处理模式
- UI 集成实例
运行示例
git clone https://github.com/bishaldahal/react-native-khalti-checkout.git
cd react-native-khalti-checkout/example
npm install
npx expo run:android
捐款
我们欢迎捐款!
如何捐款
# Fork and clone the repository
git clone https://github.com/your-username/react-native-khalti-checkout.git
cd react-native-khalti-checkout
npm install
# Run example app
cd example && npm install && npx expo run:android
准则
- 遵循现有的代码样式
- 添加新特性测试
- 需要时更新文件
- 可能时对真实设备进行测试
见 贡献指南 更多细节.
++ 辅助
需要帮忙吗? 这是你的选择:
| 资源 | 说明 | 链接 |
|---|---|---|
| 📚 文档 | 官方 Khalti 文件 | docs.khalti.com (中文(简体) ) |
| 🐛 错误报告 | 报告问题 | GitHub 问题 |
| 💬 讨论情况 | 社区支助 | GitHub 讨论 |
| 电子邮件 | 直接支助 | 支持@khalti.com |
链接
如果你觉得这有帮助, 考虑给它一颗巨星在GitHub上!
许可证
本项目根据以下规定获得许可证: MIT 许可证 - 看这个 自由主义 详细文件.
第三方通知
这个包使用了官方的 Khalti Android SDK. 见 第三次议会 NoTICES.md 完全许可信息.