Flutter支付插件khalti_flutter的使用

发布于 1周前 作者 bupafengyu 来自 Flutter

Flutter支付插件khalti_flutter的使用

Khalti是尼泊尔的一种支付网关,数字钱包和API提供商系统。khalti_flutter插件允许Flutter应用集成Khalti支付功能。以下是详细的使用指南。

目录

介绍

Khalti提供了多种支付方式,包括Khalti用户、电子银行用户、移动银行用户等。详细信息请参阅Khalti官方文档

开始

首先需要创建一个商户账户,并获取公共密钥。注册商户账户

支持的平台

支付方式 Android iOS Web Desktop
Khalti Wallet ✔️ ✔️ ✔️ ✔️
E-Banking ✔️ ✔️ ✔️
Mobile Banking ✔️ ✔️ ✔️
Connect IPS ✔️ ✔️ ✔️
SCT ✔️ ✔️ ✔️

设置

Android

AndroidManifest.xml中添加以下内容:

<activity ...>
    <meta-data android:name="flutter_deeplinking_enabled" android:value="true" />
    <intent-filter android:autoVerify="true">
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="kpg" android:host="{your package name}" />
    </intent-filter>
</activity>

iOS

Info.plist中添加以下属性:

<key>FlutterDeepLinkingEnabled</key>
<true/>
<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleTypeRole</key>
        <string>Editor</string>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>kpg</string>
        </array>
        <key>CFBundleURLName</key>
        <string>{your package name}</string>
    </dict>
</array>

Web

无需配置。

桌面

无需配置。

初始化

将应用程序的顶级小部件包装在KhaltiScope小部件中,并添加支持的语言环境和KhaltiLocalizations.delegate

Navigator方法

当使用MaterialApp或类似组件时:

KhaltiScope(
  publicKey: 'test_public_key_dc74e0fd57cb46cd93832aee0a507256',
  builder: (context, navigatorKey) {
    return MaterialApp(
      navigatorKey: navigatorKey,
      supportedLocales: const [
        Locale('en', 'US'),
        Locale('ne', 'NP'),
      ],
      localizationsDelegates: const [
        KhaltiLocalizations.delegate,
        GlobalMaterialLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
      ],
      home: HomePage(),
    );
  },
);

Router方法

当使用MaterialApp.router或类似组件时:

final routerDelegate = YourRouterDelegate();

KhaltiScope(
  publicKey: 'test_public_key_dc74e0fd57cb46cd93832aee0a507256',
  navigatorKey: routerDelegate.navigatorKey,
  builder: (context, _) {
    return MaterialApp.router(
      routerDelegate: routerDelegate,
      supportedLocales: const [
        Locale('en', 'US'),
        Locale('ne', 'NP'),
      ],
      localizationsDelegates: const [
        KhaltiLocalizations.delegate,
        GlobalMaterialLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
      ],
      home: HomePage(),
    );
  },
);

启动支付界面

有两种方法可以启动支付界面。

使用KhaltiButton

可以通过以下代码使用预设按钮:

final config = PaymentConfig(
  amount: 10000, // Amount should be in paisa
  productIdentity: 'dell-g5-g5510-2021',
  productName: 'Dell G5 G5510 2021',
  productUrl: 'https://www.khalti.com/#/bazaar',
  additionalData: { // Not mandatory; can be used for reporting purpose
    'vendor': 'Khalti Bazaar',
  },
  mobile: '9800000001', // Not mandatory; can be used to fill mobile number field
  mobileReadOnly: true, // Not mandatory; makes the mobile field not editable
);

KhaltiButton(
  config: config,
  preferences: [ // Not providing this will enable all the payment methods.
    PaymentPreference.khalti,
    PaymentPreference.eBanking,
  ],
  onSuccess: (successModel) {
    // Perform Server Verification 
  },
  onFailure: (failureModel) {
    // What to do on failure?
  },
  onCancel: () {
    // User manually cancelled the transaction
  },
);

手动方法

另一种方法是使用KhaltiScope.pay()方法:

Inkwell(
  onTap: () {
    KhaltiScope.of(context).pay(
      config: config,
      preferences: [
        PaymentPreference.connectIPS,
        PaymentPreference.eBanking,
        PaymentPreference.sct,
      ],
      onSuccess: onSuccess,
      onFailure: onFailure,
      onCancel: onCancel,
    );
  },
  child: Text('Launch Payment Interface'),
);

自定义返回URL

可以通过在PaymentConfig中设置自定义返回URL:

final config = PaymentConfig(
  returnUrl: 'https://example.com/test',
  ...
);

自定义UI

该插件不支持高度自定义的UI。如果需要自定义界面,请参考khalti包。

