Flutter支付集成插件easy_pay的使用

Flutter支付集成插件easy_pay的使用

在flutter应用内实现:

dependencies:
   easy_pay: ^0.0.4

Android 端

本指南提供了逐步指导,以配置您的Flutter项目所需的Android依赖项和设置。

第一步:将SoftPos-v1.3.66.11-Debug_Test.aar添加到您的项目

  1. 导航到您的Flutter项目的android文件夹。
  2. android文件夹内创建一个名为libs的新文件夹。
  3. SoftPos-v1.3.66.11-Debug_Test.aar文件粘贴到libs文件夹中。

第二步:在AndroidManifest.xml文件中添加以下权限

  <uses-permission android:name="android.permission.INTERNET" />
  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
  <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

第三步:更新build.gradle文件

  1. 打开android/app/build.gradle文件。
  2. dependencies部分,添加以下代码行:
implementation 'com.sdk:easypay:1.1.5'
implementation 'com.denovo:topliteapp:1.7.5.1'
compileOnly files('libs/SoftPos-v1.3.66.11-Debug_Test.aar')

第四步:在MainActivity中扩展FlutterActivity

  1. 导航到android/app/src/main/kotlin/your/package/name/
  2. 创建或更新MainActivity.kt文件,使用以下代码:
import android.os.Bundle
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugins.GeneratedPluginRegistrant

class MainActivity : FlutterActivity() {

    private val CHANNEL = "easy_pay"
    private var easyPayPlugin: EasyPayPlugin? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // 初始化EasyPay插件
        easyPayPlugin = EasyPayPlugin()
        easyPayPlugin?.setActivity(this)
    }

    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        GeneratedPluginRegistrant.registerWith(flutterEngine)
        easyPayPlugin?.let {
            flutterEngine.plugins.add(it)
        }

        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result ->
            when (call.method) {
                "startPayment" -> {
                    val secretKey = call.argument<String>("secretKey") ?: ""
                    val jsonRequest = call.argument<String>("jsonRequest") ?: ""
                    easyPayPlugin?.onMethodCall(call, result)
                }
                "registerDevice" -> {
                    val tpn = call.argument<String>("tpn") ?: ""
                    val merchantKey = call.argument<String>("merchantKey") ?: ""
                    easyPayPlugin?.onMethodCall(call, result)
                }
                else -> {
                    result.notImplemented()
                }
            }
        }
    }
}

通过以上步骤,您可以成功地为您的Flutter项目配置必要的Android依赖项和设置。如果遇到任何问题,请参阅相应的文档以获取更多帮助。

第五步:在settings.gradle文件中,在repositories部分添加以下代码

maven {
        url = uri("s3://denovo-android.s3.amazonaws.com")
        credentials(AwsCredentials) {
            accessKey = "accessKey"
            secretKey = "secretKey"
        }
    }
  maven {
        url = uri("gitUrl")
        credentials {
            username = "Username"
            password = "password"
        }
    }

第六步:在gradle.properties中添加以下代码

android.enableJetifier=true
android.disableAutomaticComponentCreation=true

第七步:在Android端调用函数

  Future<void> startTransaction() async {
   try {
      var status = await Permission.location.status;
      if (!status.isGranted) {
         status = await Permission.location.request();
         if (!status.isGranted) {
            showSnackbar('位置权限被拒绝。请允许该权限。');
            return;
         }
      }

      final response = await _easyPay.registerDevice('tpnKey', 'merchantKey');
      print("交易成功: $response");

      Map<String, dynamic> decodedResponse = jsonDecode(response ?? '{}');
      String? sessionKey = decodedResponse['session_key'];

      if (sessionKey != null) {
         print('会话密钥: $sessionKey');
         var uuid = Uuid();
         // 除类型外,更改参数值为您自己的值
         Map<String, dynamic> paymentData = {
            'type': 'SALE', // 必须为SALE
            'amount': '1', // 更改金额值为您自己的值
            'isreceiptsneeded': false,
            'showapprovalscreen': false,
            'Customobject': {
               'customeremail': 'graghu@denovosystem.com',
               'PhoneNumber': '919840720372',
               'CreditType': '1',
               'NumberOfPayments': '1',
               'ExtraData': '[]',
               'HolderID': '1',
               'TransactionUniqueIdForQuery': uuid.v1()
            }
         };

         String jsonRequest = jsonEncode(paymentData);

         final paymentResponse = await _easyPay.startPayment(sessionKey, jsonRequest);
         print('付款已启动: $paymentResponse');

      } else {
         print('响应中未找到会话密钥。');
      }

   } catch (e) {
      showSnackbar('启动交易失败: $e');
   }
}

