Flutter支付集成插件cowpay的使用

Flutter支付集成插件cowpay的使用

要求

  • 最低 Flutter 版本为 2.5.0

安装

pubspec.yaml 文件中添加以下依赖项:

dependencies:
  cowpay:
    git:
      url: https://github.com/LuminSoft/cowpay-flutter-plugin.git
      ref: latest release version

导入

在 Dart 文件中导入 cowpay 包:

import 'package:cowpay/cowpay.dart';

使用

创建一个 Widget 并在 build 函数中返回 Cowpay 插件。以下是一个完整的示例代码:

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

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

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

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Cowpay'),
        centerTitle: true,
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Container(
              margin: const EdgeInsets.only(top: 20),
              width: 300,
              child: ElevatedButton(
                  onPressed: () => Navigator.push(context,
                      MaterialPageRoute(builder: (context) => CowpayExample())),
                  child: const Text('启动 Cowpay 支付')),
            ),
          ],
        ),
      ),
    );
  }
}

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

class _CowpayExampleState extends State<CowpayExample> {
  final String amount = "15.60";
  final String customerEmail = "customer@example.com";
  final String customerMobile = "+962777777777";
  final String customerLastName = "Doe";
  final String customerFirstName = "John";
  final bool isFeesOnCustomer = true;
  final String logoStringUrl = "https://example.com/logo.png";
  final String merchantMobile = "+962777777777";
  final String description = "Payment for service";
  final String customerMerchantProfileId = "12345";
  final String merchantReferenceId = "ref12345";
  final CowpayEnvironment activeEnvironment = CowpayEnvironment.staging;
  final String merchantHashCode = "your_merchant_hash_code";
  final String merchantCode = "your_merchant_code";

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Cowpay(
      localizationCode: LocalizationCode.en,
      amount: amount,
      customerEmail: customerEmail,
      customerMobile: customerMobile,
      customerLastName: customerLastName,
      customerFirstName: customerFirstName,
      isfeesOnCustomer: isFeesOnCustomer,
      logoStringUrl: logoStringUrl,
      merchantMobile: merchantMobile,
      description: description,
      customerMerchantProfileId: customerMerchantProfileId,
      merchantReferenceId: merchantReferenceId,
      activeEnvironment: activeEnvironment,
      merchantHashCode: merchantHashCode,
      merchantCode: merchantCode,
      onSuccess: (val) {
        debugPrint(val.paymentMethodName);
      },
      onError: (val) {
        debugPrint(val.toString());
      },
      onClosedByUser: () {
        debugPrint("closedByUser");
      },
    );
  }
}

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

1 回复

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


Cowpay 是一个用于在 Flutter 应用中集成支付功能的插件。它支持多种支付方式,包括信用卡、Fawry、Valu 等。以下是使用 cowpay 插件集成支付功能的步骤:

1. 添加依赖

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

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

然后运行 flutter pub get 来获取依赖。

2. 初始化 Cowpay

在应用启动时,初始化 Cowpay 插件。你需要在 main.dart 文件中进行初始化:

import 'package:cowpay/cowpay.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // 初始化 Cowpay
  await Cowpay.instance.initialize(
    merchantCode: 'YOUR_MERCHANT_CODE',
    merchantHashKey: 'YOUR_MERCHANT_HASH_KEY',
    environment: Environment.Test, // 或 Environment.Production
  );

  runApp(MyApp());
}

3. 创建支付请求

在需要支付的地方,创建一个支付请求对象。你可以根据不同的支付方式创建不同的请求对象。

例如,使用信用卡支付:

import 'package:cowpay/cowpay.dart';

void makePayment() async {
  var paymentRequest = CowpayCreditCardRequest(
    customerMerchantProfileId: 'CUSTOMER_PROFILE_ID',
    customerMobile: 'CUSTOMER_MOBILE',
    customerEmail: 'CUSTOMER_EMAIL',
    amount: 100.0, // 支付金额
    description: 'Payment for order #123',
    cardNumber: '4111111111111111',
    cardExpiryDate: '12/25',
    cardCvv: '123',
    cardHolderName: 'John Doe',
  );

  try {
    var paymentResponse = await Cowpay.instance.payWithCreditCard(paymentRequest);
    print('Payment response: $paymentResponse');
  } catch (e) {
    print('Payment failed: $e');
  }
}

4. 处理支付响应

支付完成后,Cowpay 会返回一个支付响应对象。你可以根据支付结果进行相应的处理。

if (paymentResponse.isSuccess) {
  // 支付成功
  print('Payment successful!');
} else {
  // 支付失败
  print('Payment failed: ${paymentResponse.errorMessage}');
}

5. 其他支付方式

Cowpay 还支持其他支付方式,如 Fawry、Valu 等。你可以根据需要创建相应的支付请求对象。

例如,使用 Fawry 支付:

var paymentRequest = CowpayFawryRequest(
  customerMerchantProfileId: 'CUSTOMER_PROFILE_ID',
  customerMobile: 'CUSTOMER_MOBILE',
  customerEmail: 'CUSTOMER_EMAIL',
  amount: 100.0,
  description: 'Payment for order #123',
  fawryItems: [
    FawryItem(
      itemId: 'ITEM_ID',
      description: 'Item Description',
      price: 100.0,
      quantity: 1,
    ),
  ],
);

var paymentResponse = await Cowpay.instance.payWithFawry(paymentRequest);

6. 处理回调

Cowpay 还支持支付回调。你可以在支付完成后接收到回调通知,以便进行进一步的处理。

Cowpay.instance.setPaymentCallback((paymentResponse) {
  if (paymentResponse.isSuccess) {
    // 支付成功
  } else {
    // 支付失败
  }
});

7. 测试与生产环境

在开发过程中,你可以使用 Environment.Test 环境进行测试。上线时,请切换到 Environment.Production 环境。

8. 处理错误

在进行支付时,可能会遇到各种错误。你可以通过 try-catch 块来捕获并处理这些错误。

try {
  var paymentResponse = await Cowpay.instance.payWithCreditCard(paymentRequest);
} catch (e) {
  print('Payment failed: $e');
}
回到顶部