# @bishaldahal/react-native-khalti-checkout 中文文档

规范地址：https://npmcn.com/package/%40bishaldahal/react-native-khalti-checkout/

版本：0\.2\.2
npm 元数据更新时间：2025-11-23T01:53:55.396Z
中文译文更新时间：2026-11-08T03:47:28.295Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40bishaldahal/react-native-khalti-checkout
原文对照：https://npmcn.com/package/%40bishaldahal/react-native-khalti-checkout/?lang=original
项目主页：https://github.com/bishaldahal/react-native-khalti-checkout#readme
源码仓库：https://github.com/bishaldahal/react-native-khalti-checkout

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：114 kB，41 个文件
- 模块格式：CommonJS
- TypeScript 类型：包内自带
- Node.js 要求：\>=16
- 运行依赖：0 个
- peer 依赖：expo \*，react \*，react-native \*
- 首次发布：2025-07-09T12:14:28.777Z
- 最新版本发布：2025-09-08T03:27:47.710Z
- 近 30 天下载量：2252（2026-10-08 至 2026-11-06，npm 官方下载统计）
- 已发布版本数：9（近 12 个月 0 个）

## 中文简介

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

## 安装

```sh
npm install @bishaldahal/react-native-khalti-checkout
```

也可以使用：`pnpm add @bishaldahal/react-native-khalti-checkout`、`yarn add @bishaldahal/react-native-khalti-checkout`、`bun add @bishaldahal/react-native-khalti-checkout`

## README

# 反应本地 Khalti 退出