iOS 端

本指南提供了逐步指导,以配置您的Flutter项目所需的iOS依赖项和设置。

第一步:在info.plist文件中添加以下权限

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

<key>NSLocationWhenInUseUsageDescription</key>
<string>使用期间访问位置的原因</string>

<key>NSLocationAlwaysUsageDescription</key>
<string>始终访问位置的原因</string>

第二步:iOS示例代码

Future<void> makeRequest() async {
    try {
      final response = await _easyPay.requestWith('merchantKey');
      print("请求成功: $response");
    } catch (e) {
      showSnackbar('请求失败: $e');
    }
  }

  Future<void> performTransaction() async {
    try {
      final response = await _easyPay.transactionWith(100.0, 1);  // 更改金额值为您自己的值
      print("交易成功: $response");
    } catch (e) {
      showSnackbar('执行交易失败: $e');
    }
  }

首先调用makeRequest()函数。然后调用performTransaction()

有关更多信息,请参阅示例选项卡。

示例代码

import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:easy_pay/easy_pay.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:uuid/uuid.dart';

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

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

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

class _MyAppState extends State<MyApp> {
  String _platformVersion = 'Unknown';
  final EasyPay _easyPay = EasyPay();
  String? _sessionKey;

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

  Future<void> initPlatformState() async {
    try {
      final version = await _easyPay.getPlatformVersion() ?? '未知平台版本';
      setState(() {
        _platformVersion = version;
      });
    } catch (e) {
      print('获取平台版本失败: $e');
    }
  }

  void showSnackbar(String message) {
    final snackBar = SnackBar(content: Text(message));
    ScaffoldMessenger.of(context).showSnackBar(snackBar);
  }

  Future<void> startTransaction() async {
    try {
      var status = await Permission.location.status;
      if (!status.isGranted) {
        status = await Permission.location.request();
        if (!status.isGranted) {
          showSnackbar('位置权限被拒绝。请允许该权限。');
          return;
        }
      }

      final response = await _easyPay.registerDevice('tpnKey', 'merchantKey');
      print("交易成功: $response");

      Map<String, dynamic> decodedResponse = jsonDecode(response ?? '{}');
      String? sessionKey = decodedResponse['session_key'];

      if (sessionKey != null) {
        print('会话密钥: $sessionKey');
        var uuid = Uuid();

        Map<String, dynamic> paymentData = {
          'type': 'SALE',
          'amount': '1',
          'isreceiptsneeded': false,
          'showapprovalscreen': false,
          'Customobject': {
            'customeremail': 'graghu@denovosystem.com',
            'PhoneNumber': '919840720372',
            'CreditType': '1',
            'NumberOfPayments': '1',
            'ExtraData': '[]',
            'HolderID': '1',
            'TransactionUniqueIdForQuery': uuid.v1()
          }
        };

        String jsonRequest = jsonEncode(paymentData);

        final paymentResponse = await _easyPay.startPayment(sessionKey, jsonRequest);
        print('付款已启动: $paymentResponse');

      } else {
        print('响应中未找到会话密钥。');
      }

    } catch (e) {
      showSnackbar('启动交易失败: $e');
    }
  }

  Future<void> makeRequest() async {
    try {
      final response = await _easyPay.requestWith('merchantKey');
      print("请求成功: $response");
    } catch (e) {
      showSnackbar('请求失败: $e');
    }
  }

