Flutter支付集成插件ezetap_sdk的使用

Flutter支付集成插件ezetap_sdk的使用

欢迎来到Ezetap Payments Flutter SDK集成指南!您可以轻松地通过集成该SDK从现有的Android应用程序中收集付款。

如何集成工作

  1. 在您的移动应用中包含SDK以收集付款。
  2. SDK与服务应用进行接口通信,此应用将在运行时安装。
  3. 服务应用与卡设备和Ezetap服务器进行接口通信以完成付款处理,并将状态通知给SDK。

前提条件

支持Android API版本21或以上。

使用此包作为库

这将在您的包的pubspec.yaml文件中添加类似以下内容的一行(并运行隐式的flutter pub get):

dependencies:
  ezetap_sdk: ^0.2.6

导入它

现在在您的Dart代码中,您可以使用以下导入语句:

import 'package:ezetap_sdk/ezetap_sdk.dart';

可用方法

var json = {
  "prodAppKey": "Your prod app key",
  "demoAppKey": "Your demo app key",
  "merchantName": "merchantName",
  "userName": "userName",
  "currencyCode": 'INR',
  "appMode": "Your environment",
  "captureSignature": 'true',
  "prepareDevice": 'false',
  "captureReceipt": 'false'
};

EzetapSdk.initialize(json);
EzetapSdk.prepareDevice();
var sendReceiptJson = {
  "customerName": "customerName",
  "mobileNo": "mobileNo",
  "email": "emailId",
  "txnId": "transactionID"
};

EzetapSdk.sendReceipt(sendReceiptJson);
var json = {
  "issueType": "issueType",
  "issueInfo": "issueInfo",
  "tags": [
    "tag1", "tag2"
  ]
};

EzetapSdk.serviceRequest(json);
var json = {
  "agentName": "username",
  "saveLocally": false
};

EzetapSdk.searchTransaction(json);
var json = {
  "amount": "100",
  "options": {
    "amountTip": 0.0,
    "references": {
      "reference1": "sffr",
      "additionalReferences": []
    },
    "customer": {},
    "serviceFee": -1.0,
    "addlData": {
      "addl1": "addl1",
      "addl2": "addl2",
      "addl3": "addl3"
    },
    "appData": {
      "app1": "app1",
      "app2": "app2",
      "app3": "app3"
    }
  }
};

EzetapSdk.getTransaction(json);
var json = {};
EzetapSdk.checkForIncompleteTransaction(json);
// 传递交易ID到此函数
EzetapSdk.voidTransaction(String transactionID);
var json = {"txnId": "transactionID"};
EzetapSdk.attachSignature(json);
var json = {
  "amount": "123",
  "options": {
    "serviceFee": 100,
    "payToAccount": "LABEL",
    "paymentBy": "CREDIT OR DEBIT OR ANY (**To be used only if the service fee is being added.)",
    "paymentMode": "Card/Cash/Cheque/UPI/UPI_VOUCHER/RemotePay/BHARATQR/Brand_Offers/Brand_EMI/Normal_EMI/Wallet ",
    "providerName": "<NBFC> eg. ZestMoney. (**providerName and emiType are to be passed only if user wants to use ZestMoney. In this scenario, set \"paymentMode\": \"EMI\")",
    "emiType": "NORMAL, BRAND, EMI",
    "references": {
      "reference1": "1234",
      "additionalReferences": [
        "addRef_xx1",
        "addRef_xx2"
      ]
    },
    "appData": {
      "walletAcquirer": "freecharge/ola_money/ etc.(**walletAcquirer are to be passed only if user sets \"paymentMode\": \"Wallet\")"
    },
    "customer": {
      "name": "xyz",
      "mobileNo": "1234567890",
      "email": "abc@xyz.com"
    }
  }
};

