Flutter支付处理插件worldline_pg的使用

Flutter支付处理插件worldline_pg的使用

Worldline PG(支付网关)Flutter插件提供了你Flutter应用与Worldline支付网关原生代码之间的无缝集成。此插件使你能够轻松地将Worldline强大的支付处理能力整合到你的Flutter应用中,从而实现安全可靠的支付交易。

功能

  • 将你的Flutter应用与Worldline支付网关原生代码连接。
  • 执行各种支付相关操作,如生成请求哈希、解析响应等。
  • 轻松处理支付响应数据并检索交易详情。
  • 与Flutter应用平滑集成,确保用户获得无缝体验。
  • 利用Worldline支付网关的功能简化支付相关任务。

开始使用

要使用Worldline PG Flutter插件,你需要遵循以下步骤:

1. 安装和配置Worldline支付网关SDK

Android

在集成插件之前,请确保已将Worldline SDK提供的jar文件放置在该插件的android文件夹中。

将jar文件复制到以下路径:

  • macOS 和 Linux: $HOME/.pub-cache/hosted/pub.dev
  • Windows: %LOCALAPPDATA%\Pub\Cache

路径为:

android/src/assets/merchant-kit-sdk.jar

2. 安装

pubspec.yaml文件中添加以下行:

dependencies:
  worldline_pg: ^0.0.1

3. 导入插件

在Dart代码中导入Worldline PG Flutter插件:

import 'package:worldline_pg/worldline_pg.dart';

4. 使用插件

利用插件的API来发起支付交易、获取支付状态并处理响应。以下是一个发起支付交易的示例:

Future<void> _getRequestHash() async {
    String MID = 'your_merchant_id';
    String _orderID = 'your_order_id';
    String requestHash;
    try {
        requestHash = await _worldlinePg.getTrnRequestHash(
            orderId: _orderID,
            /// for ₹1.00 use 100
            trnAmt: '100',
            trnCurrency: 'INR',
            meTransReqType: 'S',
            responseUrl: 'https://www.google.com',
            trnRemarks: 'College Fee',
        );
    } on PlatformException {
        requestHash = 'Failed to get request hash.';
    }

    var _bytes = Uint8List.fromList(
        utf8.encode("merchantRequest=$requestHash&$MID"));
}

请参阅插件的示例代码以获取更多可用API及其使用方法。

问题与贡献

此包仍处于测试阶段,可能会有所更改。如果你遇到任何与Worldline PG Flutter插件相关的问题或希望为其开发做出贡献,请访问GitHub仓库。你的反馈和贡献将不胜感激。

许可证

此插件根据BSD-3-Clause许可证发布。请查阅LICENSE文件以获取更多详细信息。


示例代码

以下是示例代码的完整示例:

// ignore_for_file: constant_identifier_names

import 'dart:convert';
import 'dart:developer';

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

import 'package:flutter/services.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:worldline_pg/worldline_pg.dart';

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

const String ENC_KEY = 'abcdefghiklgmno01234567';
const String FORM_ACTION_URL = "https://ipg.in.worldline.com/doMEPayRequest";
const String GET_TRANS_STATUS = "https://ipg.in.worldline.com/getTransactionStatus";
const String MID = 'WL000000000000';

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

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

  [@override](/user/override)
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: PaymentStatus(),
    );
  }
}

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

  [@override](/user/override)
  State<PaymentStatus> createState() => _PaymentStatusState();
}

class _PaymentStatusState extends State<PaymentStatus> {
  final _worldlinePg = WorldlinePg(
    enckey: ENC_KEY,
    mid: MID,
  );
  String _paymentStatus = 'Payment not initiated';

  _loadPaymentStatus(String orderId) async {
    var trnResParams = await _getPaymentStatus(orderId: orderId, url: GET_TRANS_STATUS);
    var url = Uri.parse(GET_TRANS_STATUS);
    var encryptedResponse = await http.post(
      url,
      body: trnResParams,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
    ).then((value) => value.body);
    log('Encrypted Response: $encryptedResponse');

    var decryptedResponse = await _worldlinePg.getParsedTrnResMsg(
      response: encryptedResponse,
    );
    log('Decrypted Response: ${decryptedResponse.toJson()}');

    setState(() {
      _paymentStatus = decryptedResponse.statusDesc;
    });
  }

  Future<String> _getPaymentStatus({
    required String orderId,
    required String url,
  }) async {
    String paymentStatus;
    try {
      paymentStatus = await _worldlinePg.getTrnResParams(
        orderId: orderId,
        url: url,
      );
    } on PlatformException {
      paymentStatus = 'Failed to get payment status.';
    }

    log('Payment Status: $paymentStatus');
    return paymentStatus;
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Payment Status'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              _paymentStatus,
            ),
            ElevatedButton(
              onPressed: () {
                Navigator.of(context)
                    .push(
                  MaterialPageRoute(
                    builder: (context) => const PaymentPage(),
                  ),
                )
                    .then((value) {
                  _loadPaymentStatus(value);
                });
              },
              child: const Text('Initiate Payment'),
            )
          ],
        ),
      ),
    );
  }
}

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

  [@override](/user/override)
  State<PaymentPage> createState() => _PaymentPageState();
}

