@bishaldahal/react-native-khalti-checkout

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

React Native/Expo SDK for Khalti Payment Gateway. Accept payments from Khalti, eBanking, mobile banking, and cards in Nepal.

原始使用文档
文档目录36 节
  1. 🚀 Quick Start
  2. 1. Installation
  3. 2. Build Development Client
  4. 3. Basic Usage
  5. ✨ Features
  6. 📋 Prerequisites
  7. Environment Variables
  8. Setup Guide
  9. For New Projects
  10. For Existing Projects
  11. Configure Your Project
  12. Usage
  13. Complete Payment Implementation
  14. Configuration Options
  15. Event Response Types
  16. Testing
  17. Test Credentials
  18. Common Issues & Solutions
  19. Security Best Practices
  20. ✅ Do This
  21. ❌ Don't Do This
  22. 📱 Platform Support
  23. Compatibility Matrix
  24. 📖 API Reference
  25. Core Methods
  26. Utility Methods
  27. Example App
  28. Run the Example
  29. 🤝 Contributing
  30. How to contribute
  31. Guidelines
  32. 📞 Support
  33. Links
  34. License
  35. 📋 Third-Party Notices
  36. 🇳🇵 Made with ❤️ for the Nepalese Developer Community

React Native Khalti Checkout

npm version npm downloads Platform TypeScript License: MIT PRs Welcome

React Native/Expo SDK for Khalti Payment Gateway

Accept payments from Khalti wallet, eBanking, mobile banking, and cards in your Expo applications.

🚀 Quick Start • 📖 Usage • 💡 Examples • 🐛 Issues

🚀 Quick Start

Here's how to get Khalti payments working in your Expo app:

1. Installation

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

2. Build Development Client

⚠️ Important: This package requires native code and does not work with Expo Go.

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

# Or build locally
npx expo run:android

3. Basic Usage

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

That's the basic setup. Jump to detailed setup or see complete example.

✨ Features

  • 🔧 Expo Compatible - Fully tested with Expo SDK 52 & 53 (may work with others)
  • 🚀 Easy Integration - Simple API with TypeScript support
  • 🔒 Secure & Reliable - Built-in validation & error handling
  • ⚡ Real-time Events - Listen to payment events instantly
  • 🌍 Multi-environment - TEST and PROD environments
  • 📱 Native Performance - Uses Khalti's official native SDKs
  • 💾 Memory Safe - Automatic cleanup of event listeners

📋 Prerequisites

ItemRequirementLink
PlatformExpo SDK 52+ / React Native 0.72+Expo Docs
OS SupportAndroid 5.0+ (API 21) & iOS 15.1+-
Node.jsVersion 16 or higherDownload
Khalti AccountMerchant account with API keysTest | Prod
DevelopmentExpo Development BuildGuide

Environment Variables

VariableDescriptionExampleRequired
KHALTI_PUBLIC_KEYPublic key from Khalti dashboardtest_public_key_xxxxx✅
KHALTI_SECRET_KEYSecret key (backend only)test_secret_key_xxxxx✅ (Backend)

Setup Guide

⚠️ Important: This SDK only works with Expo Development Builds (not Expo Go) and is fully tested with Expo SDK 52 & 53. Compatible with other versions but not guaranteed.

For New Projects

# 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

For Existing Projects

# 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

Configure Your Project

1. Update 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. Create development build:

# 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:

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

# Open on your device with the custom development build

Usage

Complete Payment Implementation

Here's a more complete example with event listeners and error handling:

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

Configuration Options

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

Event Response Types

// 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;
}

Testing

Test Credentials

For testing in the sandbox environment, use these:

FieldValueNotes
Khalti ID9800000000 to 9800000005Any of these test numbers
MPIN11114-digit PIN
OTP9876546-digit verification code

Common Issues & Solutions

"Module not found" error

You need to rebuild your development client after installing the package:

# Clear cache and rebuild
npx expo start --clear
eas build --profile development --platform android --clear-cache

Payment not starting

Check these common issues:

  • Verify your public key is correct
  • Make sure the PIDX is valid and from your backend
  • Check your network connection
  • Validate the environment setting (TEST vs PROD)

Security Best Practices

✅ Do This

  • Use public keys only in mobile apps
  • Create payments from your backend server
  • Verify payments server-side
  • Use HTTPS for all API communications
  • Validate payment status in your backend

❌ Don't Do This

  • Never put secret keys in mobile apps
  • Don't rely only on client-side payment verification
  • Don't store sensitive payment data locally

📱 Platform Support

PlatformStatusSDK VersionNotes
AndroidFully SupportedAPI 21+Works best for testing
iOSFully SupportediOS 15.1+Full native SDK integration

Compatibility Matrix

Expo SDKReact NativeNode.jsStatus
52-530.72+16+✅ Fully Tested
49-510.70-0.7116+⚠️ May work
< 49< 0.70< 16❌ Not supported

📖 API Reference

Core Methods

MethodParametersReturnsDescription
startPayment(args)PaymentArgsPromise<PaymentSuccessPayload>Initiates payment process
onPaymentSuccess(callback)FunctionSubscriptionListen for successful payments
onPaymentError(callback)FunctionSubscriptionListen for payment errors
onPaymentCancel(callback)FunctionSubscriptionListen for payment cancellations
closePayment()NonePromise<void>Closes current payment session

Utility Methods

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

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

Example App

Check out the example application for a complete implementation with:

  • 🔧 Complete configuration setup
  • 💳 Payment flow implementation
  • 🚨 Error handling patterns
  • 🎨 UI integration examples

Run the Example

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

🤝 Contributing

We welcome contributions!

How to contribute

# 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

Guidelines

  • Follow existing code style
  • Add tests for new features
  • Update documentation when needed
  • Test on real devices when possible

See Contributing Guide for more details.

📞 Support

Need help? Here are your options:

ResourceDescriptionLink
📚 DocumentationOfficial Khalti docsdocs.khalti.com
🐛 Bug ReportsReport issuesGitHub Issues
💬 DiscussionsCommunity supportGitHub Discussions
EmailDirect support[email protected]

If you find this helpful, consider giving it a star on GitHub!

License

This project is licensed under the MIT License - see the LICENSE file for details.

📋 Third-Party Notices

This package uses the official Khalti Android SDK. See THIRD_PARTY_NOTICES.md for full license information.


🇳🇵 Made with ❤️ for the Nepalese Developer Community

Found this helpful? Give it a ⭐ on GitHub!

GitHub stars GitHub forks

Happy Coding! 🚀

版本与发布记录

@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 是什么?

React Native/Expo SDK for Khalti Payment Gateway. Accept payments from Khalti, eBanking, mobile banking, and cards in Nepal.

如何安装 @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 和提交记录判断。