Flutter支付桥接插件flutter_clickpay_bridge的使用

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

Flutter支付桥接插件flutter_clickpay_bridge的使用

安装

dependencies:
  flutter_clickpay_bridge: ^2.4.3

使用示例代码

import 'package:flutter_clickpay_bridge/*.dart';

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

class MyApp extends StatefulWidget {
  [@override](/user/override)
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _instructions = 'Tap on "Pay" Button to try Clickpay plugin';

  PaymentSdkConfigurationDetails generateConfig() {
    var billingDetails = BillingDetails("billing name", 
        "billing email", 
        "+97311111111",
        "st. 12", 
        "eg", 
        "dubai", 
        "dubai", 
        "12345");
        
    var shippingDetails = ShippingDetails("shipping name", 
     "shipping email", 
     "+97311111111",
     "st. 12", 
     "eg", 
     "dubai", 
     "dubai", 
     "12345");

    List<PaymentSdkAPms> apms = [];
    apms.add(PaymentSdkAPms.KNET_DEBIT);
    apms.add(PaymentSdkAPms.APPLE_PAY);

    var configuration = PaymentSdkConfigurationDetails(
        profileId: "profile id",
        serverKey: "your server key",
        clientKey: "your client key",
        cartId: "cart id",
        cartDescription: "cart desc",
        merchantName: "merchant name",
        screentTitle: "Pay with Card",
        amount: 20.0,
        currencyCode: "SAR",
        merchantCountryCode: "SA",
        billingDetails: billingDetails,
        shippingDetails: shippingDetails,
        alternativePaymentMethods: apms,
        linkBillingNameWithCardHolderName: true);

    return configuration;
  }

  Future<void> queryPressed() async {
    FlutterPaymentSdkBridge.queryTransaction(generateQueryConfig(), (event) {
      setState(() {
        if (event["status"] == "success") {
          // Handle transaction details here.
          var transactionDetails = event["data"];
          print(transactionDetails);
        } else if (event["status"] == "error") {
          // Handle error here.
        } else if (event["status"] == "event") {
          // Handle events here.
        }
      });
    });
  }

  Future<void> payPressed() async {
    FlutterPaymentSdkBridge.startCardPayment(generateConfig(), (event) {
      setState(() {
        if (event["status"] == "success") {
          // Handle transaction details here.
          var transactionDetails = event["data"];
          print(transactionDetails);
          if (transactionDetails["isSuccess"]) {
            print("successful transaction");
            if (transactionDetails["isPending"]) {
              print("transaction pending");
            }
          } else {
            print("failed transaction");
          }

          // print(transactionDetails["isSuccess"]);
        } else if (event["status"] == "error") {
          // Handle error here.
        } else if (event["status"] == "event") {
          // Handle events here.
        }
      });
    });
  }

  Future<void> payWithTokenPressed() async {
    FlutterPaymentSdkBridge.startTokenizedCardPayment(
        generateConfig(), "*Token*", "*TransactionReference*", (event) {
      setState(() {
        if (event["status"] == "success") {
          // Handle transaction details here.
          var transactionDetails = event["data"];
          print(transactionDetails);
          if (transactionDetails["isSuccess"]) {
            print("successful transaction");
            if (transactionDetails["isPending"]) {
              print("transaction pending");
            }
          } else {
            print("failed transaction");
          }

          // print(transactionDetails["isSuccess"]);
        } else if (event["status"] == "error") {
          // Handle error here.
        } else if (event["status"] == "event") {
          // Handle event here.
        }
      });
    });
  }

  Future<void> payWith3ds() async {
    FlutterPaymentSdkBridge.start3DSecureTokenizedCardPayment(
        generateConfig(),
        PaymentSDKSavedCardInfo("4111 11## #### 1111", "visa"),
        "*Token*", (event) {
      setState(() {
        if (event["status"] == "success") {
          // Handle transaction details here.
          var transactionDetails = event["data"];
          print(transactionDetails);
          if (transactionDetails["isSuccess"]) {
            print("successful transaction");
            if (transactionDetails["isPending"]) {
              print("transaction pending");
            }
          } else {
            print("failed transaction");
          }

          // print(transactionDetails["isSuccess"]);
        } else if (event["status"] == "error") {
          // Handle error here.
        } else if (event["status"] == "event") {
          // Handle event here.
        }
      });
    });
  }

  Future<void> payWithSavedCards() async {
    FlutterPaymentSdkBridge.startPaymentWithSavedCards(generateConfig(), false, (event) {
      setState(() {
        if (event["status"] == "success") {
          // Handle transaction details here.
          var transactionDetails = event["data"];
          print(transactionDetail);
          if (transactionDetail["isSuccess"]) {
            print("successful transaction");
            if (transactionDetail["isPending"]) {
              print("transaction pending");
            }
          } else {
            print("failed transaction");
          }

          // print(transactionDetail["isSuccess"]);
        } else if (event["status"] == "error") {
          // Handle error here.
        } else if (event["status"] == "event") {
          // Handle event here.
        }
      });
    });
  }

  Future<void> apmsPayPressed() async {
    FlutterPaymentSdkBridge.startAlternativePaymentMethod(
        await generateConfig(), (event) {
      setState(() {
        if (event["status"] == "success") {
          // Handle transaction details here.
          var transactionDetails = event["data"];
          print(transactionDetails);
        } else if (event["status"] == "error") {
          // Handle error here.
        } else if (event["status"] == "event") {
          // Handle event here.
        }
      });
    });
  }

