@bishaldahal/react-native-khalti-checkout

中文文档
0.2.2发布于 2025/09/08MITTypeScriptCommonJS零依赖近 30 天下载 2252

对 Khalti 支付网关的本地/ Expo SDK 进行反应。 在尼泊尔接受Khalti、eBanking、移动银行和卡片的付款.

中文使用文档
文档目录36 节
  1. QQ 快速启动
  2. 1. 安装
  3. 2. 建设发展客户端
  4. 3. 基本用途
  5. * 特性
  6. · 先决条件
  7. 环境变量
  8. 设置指南
  9. 新项目
  10. 用于现有项目
  11. 配置您的工程
  12. 使用量
  13. 完成付款执行
  14. 配置选项
  15. 事件应对类型
  16. 测试
  17. 测试证书
  18. 共同问题和解决方案
  19. 安保最佳做法
  20. 做这个
  21. 不要这样
  22. ++ 平台支持
  23. 兼容性矩阵
  24. API 参考
  25. 核心方法
  26. 方法
  27. 示例应用
  28. 运行示例
  29. 捐款
  30. 如何捐款
  31. 准则
  32. ++ 辅助
  33. 链接
  34. 许可证
  35. 第三方通知
  36. 为尼泊尔开发者社区制作的 QQ

反应本地 Khalti 退出

npm version npm downloads Platform TypeScript License: MIT PRs Welcome

Khalti 支付网关的本地/ Expo SDK 反应

在您的博览会应用程序中接受 Khalti 钱包、 eBanking 、 移动银行和卡片的支付 .

QQ 快速启动 二. 支助 使用量 二. 支助 实例 二. 支助 问题

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_KEYKhalti仪表板上的公用钥匙test_public_key_xxxxx✅
KHALTI_SECRET_KEY密钥( 只有后端)test_secret_key_xxxxxQQ( 备份)

设置指南

重要吗: 此 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任何测试编号
马普林11114位数 PIN
检察官办公室9876546位数核查码

共同问题和解决方案

“ 未找到模块” 错误

您需要安装软件包后重建您的开发客户端 :

# 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)PaymentArgsPromise<PaymentSuccessPayload>启动支付程序
onPaymentSuccess(callback)FunctionSubscription收听成功的付款
onPaymentError(callback)FunctionSubscription听取付款错误
onPaymentCancel(callback)FunctionSubscription监听取消付款
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 完全许可信息.


为尼泊尔开发者社区制作的 QQ

找到这个帮助? 给它一个"GitHub"!

GitHub stars GitHub forks

编码快乐

版本与发布记录

@bishaldahal/react-native-khalti-checkout 共发布 9 个版本,首次发布于 2025/07/09;过去 12 个月发布了 0 个版本。

版本发布日期距今
0.2.2latest2025/09/081.2 年前
0.2.12025/09/051.2 年前
0.2.02025/09/021.2 年前
0.2.0-beta.5beta2025/07/281.3 年前
0.2.0-beta.42025/07/101.3 年前
0.2.0-beta.32025/07/101.3 年前

关于 @bishaldahal/react-native-khalti-checkout 的常见问题

@bishaldahal/react-native-khalti-checkout 是什么?

对 Khalti 支付网关的本地/ Expo SDK 进行反应。 在尼泊尔接受Khalti、eBanking、移动银行和卡片的付款.

如何安装 @bishaldahal/react-native-khalti-checkout?

在项目目录运行 npm install @bishaldahal/react-native-khalti-checkout,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:expo(*)、react(*)、react-native(*)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@bishaldahal/react-native-khalti-checkout 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@bishaldahal/react-native-khalti-checkout 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@bishaldahal/react-native-khalti-checkout 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=16。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@bishaldahal/react-native-khalti-checkout 可以商用吗?

@bishaldahal/react-native-khalti-checkout 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@bishaldahal/react-native-khalti-checkout 的下载量有多少?

根据 npm 官方下载统计,@bishaldahal/react-native-khalti-checkout 在 2026/10/08 – 2026/11/06 这 30 天内被下载 2,252 次,日均约 75 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@bishaldahal/react-native-khalti-checkout 还在维护吗?

最新版本 0.2.2 发布于 2025/09/08(1.2 年前);至今共发布 9 个版本,其中过去 12 个月发布了 0 个;首次发布于 2025/07/09。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。