示例

完整的示例代码如下:

import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:khalti_flutter/khalti_flutter.dart';

const String testPublicKey = 'test_public_key_dc74e0fd57cb46cd93832aee0a507256';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return KhaltiScope(
      publicKey: testPublicKey,
      enabledDebugging: true,
      builder: (context, navKey) {
        return MaterialApp(
          title: 'Khalti Payment Gateway',
          supportedLocales: const [
            Locale('en', 'US'),
            Locale('ne', 'NP'),
          ],
          theme: ThemeData(
            colorSchemeSeed: Colors.deepPurple,
            useMaterial3: true,
          ),
          debugShowCheckedModeBanner: false,
          navigatorKey: navKey,
          localizationsDelegates: const [
            KhaltiLocalizations.delegate,
            GlobalMaterialLocalizations.delegate,
            GlobalCupertinoLocalizations.delegate,
            GlobalWidgetsLocalizations.delegate,
          ],
          home: HomePage(),
        );
      },
    );
  }
}

class HomePage extends StatelessWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final config = PaymentConfig(
      amount: 10000,
      productIdentity: 'dell-g5-g5510-2021',
      productName: 'Dell G5 G5510 2021',
      productUrl: 'https://www.khalti.com/#/bazaar',
    );

    return Scaffold(
      appBar: AppBar(title: Text('Khalti Payment')),
      body: Center(
        child: KhaltiButton(
          config: config,
          preferences: [PaymentPreference.khalti],
          onSuccess: (model) {
            print('Payment Success: ${model.token}');
          },
          onFailure: (model) {
            print('Payment Failure: ${model.message}');
          },
          onCancel: () {
            print('Payment Cancelled');
          },
        ),
      ),
    );
  }
}

服务器验证

在客户端支付成功后,需要进行服务器验证以确保支付的真实性。具体步骤请参阅Khalti官方文档

通过以上步骤,您可以在Flutter应用中轻松集成Khalti支付功能。希望对您有所帮助!


更多关于Flutter支付插件khalti_flutter的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter支付插件khalti_flutter的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何在Flutter项目中使用khalti_flutter插件的示例代码。这个插件用于集成Khalti支付网关到你的Flutter应用中。请确保你已经按照官方文档完成了基本的Flutter开发环境设置,并且已经在pubspec.yaml文件中添加了khalti_flutter依赖。

1. 添加依赖

首先,在你的pubspec.yaml文件中添加khalti_flutter依赖:

dependencies:
  flutter:
    sdk: flutter
  khalti_flutter: ^最新版本号  # 请替换为实际的最新版本号

然后运行flutter pub get来安装依赖。

2. 配置Android和iOS

按照khalti_flutter的官方文档,你可能需要在Android和iOS项目中进行一些配置,比如添加API密钥等。这里假设你已经完成了这些配置。

3. 使用Khalti支付插件

下面是一个简单的示例代码,展示如何在Flutter应用中使用khalti_flutter插件进行支付。

import 'package:flutter/material.dart';
import 'package:khalti_flutter/khalti_flutter.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final Khalti _khalti = Khalti();

  void _initiatePayment() async {
    try {
      // Replace with your actual merchant ID, public key, and amount
      String merchantId = 'your_merchant_id';
      String publicKey = 'your_public_key';
      double amount = 100.0; // Amount in Nepalese Rupees
      String description = 'Test Payment';
      String callbackUrl = 'your_callback_url'; // Optional

      var response = await _khalti.initiatePayment(
        merchantId: merchantId,
        publicKey: publicKey,
        amount: amount,
        description: description,
        callbackUrl: callbackUrl,
      );

      if (response.status == 'success') {
        // Payment successful, handle the response
        print('Payment successful: ${response.data}');
      } else {
        // Payment failed, handle the error
        print('Payment failed: ${response.message}');
      }
    } catch (e) {
      print('Error initiating payment: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Khalti Payment Example'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: _initiatePayment,
          child: Text('Initiate Payment'),
        ),
      ),
    );
  }
}

注意事项

  1. 替换占位符:确保将代码中的merchantId, publicKey, amount, 和 callbackUrl替换为你自己的实际值。
  2. 错误处理:在生产环境中,你应该添加更完善的错误处理和用户反馈机制。
  3. 安全性:不要在客户端代码中硬编码敏感信息,如API密钥等。考虑使用环境变量或安全存储机制来管理这些信息。

这个示例展示了如何使用khalti_flutter插件在Flutter应用中发起支付请求。根据实际需求,你可能需要调整代码来处理支付成功或失败后的逻辑,比如更新UI、通知用户等。

回到顶部