  Future<void> applePayPressed() async {
    var configuration = PaymentSdkConfigurationDetails(
        profileId: "*Profile id*",
        serverKey: "*server key*",
        clientKey: "*client key*",
        cartId: "12433",
        cartDescription: "Flowers",
        merchantName: "Flowers Store",
        amount: 20.0,
        currencyCode: "AED",
        merchantCountryCode: "ae",
        merchantApplePayIdentifier: "merchant.com.bundleId",
        simplifyApplePayValidation: true);
    FlutterPaymentSdkBridge.startApplePayPayment(configuration, (event) {
      setState(() {
        if (event["status"] == "success") {
          // Handle transaction details here.
          var transactionDetails = event["data"];
          print(transactionDetails);
        } else if (event["status"] == "error") {
          // Handle error here.
        } else if (event["status"] == "event") {
          // Handle event here.
        }
      });
    });
  }

  Widget applePayButton() {
    if (Platform.isIOS) {
      return TextButton(
        onPressed: () {
          applePayPressed();
        },
        child: Text('Pay with Apple Pay'),
      );
    }
    return SizedBox(height: 0);
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Clickpay Plugin Example App'),
        ),
        body: Center(
            child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
              Text('$_instructions'),
              SizedBox(height: 16),
              TextButton(
                onPressed: () {
                  payPressed();
                },
                child: Text('Pay with Card'),
              ),
              TextButton(
                onPressed: () {
                  payWithTokenPressed();
                },
                child: Text('Pay with Token'),
              ),
              TextButton(
                onPressed: () {
                  payWith3ds();
                },
                child: Text('Pay with 3ds'),
              ),
              TextButton(
                onPressed: () {
                  payWithSavedCards();
                },
                child: Text('Pay with saved cards'),
              ),
              SizedBox(height: 16),
              TextButton(
                onPressed: () {
                  apmsPayPressed();
                },
                child: Text('Pay with Alternative payment methods'),
              ),
              SizedBox(height: 16),
              TextButton(
                onPressed: () {
                  queryPressed();
                },
                child: Text('Query transaction'),
              ),
              SizedBox(height: 16),
              applePayButton()
            ])),
      ),
    );
  }

  PaymentSDKQueryConfiguration generateQueryConfig() {
    return new PaymentSDKQueryConfiguration(
        "ServerKey",
        "ClientKey",
        "Country Iso 2",
        "Profile Id",
        "Transaction Reference");
  }
}

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

1 回复

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


当然,以下是关于如何在Flutter项目中使用flutter_clickpay_bridge插件的一个代码示例。这个插件假设是用来桥接Flutter应用与ClickPay支付平台的。请注意,具体的使用方法和API可能会根据插件的版本和ClickPay的API变化而有所不同。以下示例代码仅作为参考,请根据插件的官方文档和ClickPay的API文档进行调整。

首先,确保你的Flutter项目中已经添加了flutter_clickpay_bridge插件。在pubspec.yaml文件中添加依赖:

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

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

接下来,在Flutter项目中配置和使用该插件。以下是一个简单的示例,展示如何初始化插件并进行支付请求:

1. 导入插件

在你的Dart文件中(例如main.dart),导入flutter_clickpay_bridge插件:

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

2. 初始化插件

在应用的入口点(通常是main.dart中的_MyAppState类或者MyApp函数中),初始化插件:

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

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

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  FlutterClickpayBridge _flutterClickpayBridge;

  @override
  void initState() {
    super.initState();
    _flutterClickpayBridge = FlutterClickpayBridge();
    // 可以在这里进行插件的初始化配置,例如设置API密钥等
    // _flutterClickpayBridge.configure(...);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            ElevatedButton(
              onPressed: () => _startPayment(),
              child: Text('Start Payment'),
            ),
          ],
        ),
      ),
    );
  }

  void _startPayment() async {
    try {
      // 构建支付请求参数
      Map<String, dynamic> paymentParams = {
        'amount': 100.0,  // 支付金额
        'currency': 'USD',  // 货币类型
        'description': 'Test Payment',  // 支付描述
        // 其他必要的支付参数...
      };

      // 发起支付请求
      var response = await _flutterClickpayBridge.startPayment(paymentParams);

      // 处理支付响应
      if (response['success']) {
        print('Payment successful: ${response['data']}');
      } else {
        print('Payment failed: ${response['error']}');
      }
    } catch (e) {
      print('Error during payment: $e');
    }
  }
}

3. 配置Android和iOS

确保在Android和iOS项目中配置了ClickPay所需的权限和API密钥。这通常涉及修改AndroidManifest.xmlInfo.plist文件,以及可能需要在原生代码中添加一些初始化代码。

注意事项

  • 上述代码是一个简化示例,实际使用中需要根据flutter_clickpay_bridge插件的API文档和ClickPay的支付流程进行详细的配置和错误处理。
  • 插件的版本号和API可能会随时间更新,请参考最新的官方文档。
  • 确保在发布应用前进行充分的测试,包括支付流程的完整性和安全性。

希望这个示例能帮助你开始使用flutter_clickpay_bridge插件进行支付桥接。如果有任何问题,请参考插件的官方文档或联系插件的维护者。

回到顶部