Flutter支付集成插件easypaisa_flutter的使用

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

Flutter支付集成插件easypaisa_flutter的使用

Easily integrate easypaisa payment option in your Flutter app.

🚀 Installation

Add this to dependencies in your app’s pubspec.yaml:

dependencies:
  easypaisa_flutter: latest_version

🔨 Initialization

Initialize the plugin in main.dart:

import 'package:easypaisa_flutter/easypaisa_flutter.dart';

void main() {
  EasypaisaFlutter.initialize(
    'username', // merchant account username
    'password', // merchant account password
    'storeId', // merchant storeId
    true, // is testing account or not
    AccountType.MA, // Merchant account type either Mobile account or OTC 
  );
  runApp(const MyApp());
}

: Usage

All requested parameters are of String type.

: Make a payment

import 'package:http/http.dart' as http;

Future<void> makePayment(String amount, String accountNumber, String email) async {
  http.Response response = await EasypaisaFlutter.requestPayment(
    amount,
    accountNumber,
    email,
  );

  print(response.body); // to print response body
}

Response Example:

{
  "orderId": "1709272404426",
  "storeId": "storeId",
  "transactionDateTime": "01/03/2024 10:53 AM",
  "responseCode": "0001",
  "responseDesc": "your response descriptions"
}

: Inquire previous payment

Future<void> inquirePaymentStatus(String orderId, String accountNumber) async {
  http.Response response = await EasypaisaFlutter.requestPaymentStatus(
    orderId,
    accountNumber,
  );

  print(response.body); // to print response body
}

Response Example:

{
  "orderId": "order Id",
  "accountNum": "654123987",
  "storeId": "store Id",
  "storeName": "PG Store 1",
  "paymentToken": "40931912",
  "transactionStatus": "PENDING",
  "transactionAmount": 12,
  "transactionDateTime": "09/08/2018 10:04 PM",
  "paymentTokenExpiryDateTime": "09/07/2019 05:06 PM",
  "msisdn": "03458508726",
  "paymentMode": "MA",
  "responseCode": "0000",
  "responseDesc": "SUCCESS"
}

示例代码 Demo

import 'package:easypaisa_flutter/easypaisa_flutter.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:http/http.dart' as http;

void main() {
  EasypaisaFlutter.initialize(
      'rideoptions',
      'd7d530ae300bf32090a2a0bc932ac708',
      '25056',
      true,
      AccountType.MA);
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: PaymentScreen(),
    );
  }
}

class PaymentScreen extends StatefulWidget {
  const PaymentScreen({super.key});

  @override
  State<PaymentScreen> createState() => _PaymentScreenState();
}

class _PaymentScreenState extends State<PaymentScreen> {
  final TextEditingController paymentAmountController = TextEditingController();
  final TextEditingController accountNumberController = TextEditingController();
  final TextEditingController emailController = TextEditingController();
  final Color primaryColor = const Color(0xff290D4A);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Payment Screen')),
      body: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          const SizedBox(height: 16.0),
          TextFormField(
            controller: accountNumberController,
            decoration: const InputDecoration(
              labelText: 'Account Number',
              border: OutlineInputBorder(),
            ),
          ),
          const SizedBox(height: 16.0),
          TextFormField(
            controller: paymentAmountController,
            decoration: const InputDecoration(
              labelText: 'Amount',
              border: OutlineInputBorder(),
            ),
          ),
          const SizedBox(height: 16.0),
          TextFormField(
            controller: emailController,
            decoration: const InputDecoration(
              labelText: 'Email',
              border: OutlineInputBorder(),
            ),
          ),
          ElevatedButton(
            style: ElevatedButton.styleFrom(
              foregroundColor: Colors.white,
              backgroundColor: primaryColor,
              elevation: 4.0,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(8.0),
              ),
            ),
            onPressed: () {
              if (accountNumberController.text.isEmpty) {
                Fluttertoast.showToast(
                  msg: "Please enter account number",
                  gravity: ToastGravity.BOTTOM,
                  backgroundColor: primaryColor,
                  textColor: Colors.white,
                );
              } else if (emailController.text.isEmpty) {
                Fluttertoast.showToast(
                  msg: "Please enter email",
                  gravity: ToastGravity.BOTTOM,
                  backgroundColor: primaryColor,
                  textColor: Colors.white,
                );
              } else if (paymentAmountController.text.isEmpty) {
                Fluttertoast.showToast(
                  msg: "Please enter amount",
                  gravity: ToastGravity.BOTTOM,
                  backgroundColor: primaryColor,
                  textColor: Colors.white,
                );
              } else {
                makePayment();
              }
            },
            child: const Text(
              'Continue',
              style: TextStyle(fontSize: 18.0),
            ),
          ),
        ],
      ),
    );
  }

  void makePayment() async {
    final http.Response response = await EasypaisaFlutter.requestPayment(
      amount: paymentAmountController.text.trim(),
      accountNo: accountNumberController.text.trim(),
      email: emailController.text.trim(),
    );
    print(response.body);
  }
}