[![npm version](https://badge.fury.io/js/@bishaldahal%2Freact-native-khalti-checkout.svg)](https://badge.fury.io/js/@bishaldahal%2Freact-native-khalti-checkout) [![npm downloads](https://img.shields.io/npm/dm/@bishaldahal/react-native-khalti-checkout.svg)](https://www.npmjs.com/package/@bishaldahal/react-native-khalti-checkout) ![Platform](https://img.shields.io/badge/platform-android%20%7C%20ios-green.svg) [![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue.svg)](https://www.typescriptlang.org/) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://github.com/bishaldahal/react-native-khalti-checkout/blob/main/LICENSE) [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](https://github.com/bishaldahal/react-native-khalti-checkout/pulls)

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

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

[QQ 快速启动](https://npmcn.com/package/%40bishaldahal/react-native-khalti-checkout/#readme--quick-start) 二. 支助 [使用量](https://npmcn.com/package/%40bishaldahal/react-native-khalti-checkout/#readme-usage) 二. 支助 [实例](https://npmcn.com/package/%40bishaldahal/react-native-khalti-checkout/#readme-example-app) 二. 支助 [问题](https://github.com/bishaldahal/react-native-khalti-checkout/issues)

## QQ 快速启动

以下是如何让 Khalti 付款在您的博览会应用中工作:

### 1\. 安装

```bash
npx expo install @bishaldahal/react-native-khalti-checkout
```

### 2\. 建设发展客户端

> **重要吗**: 此软件包需要本地代码和 **不与 Expo Go 合作**。 。 。 .

```bash
# Create development build
eas build --profile development --platform android

# Or build locally
npx expo run:android
```

### 3\. 基本用途

```typescript
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);
  }
};
```

这就是基本设置. [跳转到详细设置](https://npmcn.com/package/%40bishaldahal/react-native-khalti-checkout/#readme-setup-guide) 或者说 [参见完整示例](https://npmcn.com/package/%40bishaldahal/react-native-khalti-checkout/#readme-usage)。 。 。 .

## \* 特性

-   **相容的博览会** - 全面测试了Expo SDK 52 & 53(可与他人合作)
-   **QQ 简单整合** - 具有类型脚本支持的简单 API
-   **安全可靠( L)** - 内置验证和错误处理
-   **实时活动** - 立即听取付款情况
-   **多环境** - 科学、技术和创新环境
-   **原生性能** - 使用Khalti的官方本地SDK
-   **QQ 记忆安全** - 事件听众的自动清理

## · 先决条件

| 项目 | 所需经费 | 链接 |
| --- | --- | --- |
| **平台** | SDK 52+ / 反应原生 0. 72+ | [展览文件](https://docs.expo.dev/) |
| **业务支助** | Android 5.0+ (API 21) & iOS 15.1+ | \- 说吧 |
| **节点.js** | 版本16或以上 | [下载](https://nodejs.org/) |
| **Khalti账户** | 带有 API 密钥的 Merchant 账户 | [测试](https://test-admin.khalti.com/#/join/merchant) | [专业](https://admin.khalti.com/) |
| **发展** | 博览会发展建设 | [指南](https://npmcn.com/package/%40bishaldahal/react-native-khalti-checkout/#readme-setup-guide) |

### 环境变量

| 变量 | 说明 | 示例 | 需求 |
| --- | --- | --- | --- |
| `KHALTI_PUBLIC_KEY` | Khalti仪表板上的公用钥匙 | `test_public_key_xxxxx` | ✅ |
| `KHALTI_SECRET_KEY` | 密钥( 只有后端) | `test_secret_key_xxxxx` | QQ( 备份) |

## 设置指南

> **重要吗**: 此 SDK 仅与 **博览会开发** (不是博览会 Go) 并被充分测试 **展览 SDK 52 & 53**。与其他版本兼容,但没有保证.

### 新项目

```bash
# 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
```

### 用于现有项目

```bash
# 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:**

```json
{
  "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\. 创建发展大楼:**

```bash
# 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\. 开始开发:**

```bash
# Start development server
npx expo start --dev-client

# Open on your device with the custom development build
```

## 使用量

### 完成付款执行

以下是事件听众和错误处理的更完整的例子:

```typescript
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: "john@example.com",
          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: "john@example.com",
              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>
  );
}
```

### 配置选项

```typescript
interface PaymentArgs {
  publicKey: string; // Your Khalti public key
  pidx: string; // Payment identifier from backend
  environment?: "TEST" | "PROD"; // Default: 'TEST'
}
```

### 事件应对类型

```typescript
// 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位数核查码 |

## 共同问题和解决方案

**“ 未找到模块” 错误**

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

```bash
# 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>` | 关闭当前付款会话 |

### 方法

```typescript
// Clean up all event listeners
KhaltiPaymentSdk.removeAllListeners();

// Check if SDK is ready
const isReady = KhaltiPaymentSdk.isReady();
```

## 示例应用

看看这个 [示例应用程序](https://github.com/bishaldahal/react-native-khalti-checkout/tree/main/example) 以:

-   QQ 完整配置设置
-   \* 执行付款流程
-   QQ 错误处理模式
-   UI 集成实例

### 运行示例

```bash
git clone https://github.com/bishaldahal/react-native-khalti-checkout.git
cd react-native-khalti-checkout/example
npm install
npx expo run:android
```

## 捐款

我们欢迎捐款!

### 如何捐款

```bash
# 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
```

### 准则

-   遵循现有的代码样式
-   添加新特性测试
-   需要时更新文件
-   可能时对真实设备进行测试

见 [贡献指南](https://npmcn.com/package/%40bishaldahal/react-native-khalti-checkout/CONTRIBUTING.md) 更多细节.

## ++ 辅助

需要帮忙吗? 这是你的选择:

| 资源 | 说明 | 链接 |
| --- | --- | --- |
| 📚 **文档** | 官方 Khalti 文件 | [docs.khalti.com (中文(简体) )](https://docs.khalti.com/) |
| 🐛 **错误报告** | 报告问题 | [GitHub 问题](https://github.com/bishaldahal/react-native-khalti-checkout/issues) |
| 💬 **讨论情况** | 社区支助 | [GitHub 讨论](https://github.com/bishaldahal/react-native-khalti-checkout/discussions) |
| **电子邮件** | 直接支助 | [支持@khalti.com](mailto:support@khalti.com) |

### 链接

-   [仓库](https://github.com/bishaldahal/react-native-khalti-checkout)
-   [国家防范机制一揽子计划](https://www.npmjs.com/package/@bishaldahal/react-native-khalti-checkout)
-   [许可证](https://npmcn.com/package/%40bishaldahal/react-native-khalti-checkout/LICENSE)

如果你觉得这有帮助, 考虑给它一颗巨星在GitHub上!

## 许可证

本项目根据以下规定获得许可证: **MIT 许可证** - 看这个 [自由主义](https://npmcn.com/package/%40bishaldahal/react-native-khalti-checkout/LICENSE) 详细文件.

### 第三方通知

这个包使用了官方的 Khalti Android SDK. 见 [第三次议会 NoTICES.md](https://npmcn.com/package/%40bishaldahal/react-native-khalti-checkout/THIRD_PARTY_NOTICES.md) 完全许可信息.

* * *

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

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

[![GitHub stars](https://img.shields.io/github/stars/bishaldahal/react-native-khalti-checkout?style=social)](https://github.com/bishaldahal/react-native-khalti-checkout/stargazers) [![GitHub forks](https://img.shields.io/github/forks/bishaldahal/react-native-khalti-checkout?style=social)](https://github.com/bishaldahal/react-native-khalti-checkout/network/members)

_编码快乐_

## 常见问题

### @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 和提交记录判断。

