Flutter支付集成插件myfatoorah_flutter的使用
Flutter支付集成插件myfatoorah_flutter的使用
1. 安装与使用
1.1 添加依赖
在你的 pubspec.yaml
文件中添加 myfatoorah_flutter
插件:
dependencies:
myfatoorah_flutter: ^3.1.5
1.2 安装插件
运行以下命令来安装插件:
$ flutter pub get
1.3 导入插件
在你的 Dart 文件中导入 myfatoorah_flutter
:
import 'package:myfatoorah_flutter/myfatoorah_flutter.dart';
1.4 初始化插件
初始化 MyFatoorah 插件,设置 API Key、国家和环境(测试或生产):
MFSDK.init("Add Your API Key", MFCountry.KUWAIT, MFEnvironment.TEST);
1.5 (可选) 设置 ActionBar 属性
如果你需要自定义 AppBar 的属性,可以使用以下代码:
void setUpActionBar() {
MFSDK.setUpActionBar(
toolBarTitle: 'Company Payment',
toolBarTitleColor: '#FFEB3B',
toolBarBackgroundColor: '#CA0404',
isShowToolBar: true);
}
注意: 测试完成后,将环境从 TEST
更改为 LIVE
。
2. 发起支付
2.1 发起支付请求
发起支付请求以获取 PaymentMethodId
,这是执行支付时所需的参数。你只需要调用一次此函数并保存 PaymentMethodId
。
// Initiate Payment
initiatePayment() async {
MFInitiatePaymentRequest request = MFInitiatePaymentRequest(
invoiceAmount: 10, currencyIso: MFCurrencyISO.SAUDIARABIA_SAR);
await MFSDK
.initiatePayment(request, MFLanguage.ENGLISH)
.then((value) => debugPrint(value.toString()))
.catchError((error) => {debugPrint(error.message)});
}
2.2 执行支付
使用 PaymentMethodId
执行支付:
// The value "1" is the paymentMethodId of KNET payment method.
// You should call the "initiatePayment" API to can get this id and the ids of all other payment methods
executePayment() async {
MFExecutePaymentRequest request = MFExecutePaymentRequest(invoiceValue: 10);
request.paymentMethodId = 1;
await MFSDK
.executePayment(request, MFLanguage.ENGLISH, (invoiceId) {
debugPrint(invoiceId);
})
.then((value) => debugPrint(value.toString()))
.catchError((error) => {debugPrint(error.message)});
}
3. 发送支付
发送支付请求,可以通过电子邮件或其他方式通知用户支付信息:
sendPayment() async {
MFSendPaymentRequest request = MFSendPaymentRequest();
request.customerName = "TEESST";
request.invoiceValue = 10;
request.notificationOption = MFNotificationOption.EMAIL;
await MFSDK
.sendPayment(request, MFLanguage.ENGLISH)
.then((value) => debugPrint(value.toString()))
.catchError((error) => {debugPrint(error.message)});
}
4. 支付查询
查询特定发票/支付的详细信息:
getPaymentStatus() async {
MFGetPaymentStatusRequest request = MFGetPaymentStatusRequest(
key: '2593740', keyType: MFKeyType.INVOICEID.name);
await mfSDK
.getPaymentStatus(request, MFLanguage.ENGLISH.name)
.then((value) => debugPrint(value.toString()))
.catchError((error) => {debugPrint(error.message)});
}
5. 内嵌支付使用
5.1 创建支付卡视图
创建一个 MFPaymentCardView
实例并将其添加到 build()
函数中:
class _MyAppState extends State<MyApp> {
late MFCardPaymentView mfCardView;
@override
Widget build(BuildContext context) {
mfCardView = MFCardPaymentView(cardViewStyle: cardViewStyle());
return embeddedCardView();
}
Widget embeddedCardView() {
return Column(
children: [
SizedBox(
height: 200,
child: mfCardView,
),
],
);
}
MFCardViewStyle cardViewStyle() {
MFCardViewStyle cardViewStyle = MFCardViewStyle();
cardViewStyle.cardHeight = 200;
cardViewStyle.hideCardIcons = false;
cardViewStyle.input?.inputMargin = 5;
cardViewStyle.label?.display = true;
cardViewStyle.input?.fontFamily = MFFontFamily.Monaco;
cardViewStyle.label?.fontWeight = MFFontWeight.Heavy;
return cardViewStyle;
}
}
5.2 初始化会话
为每次支付创建一个会话,并在成功状态下加载支付卡视图:
initSession() async {
// If you want to use saved card option with embedded payment, send the parameter
// "customerIdentifier" with a unique value for each customer. This value cannot be used
// for more than one Customer.
// var request = MFInitiateSessionRequest("12332212");
// If not, then send null like this.
MFInitiateSessionRequest initiateSessionRequest = MFInitiateSessionRequest();
await MFSDK
.initSession(initiateSessionRequest, MFLanguage.ENGLISH)
.then((value) => loadEmbeddedPayment(value))
.catchError((error) => {debugPrint(error.message)});
}
loadEmbeddedPayment(MFInitiateSessionResponse session) {
loadCardView(session);
if (Platform.isIOS) applePayPayment(session);
}
loadCardView(MFInitiateSessionResponse session) {
mfCardView.load(session, (bin) {debugPrint(bin)});
}
注意: initSession()
函数应在 MFSDK.init()
之后调用。
5.3 处理支付按钮
处理支付按钮点击事件,调用 pay()
函数执行支付:
pay() async {
var executePaymentRequest = MFExecutePaymentRequest(invoiceValue: 10);
executePaymentRequest.sessionId = sessionId;
await mfCardView
.pay(executePaymentRequest, MFLanguage.ENGLISH, (invoiceId) {
debugPrint(invoiceId);
})
.then((value) => {debugPrint(value.toString())})
.catchError((error) => {debugPrint(error.message)});
}
6. Apple Pay 内嵌支付(仅限 iOS)
6.1 创建 Apple Pay 按钮
创建一个 MFApplePayButton
实例并将其添加到 build()
函数中:
class _MyAppState extends State<MyApp> {
late MFApplePayButton mfApplePayButton;
@override
Widget build(BuildContext context) {
mfApplePayButton = MFApplePayButton(applePayStyle: MFApplePayStyle());
return applePayView();
}
Widget applePayView() {
return Column(
children: [
SizedBox(
height: 50,
child: mfApplePayButton,
)
],
);
}
}
6.2 处理 Apple Pay 支付
为每次支付创建一个会话,并在成功状态下显示 Apple Pay 按钮:
applePayPayment(MFInitiateSessionResponse session) async {
MFExecutePaymentRequest executePaymentRequest =
MFExecutePaymentRequest(invoiceValue: 10);
executePaymentRequest.displayCurrencyIso = MFCurrencyISO.KUWAIT_KWD;
await mfApplePayButton
.displayApplePayButton(session, executePaymentRequest, MFLanguage.ENGLISH)
.then((value) => {
mfApplePayButton
.executeApplePayButton(null, (invoiceId) => {debugPrint(invoiceId)})
.then((value) => {debugPrint(value.toString())})
.catchError((error) => {debugPrint(error.message)})
})
.catchError((error) => {debugPrint(error.message)});
}
注意: applePayPayment()
函数应在 MFSDK.init()
之后调用。
7. 直接支付与令牌化
7.1 获取允许直接支付的支付方式
通过调用 initiatePayment
获取 paymentMethodId
,该 ID 用于直接支付。
7.2 收集用户卡片信息
收集用户的卡片信息,例如:
var mfCardRequest = MFCard(
cardHolderName: 'myFatoorah',
number: '5454545454545454',
expiryMonth: '10',
expiryYear: '23',
securityCode: '000',
);
7.3 保存卡片信息并获取令牌
如果你想保存信用卡信息并在下次支付时使用令牌,可以设置 saveToken: true
,并在响应中获取令牌。
7.4 执行直接支付
执行直接支付的示例代码如下:
executeDirectPayment() async {
var executePaymentRequest = MFExecutePaymentRequest(invoiceValue: 10);
executePaymentRequest.paymentMethodId = 20;
var directPaymentRequest = MFDirectPaymentRequest(
executePaymentRequest: executePaymentRequest,
token: null,
card: mfCardRequest,
);
await MFSDK
.executeDirectPayment(directPaymentRequest, MFLanguage.ENGLISH,
(invoiceId) {
debugPrint(invoiceId);
})
.then((value) => debugPrint(value.toString()))
.catchError((error) => {debugPrint(error.message)});
}
更多关于Flutter支付集成插件myfatoorah_flutter的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter支付集成插件myfatoorah_flutter的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,下面是一个关于如何在Flutter项目中集成并使用myfatoorah_flutter
插件的示例代码。这个插件用于集成MyFatoorah支付网关。请注意,为了运行这个示例,你需要有一个有效的MyFatoorah商家账户和相应的API密钥。
步骤 1: 添加依赖
首先,在你的pubspec.yaml
文件中添加myfatoorah_flutter
依赖:
dependencies:
flutter:
sdk: flutter
myfatoorah_flutter: ^最新版本号 # 请替换为实际的最新版本号
然后运行flutter pub get
来安装依赖。
步骤 2: 配置MyFatoorah
在你的Flutter应用的入口文件(通常是main.dart
)中,配置MyFatoorah支付插件。你需要提供你的API密钥和其他必要的配置信息。
import 'package:flutter/material.dart';
import 'package:myfatoorah_flutter/myfatoorah_flutter.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'MyFatoorah Payment Integration',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
void initState() {
super.initState();
// 配置MyFatoorah
MyFatoorahFlutter.init(
apiKey: '你的API密钥', // 替换为你的MyFatoorah API密钥
isSandbox: true, // 如果是测试环境,设置为true;生产环境设置为false
language: 'ar', // 可选,设置语言,例如'ar'为阿拉伯语,'en'为英语
);
}
void _startPayment() async {
try {
// 发起支付请求
var response = await MyFatoorahFlutter.startPayment(
amount: 100.0, // 支付金额,单位为埃及镑(EGP),可以根据需要调整
currencyCode: 'EGP', // 货币代码
description: '商品描述', // 支付描述
merchantReference: '唯一订单号', // 商家订单号,必须是唯一的
callbackUrl: 'https://你的回调URL', // 支付成功或失败后的回调URL
);
// 处理支付响应
if (response['status'] == 'success') {
// 支付成功后的处理逻辑
print('支付成功: ${response['data']}');
} else {
// 支付失败后的处理逻辑
print('支付失败: ${response['message']}');
}
} catch (e) {
// 处理异常
print('支付过程中发生错误: $e');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('MyFatoorah Payment Integration'),
),
body: Center(
child: ElevatedButton(
onPressed: _startPayment,
child: Text('发起支付'),
),
),
);
}
}
步骤 3: 处理回调
在MyFatoorah支付完成后,用户将被重定向到你提供的callbackUrl
。你需要在服务器端处理这个回调,验证支付状态并更新订单状态。
注意:回调处理逻辑需要在服务器端实现,因为涉及敏感信息的验证和处理,不适合在客户端(即Flutter应用)中处理。
额外注意事项
- 安全性:确保你的API密钥和其他敏感信息不被泄露。
- 测试环境:在集成和测试阶段,使用MyFatoorah的测试环境(
isSandbox: true
)。 - 错误处理:在实际应用中,添加更详细的错误处理和用户反馈机制。
通过上述步骤,你应该能够在Flutter应用中成功集成MyFatoorah支付插件。如果有任何问题或需要进一步的帮助,请参考MyFatoorah的官方文档或联系他们的技术支持。