Flutter巴基斯坦支付插件paymob_pakistan的使用

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

Flutter巴基斯坦支付插件paymob_pakistan的使用

Easily accept Jazzcash/Easypaisa/Card Payments through Paymob Pakistan in your Flutter app.

🚀 Installation

在您的Flutter项目的pubspec.yaml文件中添加以下依赖:

dependencies:
  paymob_pakistan: latest_version

确保将latest_version替换为实际可用的最新版本号。

🔨 Initialization

初始化插件时需要提供API密钥和其他集成ID。以下是初始化示例:

import 'package:paymob_pakistan/paymob_payment.dart';

void main() {
  PaymobPakistan.instance.initialize(
    apiKey: "YOUR_API_KEY", // 从Paymob仪表板获取
    jazzcashIntegrationId: 123123, // 从Paymob仪表板获取
    easypaisaIntegrationID: 123123, // 从Paymob仪表板获取
    integrationID: 123456, // 从Paymob仪表板获取
    iFrameID: 123456, // 从Paymob仪表板获取
  );
  runApp(const MyApp());
}

您也可以创建自己的实例:

final PaymobPakistan paymobPakistan = PaymobPakistan();
paymobPakistan.initialize(
  apiKey: "YOUR_API_KEY",
  jazzcashIntegrationId: 123123,
  easypaisaIntegrationID: 123123,
  integrationID: 123456,
  iFrameID: 123456,
);

🔖 Usage

使用插件进行支付的示例如下:

final PaymobResponse? response = await PaymobPakistan.instance.pay(
  context: context,
  currency: "PKR",
  paymentType: PaymentType.card, // 或者使用PaymentType.jazzcash或PaymentType.easypaisa
  amountInCents: "50000", // 500 PKR
  onPayment: (response) => setState(() => this.response = response), // 可选
);

示例Demo

下面是一个完整的示例,展示如何在Flutter应用中集成和使用paymob_pakistan插件:

// ignore_for_file: use_build_context_synchronously

import 'package:flutter/material.dart';
import 'package:paymob_pakistan/paymob_payment.dart';

void main() {
  PaymobPakistan.instance.initialize(
    apiKey: "YOUR_API_KEY",
    integrationID: 123456,
    iFrameID: 123456,
    jazzcashIntegrationId: 123456,
    easypaisaIntegrationID: 123456,
  );
  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        appBarTheme: const AppBarTheme(color: Color(0xFF007aec)),
        elevatedButtonTheme: ElevatedButtonThemeData(
          style: ButtonStyle(
            backgroundColor: MaterialStateProperty.all(const Color(0xFF007aec)),
          ),
        ),
      ),
      debugShowCheckedModeBanner: false,
      home: const PaymentView(),
    );
  }
}

class PaymentView extends StatefulWidget {
  const PaymentView({Key? key}) : super(key: key);

  @override
  State<PaymentView> createState() => _PaymentViewState();
}

class _PaymentViewState extends State<PaymentView> {
  PaymobResponse? response;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Paymob')),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Image.network('https://paymob.pk/images/paymobLogo.png'),
            const SizedBox(height: 24),
            if (response != null)
              Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  Text("Success ==> ${response?.success}"),
                  const SizedBox(height: 8),
                  Text("Transaction ID ==> ${response?.transactionID}"),
                  const SizedBox(height: 8),
                  Text("Message ==> ${response?.message}"),
                  const SizedBox(height: 8),
                  Text("Response Code ==> ${response?.responseCode}"),
                  const SizedBox(height: 16),
                ],
              ),
            Column(
              children: [
                ElevatedButton(
                  child: const Text('Pay with Jazzcash'),
                  onPressed: () async {
                    try {
                      final response = await PaymobPakistan.instance.initializePayment(
                        currency: "PKR",
                        amountInCents: "100",
                      );

                      final authToken = response.authToken;
                      final orderID = response.orderID;

                      await PaymobPakistan.instance.makePayment(
                        context,
                        currency: "PKR",
                        amountInCents: "100",
                        paymentType: PaymentType.jazzcash,
                        authToken: authToken,
                        orderID: orderID,
                        onPayment: (response) => setState(() => this.response = response),
                      );
                    } catch (err) {
                      rethrow;
                    }
                  },
                ),
              ],
            )
          ],
        ),
      ),
    );
  }
}

🧪 Testing Cards

✅ Successful payment

  • Card Number: 5123456789012346
  • Expiry Month: 12
  • Expiry Year: 25
  • CVV: 123
  • Name: Test Account

❎ Declined payment

  • Change CVV to 111 or expiry year to 20

Credits

所有API的功劳归于Paymob Pakistan。访问Paymob Pakistan以获取您的PayMob账户,并在您的Flutter应用程序中接受数字支付。可能需要联系Paymob支持来激活测试卡。


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

1 回复

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


当然,以下是如何在Flutter项目中使用paymob_pakistan插件的示例代码。这个插件主要用于集成Paymob支付网关到巴基斯坦的应用程序中。

前提条件

  1. 确保你已经在Flutter项目中添加了paymob_pakistan依赖。
  2. 确保你已经有了Paymob的API密钥和其他必要的配置信息。

步骤 1: 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  paymob_pakistan: ^最新版本号 # 请替换为最新版本号

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

步骤 2: 配置Paymob

在你的Flutter应用中,你需要初始化Paymob配置。这通常在应用的入口文件(如main.dart)中进行。

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

void main() {
  // 初始化Paymob配置
  Paymob.configure(
    publicKey: '你的Paymob公钥', // 替换为你的Paymob公钥
    privateKey: '你的Paymob私钥', // 替换为你的Paymob私钥
    environment: PaymobEnvironment.sandbox, // 测试环境使用sandbox,生产环境使用production
  );

  runApp(MyApp());
}

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

步骤 3: 创建支付请求

在你的主屏幕或其他适当的页面中,创建一个按钮来触发支付请求。

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

class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  void initiatePayment() async {
    try {
      // 创建支付请求数据
      final paymentRequest = PaymobPaymentRequest(
        amount: 1000, // 支付金额,单位为最小货币单位(例如,巴基斯坦卢比的最小单位为1)
        currency: 'PKR', // 货币代码
        orderId: 'order_${DateTime.now().millisecondsSinceEpoch}', // 订单ID,需唯一
        description: '测试商品描述', // 商品描述
        returnUrl: 'https://your-return-url.com', // 支付完成后返回的URL
        notifyUrl: 'https://your-notify-url.com', // 支付通知URL
      );

      // 发起支付请求
      final result = await Paymob.startPayment(context, paymentRequest);

      // 处理支付结果
      if (result.isSuccessful) {
        // 支付成功
        print('支付成功: ${result.data}');
      } else {
        // 支付失败或取消
        print('支付失败或取消: ${result.errorMessage}');
      }
    } catch (e) {
      // 处理异常
      print('支付过程中发生错误: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Paymob支付示例'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: initiatePayment,
          child: Text('发起支付'),
        ),
      ),
    );
  }
}

注意事项

  1. 安全性:不要在客户端代码中硬编码私钥。私钥应该安全地存储在服务器端,并由服务器生成支付令牌(token)发送到客户端。
  2. 测试环境:在测试环境中测试你的集成,确保一切正常工作后再切换到生产环境。
  3. 错误处理:添加适当的错误处理逻辑,以处理各种可能的异常情况。

以上代码展示了如何在Flutter应用中使用paymob_pakistan插件来发起支付请求。根据你的具体需求,你可能需要调整代码中的参数和逻辑。

回到顶部