Flutter支付插件flutter_tpay的使用
以下是关于“Flutter支付插件flutter_tpay的使用”的详细内容,包括完整的示例代码:
Flutter支付插件flutter_tpay的使用
关于
此插件允许您的应用使用Tpay进行支付。
使用
获取Tpay实例
final TpayPlatform tpay = TpayPlatform.instance;
UI模块
Tpay插件包含UI模块。用户可以通过它进行支付。
安卓设置
Tpay UI模块需要您的MainActivity继承自FlutterFragmentActivity
并传递系统返回事件。
class MainActivity: FlutterFragmentActivity() {
override fun onBackPressed() {
if (TpayBackpressUtil.isModuleVisible) {
TpayBackpressUtil.onBackPressed()
} else {
super.onBackPressed()
}
}
}
iOS设置
当将Tpay支付模块集成到您的应用时,确保正确设置必要的权限以确保顺畅的用户体验。
隐私 - 摄像头使用描述
该模块允许用户自动填写信用卡表单以进行安全支付处理。此功能需要您在应用的Info.plist文件中设置“隐私 - 摄像头使用描述”。
步骤
- 打开项目的Info.plist文件。
- 添加键值对“隐私 - 摄像头使用描述”权限,并解释相机访问的目的。明确说明相机用于自动填写信用卡表单以进行安全支付处理。
示例
<key>NSCameraUsageDescription</key>
<string>我们需要访问您的相机来自动填写信用卡表单以进行安全支付处理。</string>
配置Tpay模块
此配置允许您的应用使用Tpay UI模块和无界面支付。
final configuration = TpayConfiguration(
merchant: Merchant(
authorization: MerchantAuthorization(
clientId: "YOUR_CLIENT_ID",
clientSecret: "YOUR_CLIENT_SECRET"
),
environment: TpayEnvironment.production,
certificatePinningConfiguration: CertificatePinningConfiguration(publicKeyHash: "PUBLIC_KEY_HASH"),
blikAliasToRegister: "BLIK alias",
walletConfiguration: WalletConfiguration(
googlePay: GooglePayConfiguration(merchantId: "YOUR_MERCHANT_ID"),
applePay: ApplePayConfiguration(merchantIdentifier: "MERCHANT_IDENTIFIER", countryCode: "PL")
),
),
merchantDetails: MerchantDetails(
merchantDisplayName: [
LocalizedString(language: Language.pl, value: "polish name"),
LocalizedString(language: Language.en, value: "english name")
],
merchantHeadquarters: [
LocalizedString(language: Language.pl, value: "polish city name"),
LocalizedString(language: Language.en, value: "english city name")
],
regulations: [
LocalizedString(language: Language.pl, value: "polish regulation url"),
LocalizedString(language: Language.en, value: "english regulation url")
],
),
languages: Languages(
preferredLanguage: Language.pl,
supportedLanguages: [Language.pl, Language.en]
),
paymentMethods: PaymentMethods(
methods: [
PaymentMethod.card,
PaymentMethod.blik,
PaymentMethod.transfer
],
wallets: [
DigitalWallet.applePay,
DigitalWallet.googlePay
],
installmentPayments: [InstallmentPayment.ratyPekao, InstallmentPayment.payPo]
),
);
tpay.configure(configuration);
使用Tpay UI进行支付
final transaction = SingleTransaction(
amount: 19.99,
description: "transaction description",
payerContext: PayerContext(
payer: Payer(
name: "John Doe",
email: "example@example.com",
phone: null,
address: null
),
automaticPaymentMethods: AutomaticPaymentMethods(
tokenizedCards: [
TokenizedCard(
token: "card token",
cardTail: "1234",
brand: CreditCardBrand.mastercard
),
TokenizedCard(
token: "card token",
cardTail: "4321",
brand: CreditCardBrand.visa
)
],
blikAlias: BlikAlias(isRegistered: true, value: "alias value", label: "label")
)
)
);
tpay.startPayment(transaction);
信用卡令牌化
final payer = Payer(
name: "John Doe",
email: "example@example.com",
phone: null,
address: null
);
tpay.tokenizeCard(Tokenization(payer: payer, notificationUrl: "https://yourstore.com/notifications"));
信用卡令牌支付
final tokenPayment = TokenPayment(
amount: 19.99,
description: "transaction description",
cardToken: "card token",
payer: Payer(
name: "John Doe",
email: "example@example.com",
phone: null,
address: null
),
);
tpay.startCardTokenPayment(tokenPayment);
处理Tpay UI模块结果
void handleResult(Result result){
if (result is PaymentCompleted) {
// 支付完成成功且Tpay模块已关闭
}
if (result is PaymentCancelled) {
// 支付失败且Tpay模块已关闭
}
if (result is TokenizationCompleted) {
// 令牌化成功且Tpay模块已关闭
}
if (result is TokenizationFailure) {
// 令牌化失败且Tpay模块已关闭
}
if (result is ConfigurationSuccess) {
// Tpay模块配置成功
}
if (result is ValidationError) {
// 传递的数据不正确
}
if (result is ModuleClosed) {
// 用户关闭了Tpay模块
// 没有进行支付或令牌化
}
if (result is MethodCallError) {
// 插件出现问题
}
}
无界面支付
Tpay插件允许创建不显示Tpay UI模块的支付。
无界面BLIK支付
用户可以使用6位数的BLIK代码或别名(仅限回头客)。
final payment = BLIKPayment(
code: "123456",
alias: BlikAlias(isRegistered: true, value: "alias value", label: "label"),
paymentDetails: PaymentDetails(
amount: 19.99,
description: "transaction description",
hiddenDescription: "hidden description",
language: Language.pl
),
payer: Payer(
name: "John Doe",
email: "example@example.com",
phone: null,
address: null
),
callbacks: Callbacks(
redirects: Redirects(
successUrl: "https://yourstore.com/success",
errorUrl: "https://yourstore.com/error",
),
notifications: Notifications(
url: "https://yourstore.com",
email: "payments@yourstore.com"
)
)
);
tpay.screenlessBLIKPayment(payment);
无界面模糊BLIK支付
screenlessBLIKPayment(...)
方法可能返回 ScreenlessBlikAmbiguousAlias
结果,
这意味着用户在一个银行注册了多个BLIK别名。您需要向用户显示 ScreenlessBlikAmbiguousAlias
结果中的模糊别名。
之后,您需要使用 screenlessAmbiguousBLIKPayment(...)
方法继续支付。
final payment = AmbiguousBLIKPayment(
transactionId: "id", // 从 ScreenlessBlikAmbiguousAlias 结果接收
blikAlias: BlikAlias(...), // 用于使用 screenlessBLIKPayment(...) 方法创建支付的BLIK别名
ambiguousAlias: AmbiguousAlias(...) // 用户选择的模糊别名
);
tpay.screenlessAmbiguousBLIKPayment(payment);
无界面转账支付
转账支付需要Tpay系统中的银行渠道ID。
final payment = TransferPayment(
channelId: 4,
paymentDetails: PaymentDetails(
amount: 19.99,
description: "transaction description",
hiddenDescription: "hidden description",
language: Language.pl
),
payer: Payer(
name: "John Doe",
email: "example@example.com",
phone: null,
address: null
),
callbacks: Callbacks(
redirects: Redirects(
successUrl: "https://yourstore.com/success",
errorUrl: "https://yourstore.com/error",
),
notifications: Notifications(
url: "https://yourstore.com",
email: "payments@yourstore.com"
)
)
);
tpay.screenlessTransferPayment(payment);
无界面Raty Pekao支付
Raty Pekao支付需要Raty Pekao变体的渠道ID。
final payment = RatyPekaoPayment(
channelId: 81,
paymentDetails: PaymentDetails(
amount: 119.99,
description: "transaction description",
hiddenDescription: "hidden description",
language: Language.pl
),
payer: Payer(
name: "John Doe",
email: "example@example.com",
phone: null,
address: null
),
callbacks: Callbacks(
redirects: Redirects(
successUrl: "https://yourstore.com/success",
errorUrl: "https://yourstore.com/error",
),
notifications: Notifications(
url: "https://yourstore.com",
email: "payments@yourstore.com"
)
),
);
tpay.screenlessRatyPekaoPayment(payment);
无界面PayPo支付
final payment = PayPoPayment(
paymentDetails: PaymentDetails(
amount: 119.99,
description: "transaction description",
hiddenDescription: "hidden description",
language: Language.pl
),
payer: Payer(
name: "John Doe",
email: "example@example.com",
phone: null,
address: null
),
callbacks: Callbacks(
redirects: Redirects(
successUrl: "https://yourstore.com/success",
errorUrl: "https://yourstore.com/error",
),
notifications: Notifications(
url: "https://yourstore.com",
email: "payments@yourstore.com"
)
),
);
tpay.screenlessPayPoPayment(payment);
无界面信用卡支付
用户可以使用信用卡或信用卡令牌(仅限回头客)。当使用卡号、过期日期和CVV支付时,用户应该有一个选项保存卡片。如果选择了此选项,在成功支付后将发送卡令牌到定义的通知URL。
final payment = CreditCardPayment(
creditCard: CreditCard(
cardNumber: "card number",
expiryDate: ExpirationDate(
month: "12",
year: "24"
),
cvv: "123",
config: CreditCardConfig(
shouldSave: false,
domain: "yourstore.com"
)
),
creditCardToken: "card token",
paymentDetails: PaymentDetails(
amount: 19.99,
description: "transaction description",
hiddenDescription: "hidden description",
language: Language.pl
),
payer: Payer(
name: "John Doe",
email: "example@example.com",
phone: null,
address: null
),
callbacks: Callbacks(
redirects: Redirects(
successUrl: "https://yourstore.com/success",
errorUrl: "https://yourstore.com/error",
),
notifications: Notifications(
url: "https://yourstore.com",
email: "payments@yourstore.com"
)
)
);
tpay.screenlessCreditCardPayment(payment);
无界面Google Pay支付
用户可以使用Google Pay支付,为了开始支付,您需要提供Google Pay令牌。
final payment = GooglePayPayment(
token: "google pay token",
paymentDetails: PaymentDetails(
amount: 19.99,
description: "transaction description",
hiddenDescription: "hidden description",
language: Language.pl
),
payer: Payer(
name: "John Doe",
email: "example@example.com",
phone: null,
address: null
),
callbacks: Callbacks(
redirects: Redirects(
successUrl: "https://yourstore.com/success",
errorUrl: "https://yourstore.com/error",
),
notifications: Notifications(
url: "https://yourstore.com",
email: "payments@yourstore.com"
)
)
);
tpay.screenlessGooglePayPayment(payment);
无界面Apple Pay支付
用户可以使用Apple Pay支付,为了开始支付,您需要提供Apple Pay令牌。
final payment = ApplePayPayment(
applePayToken: "apple pay token",
paymentDetails: PaymentDetails(
amount: 19.99,
description: "transaction description",
hiddenDescription: "hidden description",
language: Language.pl
),
payer: Payer(
name: "John Doe",
email: "example@example.com",
phone: null,
address: null
),
callbacks: Callbacks(
redirects: Redirects(
successUrl: "https://yourstore.com/success",
errorUrl: "https://yourstore.com/error",
),
notifications: Notifications(
url: "https://yourstore.com",
email: "payments@yourstore.com"
)
)
);
tpay.screenlessApplePayPayment(payment);
处理无界面支付结果
void handleScreenlessResult(ScreenlessResult result) {
if (result is ScreenlessPaid) {
// 支付完成成功
}
if (result is ScreenlessPaymentCreated) {
// 支付成功创建
// 如果是BLIK支付,用户需要在银行应用中确认
// 如果是信用卡或转账支付,您需要
// 显示 result.paymentUrl 以完成支付
// 建议使用长轮询机制来观察
// 支付状态
// 您可以从 result.transactionId 中获取交易ID
}
if (result is ScreenlessPaymentError) {
// 创建支付失败
}
if (result is ScreenlessConfiguredPaymentFailed) {
// 创建支付失败因为错误
// - 信用卡数据或信用卡令牌
// - BLIK代码或BLIK别名
}
if (result is ScreenlessBlikAmbiguousAlias) {
// 当使用BLIK支付别名时,此结果表示
// 用户在一个银行注册了多个别名
// 向用户显示 result.aliases 并
// 继续使用 tpay.screenlessAmbiguousBLIKPayment(...) 方法支付
}
if (result is ScreenlessValidationError) {
// 传递的数据不正确
}
if (result is ScreenlessMethodCallError) {
// 插件出现问题
}
}
Google Pay工具(仅安卓)
SDK提供了几个与Google Pay交互的便捷方法。
// 在使用其他方法之前配置Google Pay工具
final configuration = GooglePayUtilsConfiguration(
price: 39.99, // 最终价格
merchantName: "YOUR_STORE_NAME",
merchantId: "MERCHANT_ID",
environment: GooglePayEnvironment.production
);
final configurationResult = await tpay.configureGooglePayUtils(configuration);
if (configurationResult is GooglePayConfigureSuccess) {
// 配置成功
}
if (configurationResult is GooglePayConfigureError) {
// 配置失败
// 通过 configurationResult.message 检查错误信息
}
// 检查Google Pay是否可用
// 如果未配置Google Pay工具,此方法将始终返回false
final isAvailable = await tpay.isGooglePayAvailable();
if (isAvailable) {
// 显示Google Pay按钮
}
// 如果Google Pay可用,您可以打开它
final googlePayResult = await tpay.openGooglePay();
if (googlePayResult is GooglePayOpenSuccess) {
// 成功收到信用卡数据
// 此结果包含 token, description, cardNetwork 和 cardTail 参数
// 使用 googlePayResult.token 参数与 tpay.screenlessGooglePayPayment(...)
// 一起创建一个Google Pay支付
}
if (googlePayResult is GooglePayOpenCancelled) {
// 用户关闭了Google Pay模块而未选择信用卡
}
if (googlePayResult is GooglePayOpenUnknownError) {
// 未知错误
}
if (googlePayResult is GooglePayOpenNotConfigured) {
// Google Pay工具未配置
}
获取支付渠道
获取您的商户账户可用的支付渠道。根据支付约束过滤渠道。
final result = await tpay.getAvailablePaymentChannels();
if (result is PaymentChannelsSuccess) {
// 收到了支付渠道
for (var channel in result.channels) {
// 渠道可能有支付约束
// 如果不满足,支付创建将失败
for (var constraint in channel.constraints) {
if (constraint is AmountPaymentConstraint) {
// 检查您的支付金额是否在
// - constraint.minimum
// - constraint.maximum
// 这个约束可以有:
// - 只有最小值
// - 只有最大值
// - 最小值和最大值
}
}
// 如果所有支付约束都满足,则显示支付渠道
}
}
if (result is PaymentChannelsError) {
// 发生错误
// 通过 result.message 读取错误信息
}
运行示例应用
git clone <github-link> tpay
cd tpay/example
flutter run
更多关于Flutter支付插件flutter_tpay的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter支付插件flutter_tpay的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,关于Flutter支付插件flutter_tpay
的使用,下面是一个简单的代码示例,展示了如何在Flutter应用中集成和使用该插件。
首先,确保你已经在pubspec.yaml
文件中添加了flutter_tpay
依赖:
dependencies:
flutter:
sdk: flutter
flutter_tpay: ^最新版本号 # 请替换为实际的最新版本号
然后,运行flutter pub get
来获取依赖。
接下来,在你的Flutter应用中,你可以按照以下步骤使用flutter_tpay
进行支付:
- 导入插件:
在你的Dart文件中导入flutter_tpay
插件:
import 'package:flutter_tpay/flutter_tpay.dart';
- 配置支付参数:
在需要进行支付的地方,配置支付所需的参数。例如:
void initPayment() async {
// 配置支付参数
final FlutterTpay flutterTpay = FlutterTpay();
// 设置支付参数,这些参数应该根据你的实际支付需求来配置
Map<String, dynamic> paymentParams = {
'amount': '1000', // 支付金额,单位通常是分
'currency': 'NGN', // 货币类型
'email': 'user@example.com', // 用户邮箱
'fullname': 'John Doe', // 用户全名
'phone': '08012345678', // 用户电话号码
'merchant_key': 'your_merchant_key', // 商户密钥
'merchant_id': 'your_merchant_id', // 商户ID
'callback_url': 'https://yourcallbackurl.com', // 支付回调URL
'ref': 'unique_transaction_ref', // 交易唯一引用标识
'hash': 'generated_hash', // 根据商户密钥、商户ID、金额等生成的哈希值(通常用于验证支付请求的有效性)
'country': 'NG', // 国家代码
'custom': '{"order_id":"123456"}', // 自定义数据,可以是JSON字符串
};
try {
// 发起支付请求
bool result = await flutterTpay.initializePayment(paymentParams);
if (result) {
print('支付初始化成功');
} else {
print('支付初始化失败');
}
} catch (e) {
print('支付初始化过程中发生错误: $e');
}
}
注意:上述代码中的merchant_key
、merchant_id
、hash
等参数需要根据实际的支付服务提供商的要求进行配置。特别是hash
值,通常需要根据商户密钥、商户ID、金额等参数通过特定的算法生成,以确保支付请求的有效性。
- 调用支付功能:
你可以在按钮点击事件中调用initPayment
函数来启动支付流程:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Flutter TPay Example'),
),
body: Center(
child: ElevatedButton(
onPressed: initPayment,
child: Text('发起支付'),
),
),
),
);
}
}
在这个示例中,当用户点击“发起支付”按钮时,将调用initPayment
函数来初始化支付流程。
重要提示:
- 在实际使用中,请确保你已经正确配置了所有必要的支付参数,并且已经与支付服务提供商完成了必要的对接工作。
flutter_tpay
插件的具体使用方法和参数可能会随着版本的更新而发生变化,请务必参考最新的官方文档或插件仓库中的README文件。
希望这个示例能够帮助你在Flutter应用中集成和使用flutter_tpay
插件进行支付。