Flutter支付功能插件flutter_pay的使用
Flutter支付功能插件flutter_pay的使用
Google Pay 准备工作
请参考 Android 官方文档进行配置。
Apple Pay 准备工作
请参考 Apple 官方文档进行配置。
使用方法
首先,你需要确保设备上支持 Pay API:
import 'package:flutter_pay/flutter_pay.dart';
FlutterPay flutterPay = FlutterPay();
// 检查设备是否支持支付
bool isAvailable = await flutterPay.canMakePayments();
如果你需要检查用户是否有至少一张有效的卡片:
import 'package:flutter_pay/flutter_pay.dart';
FlutterPay flutterPay = FlutterPay();
// 检查是否有有效卡片
bool isAvailable = await flutterPay.canMakePaymentsWithActiveCard();
// 你也可以指定允许的支付网络
bool isAvailable = await flutterPay.canMakePaymentsWithActiveCard(
allowedPaymentNetworks: [
PaymentNetwork.visa,
PaymentNetwork.masterCard,
],
);
要发起支付请求,可以使用 requestPayment
方法。此函数将返回一个 token,你需要将该 token 发送到你的网关以完成支付。示例如下:
import 'package:flutter_pay/flutter_pay.dart';
PaymentItem item = PaymentItem(name: "T-Shirt", price: 2.98);
FlutterPay flutterPay = FlutterPay();
// 设置环境为测试环境
flutterPay.setEnvironment(environment: PaymentEnvironment.Test);
String token = await flutterPay.requestPayment(
googleParameters: GoogleParameters(
gatewayName: "example",
gatewayMerchantId: "example_id",
merchantId: "example_merchant_id",
merchantName: "exampleMerchantName",
),
appleParameters: AppleParameters(merchantIdentifier: "merchant.flutterpay.example"),
currencyCode: "USD",
countryCode: "US",
paymentItems: [item],
);
注意,某些参数仅影响 Apple Pay 或 Google Pay。例如,paymentItems
仅影响 Apple Pay,而最后一项用于总计标签。merchantName
仅影响 Google Pay,并会显示给用户。gatewayName
也仅影响 Google Pay,请参阅 Google Pay 集成部分。
支付网络矩阵
支付网络 | iOS | Android |
---|---|---|
Visa | + | + |
MasterCard | + | + |
American Express | + | + |
Interac | + | + |
Discover | + | + |
JCB | + | + |
Maestro | + | - |
Electron | + | - |
Cartes Bancarries | + | - |
Union Pay | + | - |
EftPos | + | - |
Elo | + | - |
ID Credit | + | - |
Mada | + | - |
Private Label | + | - |
Quic Pay | + | - |
Suica | + | - |
V Pay | + | - |
路线图
- ✅ 基本实现
- ❌ 完整文档
- ❌ 添加商户能力支持
- ❌ 添加账单和收货信息支持
完整示例 Demo
以下是一个完整的示例代码,展示了如何在 Flutter 应用中使用 flutter_pay
插件:
import 'package:flutter/material.dart';
import 'package:flutter_pay/flutter_pay.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
[@override](/user/override)
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
FlutterPay flutterPay = FlutterPay();
String result = "Result will be shown here";
[@override](/user/override)
void initState() {
super.initState();
}
void makePayment() async {
List<PaymentItem> items = [
PaymentItem(name: "T-Shirt", price: 2.98)
];
// 设置环境为测试环境
flutterPay.setEnvironment(environment: PaymentEnvironment.Test);
try {
String token = await flutterPay.requestPayment(
googleParameters: GoogleParameters(
gatewayName: "example",
gatewayMerchantId: "example_id",
),
appleParameters: AppleParameters(merchantIdentifier: "merchant.flutterpay.example"),
currencyCode: "USD",
countryCode: "US",
paymentItems: items,
);
setState(() {
this.result = "Payment successful! Token: $token";
});
} catch (e) {
setState(() {
this.result = "Error: $e";
});
}
}
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
),
body: Container(
padding: EdgeInsets.all(12.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
this.result,
style: TextStyle(
fontSize: 16.0,
),
),
ElevatedButton(
child: Text("Can make payments?"),
onPressed: () async {
try {
bool canMakePayments = await flutterPay.canMakePayments();
setState(() {
this.result = "Can make payments: $canMakePayments";
});
} catch (e) {
setState(() {
this.result = "Error: $e";
});
}
},
),
ElevatedButton(
child: Text("Can make payments with verified card?"),
onPressed: () async {
try {
bool canMakePaymentsWithActiveCard =
await flutterPay.canMakePaymentsWithActiveCard(
allowedPaymentNetworks: [
PaymentNetwork.visa,
PaymentNetwork.masterCard,
],
);
setState(() {
this.result = "Can make payments with verified card: $canMakePaymentsWithActiveCard";
});
} catch (e) {
setState(() {
this.result = "Error: $e";
});
}
},
),
ElevatedButton(
child: Text("Try to pay?"),
onPressed: () {
makePayment();
},
)
],
),
),
),
);
}
}
更多关于Flutter支付功能插件flutter_pay的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter支付功能插件flutter_pay的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是如何在Flutter项目中集成并使用flutter_pay
插件来实现支付功能的示例代码。flutter_pay
插件允许你在Flutter应用中轻松集成多种支付方式。请注意,实际使用时,你需要根据具体的支付服务提供商进行配置和测试。
1. 添加依赖
首先,在你的pubspec.yaml
文件中添加flutter_pay
依赖:
dependencies:
flutter:
sdk: flutter
flutter_pay: ^x.y.z # 请替换为最新版本号
然后运行flutter pub get
来安装依赖。
2. 配置Android和iOS
Android
在android/app/src/main/AndroidManifest.xml
中添加必要的权限和网络配置。具体配置取决于你的支付服务提供商的要求。
iOS
在ios/Runner/Info.plist
中添加必要的配置,如URL Scheme等,这同样取决于你的支付服务提供商。
3. 初始化FlutterPay
在你的Flutter应用中,你需要初始化FlutterPay
实例,并配置相关的支付参数。
import 'package:flutter/material.dart';
import 'package:flutter_pay/flutter_pay.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Flutter Pay Example'),
),
body: Center(
child: PaymentButton(),
),
),
);
}
}
class PaymentButton extends StatefulWidget {
@override
_PaymentButtonState createState() => _PaymentButtonState();
}
class _PaymentButtonState extends State<PaymentButton> {
FlutterPay? _flutterPay;
@override
void initState() {
super.initState();
_initFlutterPay();
}
Future<void> _initFlutterPay() async {
// 替换为你的支付服务提供商的配置信息
final FlutterPayConfig config = FlutterPayConfig(
publicKey: 'your_public_key', // 替换为你的公钥
environment: FlutterPayEnvironment.sandbox, // 沙盒环境,生产环境使用 FlutterPayEnvironment.production
supportedMethods: ['card'], // 支持的支付方式,例如信用卡
merchantIdentifier: 'your_merchant_identifier', // 替换为你的商户标识符
returnUrlScheme: 'yourapp://payment', // 回调URL Scheme
);
_flutterPay = FlutterPay(config: config);
// 监听支付结果
_flutterPay!.paymentResultStream.listen((result) {
if (result.status == FlutterPayStatus.success) {
// 支付成功处理
print('Payment successful: ${result.token}');
} else if (result.status == FlutterPayStatus.failed) {
// 支付失败处理
print('Payment failed: ${result.errorMessage}');
} else if (result.status == FlutterPayStatus.cancelled) {
// 支付取消处理
print('Payment cancelled');
}
});
}
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: _flutterPay != null ? () => _startPayment() : null,
child: Text('Start Payment'),
);
}
Future<void> _startPayment() async {
try {
// 启动支付流程
final FlutterPayRequest request = FlutterPayRequest(
amount: '10.00', // 支付金额
currencyCode: 'USD', // 货币代码
description: 'Test payment', // 支付描述
);
await _flutterPay!.startPayment(request);
} catch (e) {
print('Error starting payment: $e');
}
}
}
4. 处理回调
确保你的应用能够处理支付回调。这通常涉及到在AndroidManifest.xml
和Info.plist
中配置URL Scheme,并在你的Flutter应用中监听这些回调。
注意事项
- 替换所有示例代码中的占位符(如
your_public_key
)为你的实际支付服务提供商提供的值。 - 根据你的支付服务提供商的要求,可能还需要额外的配置和步骤。
- 在发布到生产环境之前,请在沙盒环境中充分测试支付功能。
以上代码提供了一个基本的集成示例,实际应用中可能需要根据具体需求进行调整和扩展。