Support the package by giving it a thumbs up at the top of this page or buy the developer a coffee here.


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

1 回复

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


当然,以下是如何在Flutter项目中集成和使用easypaisa_flutter插件的示例代码和步骤。请注意,由于easypaisa_flutter插件可能是一个虚构或特定于某个地区的插件,以下示例将基于一般的Flutter插件集成流程,并假设该插件提供类似的API接口。

步骤 1: 添加依赖

首先,你需要在pubspec.yaml文件中添加easypaisa_flutter插件的依赖。由于我无法直接访问最新的插件仓库,这里假设插件的依赖项如下:

dependencies:
  flutter:
    sdk: flutter
  easypaisa_flutter: ^x.y.z  # 请替换为实际版本号

确保替换^x.y.z为实际的插件版本号。

步骤 2: 获取插件

pubspec.yaml文件保存后,运行以下命令来获取插件:

flutter pub get

步骤 3: 导入插件

在你需要使用支付功能的Dart文件中导入插件:

import 'package:easypaisa_flutter/easypaisa_flutter.dart';

步骤 4: 初始化插件

根据插件的API文档,你可能需要在应用启动时初始化插件。这里假设有一个init方法:

void main() {
  runApp(MyApp());
  // 假设需要初始化插件
  EasyPaisaFlutter.init();
}

步骤 5: 使用插件进行支付

以下是一个简单的示例,展示如何使用插件进行支付。请注意,这里的API调用和参数是基于假设的,你应该参考实际的插件文档。

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Easy Paisa Payment Example'),
        ),
        body: Center(
          child: PaymentButton(),
        ),
      ),
    );
  }
}

class PaymentButton extends StatefulWidget {
  @override
  _PaymentButtonState createState() => _PaymentButtonState();
}

class _PaymentButtonState extends State<PaymentButton> {
  void _makePayment() async {
    try {
      // 假设这些是支付所需的参数
      String amount = "100"; // 金额
      String phoneNumber = "+921234567890"; // 用户电话号码
      String description = "Payment for goods"; // 支付描述

      // 调用插件的支付方法
      bool result = await EasyPaisaFlutter.makePayment(
        amount: amount,
        phoneNumber: phoneNumber,
        description: description,
      );

      if (result) {
        // 支付成功
        showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              title: Text("Payment Successful"),
              content: Text("Payment has been successfully processed."),
              actions: <Widget>[
                TextButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                  child: Text("OK"),
                ),
              ],
            );
          },
        );
      } else {
        // 支付失败
        showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              title: Text("Payment Failed"),
              content: Text("Payment processing failed. Please try again."),
              actions: <Widget>[
                TextButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                  child: Text("OK"),
                ),
              ],
            );
          },
        );
      }
    } catch (e) {
      // 处理异常
      print("Payment error: $e");
      showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text("Error"),
            content: Text("An error occurred during payment processing."),
            actions: <Widget>[
              TextButton(
                onPressed: () {
                  Navigator.of(context).pop();
                },
                child: Text("OK"),
              ),
            ],
          );
        },
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: _makePayment,
      child: Text("Make Payment"),
    );
  }
}

注意事项

  1. 实际参数:请确保你传递的参数(如金额、电话号码和描述)符合Easy Paisa的支付要求。
  2. 错误处理:在实际应用中,你可能需要更详细的错误处理逻辑。
  3. 安全性:确保支付过程中涉及的用户数据是安全的,并遵守相关的隐私政策。

由于easypaisa_flutter插件的具体实现细节可能有所不同,建议查阅该插件的官方文档以获取最准确的信息。

回到顶部