EzetapSdk.pay(json);
// 传递交易ID到此函数
EzetapSdk.printReceipt(String transactionID);
// 传递图像作为base64字符串到此函数
EzetapSdk.printBitmap(String? base64Image);
EzetapSdk.logout();
var json = {"txnIds": [""]};
EzetapSdk.stopPayment(json);
EzetapSdk.scanBarcode();
var json = {
  "amount": "100",
  "txnId": "transactionID"
};
EzetapSdk.refundTransaction(json);
EzetapSdk.checkForUpdates();
EzetapSdk.checkPrinterStatus();
EzetapSdk.printTextReceipt(txtReceipt);
EzetapSdk.showReceiptView(jsonEncode(receipt));
EzetapSdk.getDeviceInfo();
Future<void> onPaymentClicked(json) async {
  String? result = await EzetapSdk.pay(json);
  if (!mounted) return;
  setState(() {
    _result = result;
  });
}
Future<void> onBarcodePressed() async {
  String? result = await EzetapSdk.scanBarcode();
  if (!mounted) return;
  setState(() {
    _result = result;
  });
}
Future<void> checkPrinterStatus() async {
  String? result = await EzetapSdk.checkPrinterStatus();
  if (!mounted) return;
  setState(() {
    _result = result;
  });
}
Future<void> printTextReceipt() async {
  var txtReceipt = "-----------------------------------\n" +
      "           Receipt\n" +
      "-----------------------------------\n" +
      "\n" +
      "Date: January 9, 2024\n" +
      "Time: 12:30 PM\n" +
      "\n" +
      "-----------------------------------\n" +
      "\n" +
      "Items Purchased:\n" +
      "1. Item Name        10.00\n" +
      "2. Another Item     15.50\n" +
      "3. Yet Another Item 8.75\n" +
      "\n" +
      "-----------------------------------\n" +
      "\n" +
      "Subtotal:           34.25\n" +
      "Tax (8%):           2.74\n" +
      "Total Amount:       36.99\n" +
      "\n" +
      "-----------------------------------\n" +
      "\n" +
      "Payment Method:     Credit Card\n" +
      "\n" +
      "Card Number:        **** **** **** 1234\n" +
      "Expiry Date:        12/25\n" +
      "Authorization Code: 56789\n" +
      "\n" +
      "-----------------------------------\n" +
      "\n" +
      "Thank you for your purchase!\n" +
      "Please come again.\n" +
      "\n" +
      "-----------------------------------";

  String? result = await EzetapSdk.printTextReceipt(txtReceipt);
  if (!mounted) return;
  setState(() {
    _result = result;
  });
}
Future<void> showCustomReceiptView() async {
  final ByteData data = await rootBundle.load('assets/logo.png');
  final Uint8List bytes = data.buffer.asUint8List();
  ui.decodeImageFromList(bytes, (ui.Image img) async {
    ByteData? byteData = await img.toByteData(format: ui.ImageByteFormat.png);
    var receipt = [
      base64.encode(byteData?.buffer.asUint8List() as List<int>),
      "<div class=\"item\" style=\"text-align: center;\"><span style=\"font-size: 34;\"><big>Heading</big></span></div>",
      "<div class=\"item\"><span>Date:</span> <span>2024-02-12</span></div>",
      "<div class=\"item\"><span>Time:</span> <span>15:30</span></div>",
      "<div class=\"item\"><span>Receipt No:</span> <span>123456</span></div>",
      "<div class=\"item\"><span>Items:</span><ul><li>Item 1 - \$10</li><li>Item 2 - \$20</li><li>Item 3 - \$15</li></ul></div>",
      "<div class=\"item\"><span>Total:</span> <span>\$45</span></div>",
      "<div class=\"item\"><span>Date:</span> <span>2024-02-12</span></div>",
      "<div class=\"item\"><span>Time:</span> <span>15:30</span></div>",
      "<div class=\"item\"><span>Receipt No:</span> <span>123456</span></div>",
      "<div class=\"item\"><span>Items:</span><ul><li>Item 1 - \$10</li><li>Item 2 - \$20</li><li>Item 3 - \$15</li></ul></div>",
      "<div class=\"item\"><span>Total:</span> <span>\$45</span></div>",
      "<div class=\"item\"><span>Date:</span> <span>2024-02-12</span></div>",
      "<div class=\"item\"><span>Time:</span> <span>15:30</span></div>",
      "<div class=\"item\"><span>Receipt No:</span> <span>123456</span></div>",
      "<div class=\"item\"><span>Items:</span><ul><li>Item 1 - \$10</li><li>Item 2 - \$20</li><li>Item 3 - \$15</li></ul></div>",
      "<div class=\"item\"><span>Total:</span> <span>\$45</span></div>",
      base64.encode(byteData?.buffer.asUint8List() as List<int>)
    ];
    try {
      String? result = await EzetapSdk.showReceiptView(jsonEncode(receipt));
      if (!mounted) return;
      setState(() {
        _result = result;
      });
    } on PlatformException catch (e) {
      if (!mounted) return;
      setState(() {
        _result = e.message.toString();
      });
    }
  });
}

