Flutter支付集成插件flutter_zalopay_sdk的使用
Flutter支付集成插件flutter_zalopay_sdk的使用
flutter_zalopay_sdk
是一个用于在Flutter应用中集成Zalo Pay SDK的插件。本文将介绍如何设置和使用该插件。
开始前的准备
注意: 在使用 ZaloPaySDK 之前,需要从 Zalo 获取你的 appId
。在这个文档中,我们将使用 appId = 2553
,这是 Zalo 提供的示例 appId
。
平台配置
Android 配置
在 AndroidManifest.xml
文件中添加以下配置:
<activity
...
android:launchMode="singleTask"
...>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="demozpdk"
android:host="app" />
</intent-filter>
<meta-data
android:name="com.vng.zalo.sdk.APP_ID"
android:value="2553" />
<meta-data
android:name="com.vng.zalo.sdk.URI_SCHEME"
android:value="demozpdk://app" />
<meta-data
android:name="com.vng.zalo.sdk.ENVIRONMENT"
android:value="SANDBOX" /> <!-- 如果要使用生产环境,请替换为 "PRODUCTION" -->
</activity>
iOS 配置
在 Info.plist
文件中添加以下配置:
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>CFBundleURLName</key>
<string>com.flutterzalopay.flutterZaloSdkExample</string>
<key>CFBundleURLSchemes</key>
<array>
<string>demozpdk</string>
</array>
</dict>
<dict>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>CFBundleURLName</key>
<string>com.flutterzalopay.flutterZaloSdkExample</string>
<key>CFBundleURLSchemes</key>
<array>
<string>zp-redirect-2553</string>
</array>
</dict>
</array>
<key>LSApplicationQueriesSchemes</key>
<array>
<string>zalo</string>
<string>zalopay</string>
<string>zalopay.api.v2</string>
</array>
在 AppDelegate.swift
文件中添加以下代码:
import zpdk
override func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
return ZaloPaySDK.sharedInstance().application(app, open:url, sourceApplication: "vn.com.vng.zalopay", annotation:nil)
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
ZaloPaySDK.sharedInstance()?.initWithAppId(2553, uriScheme: "demozpdk://app", environment: .sandbox) // 如果要使用生产环境,请替换为 .production
return true
}
如何使用
调用 FlutterZaloPaySDK.payOrder(zpToken: String)
方法来发起支付请求。订单的最新状态可以通过 FlutterZaloPaySDK.currentStatus
来获取,默认值为 null
。
可用的状态包括:
FlutterZaloPaymentStatus.PROCESSING
FlutterZaloPaymentStatus.FAILED
FlutterZaloPaymentStatus.SUCCESS
FlutterZaloPaymentStatus.CANCELLED
示例代码
下面是一个完整的示例 Demo,展示了如何使用 flutter_zalopay_sdk
插件:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_zalo_sdk_example/repo/payment.dart';
import 'package:flutter_zalopay_sdk/flutter_zalopay_sdk.dart';
import 'package:flutter_zalo_sdk_example/utils/config.dart';
import 'package:flutter_zalo_sdk_example/utils/theme_data.dart';
void main() => runApp(App());
class App extends StatelessWidget {
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
title: AppConfig.appName,
theme: myTheme,
home: Dashboard(
title: AppConfig.appName,
version: AppConfig.version,
),
debugShowCheckedModeBanner: false,
);
}
}
class Dashboard extends StatefulWidget {
final String title;
final String version;
Dashboard({this.title, this.version});
[@override](/user/override)
_DashboardState createState() => _DashboardState();
}
class _DashboardState extends State<Dashboard> {
[@override](/user/override)
Widget build(BuildContext context) {
return GestureDetector(
child: Scaffold(
resizeToAvoidBottomInset: true,
appBar: AppBar(
elevation: 0,
leading: Center(child: Text(widget.version)),
title: Text(
widget.title,
style: Theme.of(context).textTheme.headline6,
),
),
body: SafeArea(
child: HomeZaloPay(widget.title),
),
),
onTap: () {
FocusScopeNode currentFocus = FocusScope.of(context);
if (!currentFocus.hasPrimaryFocus) {
currentFocus.unfocus();
}
},
);
}
}
class HomeZaloPay extends StatefulWidget {
final String title;
HomeZaloPay(this.title);
[@override](/user/override)
_HomeZaloPayState createState() => _HomeZaloPayState();
}
class _HomeZaloPayState extends State<HomeZaloPay> {
final textStyle = TextStyle(color: Colors.black54);
final valueStyle = TextStyle(
color: AppColor.accentColor, fontSize: 18.0, fontWeight: FontWeight.w400);
String zpTransToken = "";
String payResult = "";
String payAmount = "10000";
bool showResult = false;
[@override](/user/override)
void initState() {
super.initState();
}
Widget _btnCreateOrder(String value) => Padding(
padding: const EdgeInsets.symmetric(vertical: 20.0, horizontal: 20.0),
child: GestureDetector(
onTap: () async {
int amount = int.parse(value);
if (amount < 1000 || amount > 1000000) {
setState(() {
zpTransToken = "Invalid Amount";
});
} else {
showDialog(
context: context,
builder: (BuildContext context) {
return Center(
child: CircularProgressIndicator(),
);
});
var result = await createOrder(amount);
if (result != null) {
Navigator.pop(context);
zpTransToken = result.zptranstoken;
print("zpTransToken $zpTransToken'.");
setState(() {
zpTransToken = result.zptranstoken;
showResult = true;
});
}
}
},
child: Container(
height: 50.0,
alignment: Alignment.center,
decoration: BoxDecoration(
color: AppColor.primaryColor,
borderRadius: BorderRadius.circular(8.0),
),
child: Text("Create Order",
style: TextStyle(color: Colors.white, fontSize: 20.0))),
),
);
Widget _btnPay(String zpToken) => Padding(
padding: const EdgeInsets.symmetric(vertical: 20.0, horizontal: 20.0),
child: Visibility(
visible: showResult,
child: GestureDetector(
onTap: () async {
FlutterZaloPaySdk.payOrder(zpToken: zpToken).then((event) {
setState(() {
switch (event) {
case FlutterZaloPayStatus.cancelled:
payResult = "User Huỷ Thanh Toán";
break;
case FlutterZaloPayStatus.success:
payResult = "Thanh toán thành công";
break;
case FlutterZaloPayStatus.failed:
payResult = "Thanh toán thất bại";
break;
default:
payResult = "Thanh toán thất bại";
break;
}
});
});
},
child: Container(
height: 50.0,
alignment: Alignment.center,
decoration: BoxDecoration(
color: AppColor.primaryColor,
borderRadius: BorderRadius.circular(8.0),
),
child: Text("Pay",
style: TextStyle(color: Colors.white, fontSize: 20.0))),
),
));
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
_quickConfig,
TextFormField(
decoration: const InputDecoration(
hintText: 'Amount',
icon: Icon(Icons.attach_money),
),
initialValue: payAmount,
onChanged: (value) {
setState(() {
payAmount = value;
});
},
keyboardType: TextInputType.number,
),
_btnCreateOrder(payAmount),
Padding(
padding: const EdgeInsets.symmetric(vertical: 5.0),
child: Visibility(
child: Text(
"zptranstoken:",
style: textStyle,
),
visible: showResult,
),
),
Container(
padding: const EdgeInsets.symmetric(vertical: 5.0),
child: Text(
zpTransToken,
style: valueStyle,
),
),
_btnPay(zpTransToken),
Padding(
padding: const EdgeInsets.symmetric(vertical: 5.0),
child: Visibility(
child: Text("Transaction status:", style: textStyle),
visible: showResult),
),
Container(
padding: const EdgeInsets.symmetric(vertical: 5.0),
child: Text(
payResult,
style: valueStyle,
),
),
],
),
);
}
}
Widget _quickConfig = Container(
margin: const EdgeInsets.symmetric(vertical: 10.0, horizontal: 20.0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
padding: const EdgeInsets.symmetric(vertical: 10.0),
child: Text("AppID: 2553"),
),
],
),
],
),
);
更多关于Flutter支付集成插件flutter_zalopay_sdk的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter支付集成插件flutter_zalopay_sdk的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
在Flutter项目中集成flutter_zalopay_sdk
插件以实现支付功能,可以按照以下步骤进行。以下是一个基本的代码示例,展示如何在Flutter中使用flutter_zalopay_sdk
插件。
1. 添加依赖
首先,在你的pubspec.yaml
文件中添加flutter_zalopay_sdk
依赖:
dependencies:
flutter:
sdk: flutter
flutter_zalopay_sdk: ^最新版本号 # 请替换为实际发布的最新版本号
然后运行flutter pub get
来获取依赖。
2. 配置iOS和Android
iOS
在ios/Runner/Info.plist
中添加必要的配置,例如支付URL schemes等(具体配置请参考Zalopay SDK的官方文档)。
Android
在android/app/src/main/AndroidManifest.xml
中添加必要的权限和配置(同样,具体配置请参考官方文档)。
3. 初始化插件并调用支付功能
在你的Flutter代码中,初始化flutter_zalopay_sdk
并调用支付功能。以下是一个简单的示例:
import 'package:flutter/material.dart';
import 'package:flutter_zalopay_sdk/flutter_zalopay_sdk.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Flutter Zalopay SDK Example'),
),
body: Center(
child: ElevatedButton(
onPressed: _startPayment,
child: Text('Start Payment'),
),
),
),
);
}
Future<void> _startPayment() async {
try {
// 配置支付参数
final paymentParams = ZalopayParams(
merchantId: 'your_merchant_id', // 替换为你的商户ID
amount: '100.00', // 支付金额
currencyCode: 'USD', // 货币代码
orderRef: 'order_${DateTime.now().millisecondsSinceEpoch}', // 订单号
redirectUrl: 'your_redirect_url', // 回调URL
// 其他可选参数,请参考SDK文档
);
// 调用支付方法
final result = await Zalopay.startPayment(paymentParams);
// 处理支付结果
if (result.isSuccess) {
print('Payment successful');
// 支付成功后的逻辑处理
} else {
print('Payment failed: ${result.errorMessage}');
// 支付失败后的逻辑处理
}
} catch (e) {
print('Error starting payment: $e');
}
}
}
4. 处理支付回调
对于支付回调,通常需要在你的服务器端处理,因为支付成功后,Zalopay会向你的回调URL发送支付结果通知。你需要在你的服务器端设置相应的处理逻辑来验证支付结果并更新订单状态。
注意事项
- 确保你已经按照Zalopay SDK的官方文档完成了所有必要的配置和集成步骤。
- 在发布应用之前,务必在测试环境中充分测试支付功能。
- 处理支付结果时,要注意验证支付通知的真实性和完整性,防止伪造支付通知。
这个示例展示了如何在Flutter项目中集成flutter_zalopay_sdk
插件,并调用支付功能。具体的集成细节和参数配置,请参考Zalopay SDK的官方文档。