Flutter支付处理插件payengine的使用

Flutter支付处理插件PayEngine的使用

PayEngine SDK for Flutter

PayEngine Flutter SDK允许你在原生Android和iOS应用中构建令人愉悦的支付体验。我们提供了强大的和可定制的UI屏幕和元素,可以直接使用来收集用户支付信息。

安装

在项目中添加PayEngine注册库:

allprojects {
    repositories {
        ...your repositories
        
        maven {
            name = "pe-maven"
            url = uri("https://maven.payengine.co/payengine")
            credentials {
                username = "<username>"
                password = "<password>"
            }
        }
    }
}

联系PayEngine支持获取用户名和密码。

前置条件

Android

要使用安全字段组件,你需要安装并配置Material Components主题。

  1. app/build.gradle文件中添加以下依赖(指定版本):
implementation 'com.google.android.material:material:<version>'
  1. styles.xml文件中设置适当的样式:
<style name="Theme.MyApp" parent="Theme.MaterialComponents.DayNight.NoActionBar">
    <!-- ... -->
</style>
iOS

运行以下命令:

cd ios &amp;&amp; pod install --repo-update &amp;&amp; cd ..

使用

PayEngine配置
final PayEngineConfig config = const PayEngineConfig(
      publicKey: "pk_test_xxx",
      scriptURL: "https://console.payengine.dev");
final String merchantId = "&lt;your-merchant-id&gt;";

将配置包装在一个Provider中:

PayEngineProvider(
  config: config, 
  child: const MyApp()
)
信用卡表单
var additionalFields = List&lt;PayEngineField&gt;.from([
      PayEngineField('address_zip', 'text', 'Zip Code', true,
          keyboardType: PayEngineKeyboardType.number,
          pattern:
              r"^(?:\d{5}(?:-\d{4})?|[ABCEGHJKLMNPRSTVXY]\d[A-Z] ?\d[A-Z]\d)$"),
    ]);

final creditCardForm = CreditCardForm(additionalFields: additionalFields);

Container(padding: const EdgeInsets.all(10), child: creditCardForm),

OutlinedButton(
    onPressed: () async {
      final response = await creditCardForm.tokenize(merchantId);
      setState(() {
        result = response;
      });
    },
    child: const Text('Tokenize')),
银行账户表单
final bankAccountForm = BankAccountForm();

Container(padding: const EdgeInsets.all(10), child: bankAccountForm),
OutlinedButton(
    onPressed: () async {
      final response = await bankAccountForm.tokenize(merchantId);
      setState(() {
        result = response;
      });
    },
    child: const Text('Tokenize')),

Google Pay和Apple Pay

检查是否支持
final isSupported = PayEngineNative.userCanPay(PayProvider.applePay, Config.merchantId)

始终在呈现支付按钮之前调用此方法,参见下面的示例。

Google Pay
final paymentRequest = PEPaymentRequest(
  merchantId: Config.merchantId, 
  paymentAmount: 10.00, 
  paymentItems: [
    PEPaymentItem(
      label: "Test Item", 
      amount: 10.00,
    )
  ],
  platformOptions: PEGooglePayOptions(billingAddressRequired: true, shippingAddressRequired: true)
);

// 渲染按钮
FutureBuilder&lt;bool&gt;(
  future: PayEngineNative.userCanPay(
      PayProvider.googlePay, Config.merchantId),
  builder: (context, snapshot) {
    if (snapshot.connectionState == ConnectionState.done) {
      if (snapshot.hasError) {
        return Center(
          child: Text(
            '${snapshot.error}',
          ),
        );
      } else if (snapshot.data == true) {
        return PEGooglePayButton(
          paymentRequest: paymentRequest,
          onPaymentFailed: (error) {
            debugPrint("onPaymentFailed $error");
            result = error.toString();
          },
          onPaymentSheetDismissed: () {
            debugPrint("onPaymentSheetDismissed");
          },
          onTokenDidReturn: (token, metadata, billingAddress, shippingAddress) {
            debugPrint("onTokenDidReturn $token $metadata ${billingAddress?.toJson()} ${shippingAddress?.toJson()}");
            result = token;
          },
        );
      } else {
        return const Text("Google Pay is not supported");
      }
    } else {
      return const SizedBox.shrink();
    }
  })
Apple Pay
final paymentRequest = PEPaymentRequest(
  merchantId: Config.merchantId,
  paymentAmount: 10.00,
  paymentItems: [
    PEPaymentItem(
      label: "Test Item",
      amount: 10.00,
    )
  ],
  platformOptions: PEApplePayOptions(
      requiredBillingContactFields: [PEContactField.postalAddress],
      requiredShippingContactFields: [PEContactField.name])
  );