您需要什么

  1. Flutter开发环境
  2. 可以连接互联网的Android手机
  3. 本文档
  4. Ezetap应用密钥或登录凭证以访问Ezetap服务
  5. 用于测试卡支付的Ezetap设备

示例代码

以下是main.dart文件的示例代码:

import 'dart:async';
import 'dart:convert';
import 'dart:ui' as ui;

import 'package:eze_sdk_flutter_example/re_print.dart';
import 'package:ezetap_sdk/ezetap_sdk.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:screenshot/screenshot.dart';

void main() {
  runApp(const MaterialApp(home: MyApp()));
}

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

  [@override](/user/override)
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _result = 'Unknown';

  // 平台消息是异步的,因此我们在异步方法中初始化
  Future<void> initSdk() async {
    var json = {
      "prodAppKey": "",
      "demoAppKey": "",
      "merchantName": "",
      "userName": "",
      "currencyCode": 'INR',
      "appMode": "DEMO",
      "captureSignature": 'true',
      "prepareDevice": 'false',
      "captureReceipt": 'false'
    };
    String? result = await EzetapSdk.initialize(jsonEncode(json));
    if (!mounted) return;
    setState(() {
      _result = result;
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Ezetap Sample'),
        ),
        body: Center(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              ElevatedButton(onPressed: initSdk, child: const Text("SDK Init")),
              ElevatedButton(
                  onPressed: onPreparePressed,
                  child: const Text("Prepare Device")),
              ElevatedButton(
                  onPressed: () {
                    onPressed(context);
                  },
                  child: const Text("Print Bitmap")),
              ElevatedButton(
                  onPressed: onBarcodePressed,
                  child: const Text("Scan Barcode")),
              ElevatedButton(
                  onPressed: checkPrinterStatus,
                  child: const Text("Printer Status")),
              ElevatedButton(
                  onPressed: printTextReceipt,
                  child: const Text("Print Text Receipt")),
              ElevatedButton(
                  onPressed: showCustomReceiptView,
                  child: const Text("Print Custom Receipt")),
              ElevatedButton(
                  onPressed: onGetDeviceInfo,
                  child: const Text("Device Info")),
              Expanded(
                flex: 1,
                child: SingleChildScrollView(
                    scrollDirection: Axis.vertical, child: Text(_result)),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Future<void> onGetDeviceInfo() async {
    String? result = await EzetapSdk.getDeviceInfo();
    if (!mounted) return;
    setState(() {
      _result = result;
    });
  }

  Future<void> onBarcodePressed() async {
    String? result = await EzetapSdk.scanBarcode();
    if (!mounted) return;
    setState(() {
      _result = result;
    });
  }

  Future<void> onPressed(BuildContext context) async {
    final controller = ScreenshotController();

    ///@author TIJO THOMAS
    ///BillWidget是用于创建base64的假收据小部件
    ///const BoxConstraints(maxHeight: 1500),根据您的收据更改高度
    final bytes = await controller.captureFromLongWidget(
      InheritedTheme.captureAll(context, const Material(child: ReprintPage())),
      pixelRatio: 2.0,
      context: context,
      constraints: const BoxConstraints(maxHeight: 1500),
      delay: const Duration(milliseconds: 100),
    );
    var base64Image = base64Encode(bytes);
    debugPrint(base64Image);
    try {
      String? result = await EzetapSdk.printBitmap(base64Image);
      if (!mounted) return;
      setState(() {
        _result = result;
      });
    } on PlatformException catch (e) {
      if (!mounted) return;
      setState(() {
        _result = e.message.toString();
      });
    }
  }

  Future<void> onPreparePressed() async {
    String? result = await EzetapSdk.prepareDevice();
    if (!mounted) return;
    setState(() {
      _result = result;
    });
  }

  Future<void> checkPrinterStatus() async {
    String? result = await EzetapSdk.checkPrinterStatus();
    if (!mounted) return;
    setState(() {
      _result = result;
    });
  }

  Future<void> printTextReceipt() async {
    var txtReceipt = "-----------------------------------\n" +
        "           Receipt\n" +
        "-----------------------------------\n" +
        "\n" +
        "Date: January 9, 2024\n" +
        "Time: 12:30 PM\n" +
        "\n" +
        "-----------------------------------\n" +
        "\n" +
        "Items Purchased:\n" +
        "1. Item Name        10.00\n" +
        "2. Another Item     15.50\n" +
        "3. Yet Another Item 8.75\n" +
        "\n" +
        "-----------------------------------\n" +
        "\n" +
        "Subtotal:           34.25\n" +
        "Tax (8%):           2.74\n" +
        "Total Amount:       36.99\n" +
        "\n" +
        "-----------------------------------\n" +
        "\n" +
        "Payment Method:     Credit Card\n" +
        "\n" +
        "Card Number:        **** **** **** 1234\n" +
        "Expiry Date:        12/25\n" +
        "Authorization Code: 56789\n" +
        "\n" +
        "-----------------------------------\n" +
        "\n" +
        "Thank you for your purchase!\n" +
        "Please come again.\n" +
        "\n" +
        "-----------------------------------";
    try {
      String? result = await EzetapSdk.printTextReceipt(txtReceipt);
      if (!mounted) return;
      setState(() {
        _result = result;
      });
    } on PlatformException catch (e) {
      if (!mounted) return;
      setState(() {
        _result = e.message.toString();
      });
    }
  }

  Future<void> showCustomReceiptView() async {
    final ByteData data = await rootBundle.load('assets/logo.png');
    final Uint8List bytes = data.buffer.asUint8List();
    ui.decodeImageFromList(bytes, (ui.Image img) async {
      ByteData? byteData = await img.toByteData(format: ui.ImageByteFormat.png);
      var receipt = [
        base64.encode(byteData?.buffer.asUint8List() as List<int>),
        "<div class=\"item\" style=\"text-align: center;\"><span style=\"font-size: 34;\"><big>Heading</big></span></div>",
        "<div class=\"item\"><span>Date:</span> <span>2024-02-12</span></div>",
        "<div class=\"item\"><span>Time:</span> <span>15:30</span></div>",
        "<div class=\"item\"><span>Receipt No:</span> <span>123456</span></div>",
        "<div class=\"item\"><span>Items:</span><ul><li>Item 1 - \$10</li><li>Item 2 - \$20</li><li>Item 3 - \$15</li></ul></div>",
        "<div class=\"item\"><span>Total:</span> <span>\$45</span></div>",
        "<div class=\"item\"><span>Date:</span> <span>2024-02-12</span></div>",
        "<div class=\"item\"><span>Time:</span> <span>15:30</span></div>",
        "<div class=\"item\"><span>Receipt No:</span> <span>123456</span></div>",
        "<div class=\"item\"><span>Items:</span><ul><li>Item 1 - \$10</li><li>Item 2 - \$20</li><li>Item 3 - \$15</li></ul></div>",
        "<div class=\"item\"><span>Total:</span> <span>\$45</span></div>",
        "<div class=\"item\"><span>Date:</span> <span>2024-02-12</span></div>",
        "<div class=\"item\"><span>Time:</span> <span>15:30</span></div>",
        "<div class=\"item\"><span>Receipt No:</span> <span>123456</span></div>",
        "<div class=\"item\"><span>Items:</span><ul><li>Item 1 - \$10</li><li>Item 2 - \$20</li><li>Item 3 - \$15</li></ul></div>",
        "<div class=\"item\"><span>Total:</span> <span>\$45</span></div>",
        "<div class=\"item\"><span>Date:</span> <span>2024-02-12</span></div>",
        "<div class=\"item\"><span>Time:</span> <span>15:30</span></div>",
        "<div class=\"item\"><span>Receipt No:</span> <span>123456</span></div>",
        "<div class=\"item\"><span>Items:</span><ul><li>Item 1 - \$10</li><li>Item 2 - \$20</li><li>Item 3 - \$15</li></ul></div>",
        "<div class=\"item\"><span>Total:</span> <span>\$45</span></div>",
        base64.encode(byteData?.buffer.asUint8List() as List<int>)
      ];
      try {
        String? result = await EzetapSdk.showReceiptView(jsonEncode(receipt));
        if (!mounted) return;
        setState(() {
          _result = result;
        });
      } on PlatformException catch (e) {
        if (!mounted) return;
        setState(() {
          _result = e.message.toString();
        });
      }
    });
  }
}

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

1 回复

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


在Flutter项目中集成ezetap_sdk支付插件,可以按照以下步骤进行。假设你已经有一个Flutter项目,并且熟悉基本的Flutter开发流程。以下是一个基本的代码案例来展示如何使用ezetap_sdk插件。

1. 添加依赖

首先,在pubspec.yaml文件中添加ezetap_sdk依赖:

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

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

2. 配置iOS和Android

iOS配置

  • ios/Runner/Info.plist文件中,添加必要的权限配置,例如相机访问权限(如果需要)。
  • 确保在Xcode中配置好了支付相关的证书和标识符。

Android配置

  • android/app/src/main/AndroidManifest.xml文件中,添加必要的权限,例如:
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.INTERNET" />
  • android/app/build.gradle文件中,确保设置了正确的minSdkVersiontargetSdkVersion

3. 使用Ezetap SDK

在你的Flutter项目中,创建一个新的Dart文件(例如payment_screen.dart)来集成和使用Ezetap SDK。以下是一个基本的示例代码:

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

class PaymentScreen extends StatefulWidget {
  @override
  _PaymentScreenState createState() => _PaymentScreenState();
}

class _PaymentScreenState extends State<PaymentScreen> {
  final EzetapSdk _ezetapSdk = EzetapSdk();

  @override
  void initState() {
    super.initState();
    _initializeEzetapSdk();
  }

  Future<void> _initializeEzetapSdk() async {
    try {
      // 初始化SDK,替换为你的API密钥和商户ID
      await _ezetapSdk.initialize(
        apiKey: '你的API密钥',
        merchantId: '你的商户ID',
      );
      print('Ezetap SDK initialized successfully');
    } catch (e) {
      print('Failed to initialize Ezetap SDK: $e');
    }
  }

  Future<void> _startPayment() async {
    try {
      // 启动支付流程,替换为实际的支付参数
      final Map<String, dynamic> paymentDetails = {
        'amount': 100.0, // 支付金额
        'currency': 'USD', // 货币代码
        'orderId': 'unique_order_id_12345', // 订单ID
        // 其他必要的支付参数
      };

      final result = await _ezetapSdk.startPayment(paymentDetails);
      print('Payment result: $result');

      if (result['status'] == 'success') {
        // 支付成功处理逻辑
        showDialog(
          context: context,
          builder: (context) => AlertDialog(
            title: Text('Payment Successful'),
            content: Text('Transaction ID: ${result['transactionId']}'),
            actions: <Widget>[
              FlatButton(
                child: Text('OK'),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              ),
            ],
          ),
        );
      } else {
        // 支付失败处理逻辑
        showDialog(
          context: context,
          builder: (context) => AlertDialog(
            title: Text('Payment Failed'),
            content: Text('Error: ${result['error']}'),
            actions: <Widget>[
              FlatButton(
                child: Text('OK'),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              ),
            ],
          ),
        );
      }
    } catch (e) {
      print('Failed to start payment: $e');
      showDialog(
        context: context,
        builder: (context) => AlertDialog(
          title: Text('Error'),
          content: Text('An error occurred: $e'),
          actions: <Widget>[
            FlatButton(
              child: Text('OK'),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        ),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Payment Screen'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: _startPayment,
          child: Text('Start Payment'),
        ),
      ),
    );
  }
}

4. 运行应用

确保所有配置正确后,运行你的Flutter应用:

flutter run

这个示例展示了如何初始化Ezetap SDK并启动支付流程。请根据你的实际需求调整支付参数和处理逻辑。注意,在实际项目中,你应该妥善处理API密钥和敏感信息,避免硬编码在代码中。

回到顶部