  Future<void> performTransaction() async {
    try {
      final response = await _easyPay.transactionWith(100.0, 1);
      print("交易成功: $response");
    } catch (e) {
      showSnackbar('执行交易失败: $e');
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('插件示例应用'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text('运行在: $_platformVersion\n'),
              if (Platform.isAndroid)
                ElevatedButton(
                onPressed: () => startTransaction(),
                child: const Text('开始交易'),
              ),
              if (Platform.isIOS)
                ElevatedButton(
                onPressed: () => makeRequest(),
                child: const Text('发起请求'),
              ),
              if (Platform.isIOS)
                ElevatedButton(
                  onPressed: () => performTransaction(),
                  child: const Text('执行交易'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

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

1 回复

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


easy_pay 是一个 Flutter 插件,用于简化支付功能的集成。它支持多种支付方式,如支付宝、微信支付、Apple Pay、Google Pay 等。通过 easy_pay,开发者可以更轻松地在 Flutter 应用中实现支付功能。

以下是使用 easy_pay 插件的基本步骤和示例代码:

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  easy_pay: ^1.0.0  # 请使用最新版本

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

2. 初始化插件

在使用 easy_pay 之前,通常需要进行一些初始化操作,例如配置支付平台的相关参数。

import 'package:easy_pay/easy_pay.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // 初始化支付插件
  await EasyPay.init(
    alipayConfig: AlipayConfig(
      appId: 'your_alipay_app_id',
      rsaPrivateKey: 'your_rsa_private_key',
      rsaPublicKey: 'your_rsa_public_key',
    ),
    wechatPayConfig: WechatPayConfig(
      appId: 'your_wechat_app_id',
      partnerId: 'your_wechat_partner_id',
      prepayId: 'your_wechat_prepay_id',
      packageValue: 'your_wechat_package_value',
      nonceStr: 'your_wechat_nonce_str',
      timeStamp: 'your_wechat_timestamp',
      sign: 'your_wechat_sign',
    ),
    applePayConfig: ApplePayConfig(
      merchantIdentifier: 'your_apple_pay_merchant_identifier',
      countryCode: 'US',
      currencyCode: 'USD',
    ),
    googlePayConfig: GooglePayConfig(
      merchantId: 'your_google_pay_merchant_id',
      environment: Environment.test,  // 或 Environment.production
    ),
  );

  runApp(MyApp());
}

3. 发起支付

使用 EasyPay.pay 方法发起支付请求。你可以根据支付平台选择相应的支付方式。

void payWithAlipay() async {
  try {
    final result = await EasyPay.pay(
      PayType.alipay,
      orderInfo: 'your_order_info',
    );
    print('支付结果: $result');
  } catch (e) {
    print('支付失败: $e');
  }
}

void payWithWechat() async {
  try {
    final result = await EasyPay.pay(
      PayType.wechat,
      orderInfo: 'your_order_info',
    );
    print('支付结果: $result');
  } catch (e) {
    print('支付失败: $e');
  }
}

void payWithApplePay() async {
  try {
    final result = await EasyPay.pay(
      PayType.applePay,
      orderInfo: 'your_order_info',
    );
    print('支付结果: $result');
  } catch (e) {
    print('支付失败: $e');
  }
}

void payWithGooglePay() async {
  try {
    final result = await EasyPay.pay(
      PayType.googlePay,
      orderInfo: 'your_order_info',
    );
    print('支付结果: $result');
  } catch (e) {
    print('支付失败: $e');
  }
}

4. 处理支付结果

支付完成后,EasyPay.pay 方法会返回一个 PayResult 对象,你可以根据 PayResult 来处理支付结果。

enum PayResult {
  success,
  fail,
  cancel,
  unknown,
}

5. 示例 UI

以下是一个简单的 UI 示例,展示如何使用按钮触发支付:

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

class PaymentPage extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('支付'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ElevatedButton(
              onPressed: payWithAlipay,
              child: Text('支付宝支付'),
            ),
            ElevatedButton(
              onPressed: payWithWechat,
              child: Text('微信支付'),
            ),
            ElevatedButton(
              onPressed: payWithApplePay,
              child: Text('Apple Pay'),
            ),
            ElevatedButton(
              onPressed: payWithGooglePay,
              child: Text('Google Pay'),
            ),
          ],
        ),
      ),
    );
  }

  void payWithAlipay() async {
    try {
      final result = await EasyPay.pay(
        PayType.alipay,
        orderInfo: 'your_order_info',
      );
      print('支付结果: $result');
    } catch (e) {
      print('支付失败: $e');
    }
  }

  void payWithWechat() async {
    try {
      final result = await EasyPay.pay(
        PayType.wechat,
        orderInfo: 'your_order_info',
      );
      print('支付结果: $result');
    } catch (e) {
      print('支付失败: $e');
    }
  }

  void payWithApplePay() async {
    try {
      final result = await EasyPay.pay(
        PayType.applePay,
        orderInfo: 'your_order_info',
      );
      print('支付结果: $result');
    } catch (e) {
      print('支付失败: $e');
    }
  }

  void payWithGooglePay() async {
    try {
      final result = await EasyPay.pay(
        PayType.googlePay,
        orderInfo: 'your_order_info',
      );
      print('支付结果: $result');
    } catch (e) {
      print('支付失败: $e');
    }
  }
}

void main() {
  runApp(MaterialApp(
    home: PaymentPage(),
  ));
}
回到顶部