// 渲染按钮
FutureBuilder&lt;bool&gt;(
  future: PayEngineNative.userCanPay(
      PayProvider.applePay, Config.merchantId),
  builder: (context, snapshot) {
    if (snapshot.connectionState == ConnectionState.done) {
      if (snapshot.hasError) {
        return Center(
          child: Text(
            '${snapshot.error}',
          ),
        );
      } else if (snapshot.data == true) {
        return PEApplePayButton(
          paymentRequest: paymentRequest,
          onPaymentFailed: (error) {
            debugPrint("onPaymentFailed $error");
            result = error.toString();
          },
          onPaymentSheetDismissed: () {
            debugPrint("onPaymentSheetDismissed");
          },
          onTokenDidReturn: (token, metadata, billingContact, shippingContact) {
            debugPrint("onTokenDidReturn $token $metadata ${billingContact?.toJson()} ${shippingContact?.toJson()}");
            result = token;
          },
        );
      } else {
        return const Text("Apple Pay is not supported");
      }
    } else {
      return const SizedBox.shrink();
    }
  })

示例代码

example/lib/main.dart

import 'package:flutter/material.dart';
import 'package:payengine/payengine_provider.dart';
import 'package:payengine_example/config.dart';
import 'package:payengine_example/screens/credit_card_screen.dart';
import 'package:payengine_example/themes.dart';

void main() {
  runApp(
    PayEngineProvider(
      config: Config.config, 
      child: const MyApp()
    )
  );
}

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

  [@override](/user/override)
  State&lt;MyApp&gt; createState() =&gt; _MyAppState();
}

class _MyAppState extends State&lt;MyApp&gt; with TickerProviderStateMixin {
  Map&lt;dynamic, dynamic&gt; result = {};

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

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: MyAppThemes.lightTheme,
      darkTheme: MyAppThemes.darkTheme,
      themeMode: ThemeMode.light,
      home: const CreditCardScreen(),
    );
  }
}

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

1 回复

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


当然,下面是一个关于如何在Flutter中使用payengine插件进行支付处理的示例代码。请注意,这只是一个基本示例,实际使用时可能需要根据具体需求和支付引擎的配置进行调整。

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

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

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

接下来,在你的Flutter应用中,你可以按照以下步骤进行支付处理:

  1. 初始化支付引擎

    你需要在应用的某个地方(比如main.dart或者一个专门的支付初始化页面)初始化支付引擎。

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

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  
  // 初始化支付引擎(假设你有相关的API密钥和配置)
  PayEngine.instance.init(
    apiKey: 'your_api_key', // 替换为你的API密钥
    environment: PayEngineEnvironment.sandbox, // 测试环境,生产环境使用 PayEngineEnvironment.production
  );

  runApp(MyApp());
}
  1. 创建支付请求

    在需要发起支付的地方(比如一个按钮点击事件),创建一个支付请求。

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

class _PaymentScreenState extends State<PaymentScreen> {
  void _initiatePayment() async {
    try {
      // 创建支付请求
      final paymentRequest = PayEnginePaymentRequest(
        amount: 100.0, // 支付金额
        currency: 'USD', // 货币类型
        description: 'Test Payment', // 支付描述
        // 其他必要的支付参数,比如商品详情、用户信息等
      );

      // 发起支付
      final paymentResponse = await PayEngine.instance.startPayment(paymentRequest);

      // 处理支付响应
      if (paymentResponse.success) {
        // 支付成功,处理成功逻辑
        print('Payment successful!');
      } else {
        // 支付失败,处理失败逻辑
        print('Payment failed: ${paymentResponse.errorMessage}');
      }
    } catch (e) {
      // 处理异常
      print('Error initiating payment: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Payment Screen'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: _initiatePayment,
          child: Text('Initiate Payment'),
        ),
      ),
    );
  }
}
  1. 处理支付结果

    根据支付引擎的配置,支付结果可能会通过回调或者需要你自己轮询支付状态来获取。这里假设支付结果是通过回调返回的,你可以在支付成功或失败后执行相应的逻辑。

请注意,以上代码是一个简化的示例,实际使用中你可能需要处理更多的支付细节和异常情况,比如网络错误、用户取消支付等。此外,payengine插件的具体API和配置可能会随着版本的更新而变化,因此请参考最新的官方文档和示例代码。

最后,别忘了在发布应用前将支付环境从测试环境切换到生产环境,并确保所有支付相关的配置都是正确的。

回到顶部