class _PaymentPageState extends State<PaymentPage> {
  Uint8List _bytes = Uint8List(0);
  final GlobalKey _webViewKey = GlobalKey();
  final _orderID = '${DateTime.now().millisecondsSinceEpoch}';
  bool _isLoading = true;
  final _worldlinePg = WorldlinePg.instance;

  [@override](/user/override)
  void initState() {
    super.initState();
    _getRequestHash();
  }

  Future<void> _getRequestHash() async {
    String requestHash;
    try {
      requestHash = await _worldlinePg.getTrnRequestHash(
        orderId: _orderID,
        trnAmt: '100',
        trnCurrency: 'INR',
        meTransReqType: 'S',
        responseUrl: 'https://www.google.com',
        trnRemarks: 'College Fee',
      );
    } on PlatformException {
      requestHash = 'Failed to get request hash.';
    }

    _bytes = Uint8List.fromList(
        utf8.encode("merchantRequest=$requestHash&MID=$MID"));

    if (!mounted) return;

    setState(() {
      _isLoading = false;
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        Navigator.pop(
          context,
          _orderID,
        );
        return false;
      },
      child: Scaffold(
        body: _isLoading
            ? const Center(
                child: CircularProgressIndicator(),
              )
            : InAppWebView(
                key: _webViewKey,
                initialUrlRequest: URLRequest(
                  url: Uri.parse(FORM_ACTION_URL),
                  method: 'POST',
                  body: _bytes,
                  headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                  },
                ),
                onReceivedServerTrustAuthRequest:
                    (controller, challenge) async {
                  // Do some checks here to decide if CANCELS or PROCEEDS
                  return ServerTrustAuthResponse(
                      action: ServerTrustAuthResponseAction.PROCEED);
                },
              ),
      ),
    );
  }
}

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

1 回复

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


当然,以下是一个关于如何在Flutter项目中使用worldline_pg插件进行支付处理的示例代码。请注意,实际使用中你可能需要根据具体需求和Worldline支付网关的API文档进行一些调整。

首先,确保你已经在pubspec.yaml文件中添加了worldline_pg依赖项:

dependencies:
  flutter:
    sdk: flutter
  worldline_pg: ^x.y.z  # 请替换为最新版本号

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

接下来,我们来看一个基本的支付处理示例。在这个示例中,我们假设你已经从Worldline获取了所有必要的配置信息(如商户ID、密钥等)。

1. 配置支付参数

在Flutter应用的某个地方(例如一个Dart文件),配置支付参数:

import 'package:worldline_pg/worldline_pg.dart';

// 配置支付参数
final paymentParams = PaymentParams(
  merchantId: 'your_merchant_id', // 替换为你的商户ID
  amount: 100.0, // 支付金额(单位:最小货币单位,例如:100表示1.00美元)
  currency: 'USD', // 货币代码
  orderId: 'unique_order_id', // 订单ID,需要唯一
  returnUrl: 'https://yourwebsite.com/return', // 支付完成后的回调URL
  notifyUrl: 'https://yourwebsite.com/notify', // 支付通知URL
  // 其他可选参数,根据Worldline的要求添加
);

2. 发起支付请求

在你的UI组件中(例如一个按钮点击事件),调用支付插件的支付方法:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: PaymentScreen(),
    );
  }
}

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

class _PaymentScreenState extends State<PaymentScreen> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Payment Screen'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () async {
            try {
              // 发起支付请求
              final result = await WorldlinePg.startPayment(paymentParams);
              // 处理支付结果
              if (result.success) {
                // 支付成功,处理后续逻辑
                print('Payment successful');
              } else {
                // 支付失败,处理错误
                print('Payment failed: ${result.errorMessage}');
              }
            } catch (e) {
              // 处理异常
              print('An error occurred: $e');
            }
          },
          child: Text('Pay Now'),
        ),
      ),
    );
  }
}

3. 处理支付回调

确保你的服务器能够处理Worldline支付网关的回调通知(例如notifyUrl中指定的URL)。这部分逻辑通常在你的服务器端实现,而不是在Flutter应用中。

注意事项

  1. 安全性:确保所有敏感信息(如商户ID、密钥等)在客户端和服务器端都妥善保管。
  2. 支付参数:根据Worldline支付网关的要求,可能需要添加其他支付参数。
  3. 错误处理:在实际应用中,需要更完善的错误处理逻辑,以应对各种可能的异常情况。
  4. 测试环境:在正式上线之前,务必在测试环境中充分测试支付流程。

以上是一个基本的Flutter应用中使用worldline_pg插件进行支付处理的示例代码。希望这对你有所帮助!

回到顶部