Flutter PayPal支付集成插件easy_paypal的使用
Flutter PayPal支付集成插件easy_paypal的使用
Easy Paypal
简介
Easy Paypal
是由InspireUI公司开发的原生PayPal结账模块。
Fluxstore
是一个受Flutter框架启发的通用电子商务应用。它的目标是减少企业在设计、开发和测试移动应用上花费的数千小时,为市场提供高生产力和成本效益的应用程序。它能够满足所有业务需求,包括电子商务功能、令人印象深刻的用户体验和在iOS和Android设备上的流畅性能。
使用步骤
1. 添加依赖
首先,在项目的pubspec.yaml
文件中添加easy_paypal
依赖:
dependencies:
easy_paypal: ^版本号
然后运行flutter pub get
以安装依赖。
2. 初始化配置
在应用程序初始化时,需要调用initConfig
方法来设置PayPal客户端ID和环境(沙箱或生产环境):
class _MyAppState extends State<MyApp> {
final _easyPaypalPlugin = EasyPaypal();
final scaffoldMessengerKey = GlobalKey<ScaffoldMessengerState>();
final navigatorKey = GlobalKey<NavigatorState>();
[@override](/user/override)
void initState() {
super.initState();
initPlatformState();
}
Future<void> initPlatformState() async {
try {
_easyPaypalPlugin.initConfig(
config: const PPCheckoutConfig(
clientId: '您的客户端ID',
environment: PPEnvironment.sandbox, // 或 PPEnvironment.production
returnUrl: 'com.example.easy.paypal://paypalpay',
),
);
_easyPaypalPlugin.setCallback(PPCheckoutCallback(
onApprove: (data) {
// 成功回调
showCupertinoDialog(
context: navigatorKey.currentContext!,
builder: (context) {
return CupertinoAlertDialog(
title: const Text('成功'),
content: Column(
children: [
Text('订单ID: ${data.orderId}'),
Text('付款人ID: ${data.payerId}'),
Text('JSON数据: ${data.toJson()}'),
],
),
actions: [
CupertinoDialogAction(
child: const Text('确定'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
debugPrint('onApprove: $data');
},
onError: (data) {
// 错误回调
final snackBar = SnackBar(
content: Text(data.reason),
behavior: SnackBarBehavior.floating,
);
scaffoldMessengerKey.currentState?.showSnackBar(snackBar);
debugPrint('onError: $data');
},
onCancel: () {
debugPrint('onCancel');
},
onShippingChange: (data) {
debugPrint('onShippingChange: $data');
},
));
} catch (e) {
debugPrint(':::: ERROR: $e');
}
if (!mounted) return;
}
}
3. 创建订单
创建一个订单对象,并根据需要设置订单信息,例如意图、应用上下文、购买单元等:
var order = const PPOrder(
intent: PPOrderIntent.capture,
appContext: PPOrderAppContext(
brandName: 'Easy Paypal',
shippingPreference: PPShippingPreference.noShipping,
userAction: PPUserAction.payNowAction,
),
purchaseUnitList: [
PPPurchaseUnit(
referenceId: 'test',
shipping: PPShipping(
address: PPOrderAddress(
addressLine1: '123 Main St',
adminArea1: 'TX',
adminArea2: 'Austin',
postalCode: '78751',
countryCode: 'US',
),
),
orderAmount: PPOrderAmount(
currencyCode: PPCurrencyCode.usd,
value: '6',
),
),
],
);
4. 触发支付
通过调用checkout
方法触发支付流程:
floatingActionButton: FloatingActionButton(
onPressed: () {
_easyPaypalPlugin.checkout(order: order);
},
child: const Icon(Icons.shopping_cart),
),
5. 构建用户界面
构建一个表单,允许用户输入订单详细信息并提交:
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
scaffoldMessengerKey: scaffoldMessengerKey,
navigatorKey: navigatorKey,
home: Scaffold(
appBar: AppBar(
title: const Text('PayPal插件示例应用'),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
_easyPaypalPlugin.checkout(order: order);
},
child: const Icon(Icons.shopping_cart),
),
body: GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () {
// 隐藏键盘
FocusScope.of(context).requestFocus(FocusNode());
},
child: Form(
child: SingleChildScrollView(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// 订单意图
Text(
'意图',
style: Theme.of(context).textTheme.titleLarge,
),
Item(
title: '意图',
child: DropdownButtonFormField<PPOrderIntent>(
value: order.intent,
items: PPOrderIntent.values
.map((e) => DropdownMenuItem(
value: e,
child: Text(e.name.screamingSnake),
))
.toList(),
onChanged: (value) {
order = order.copyWith(intent: value!);
},
),
),
const Divider(),
// 应用上下文
Text(
'应用上下文',
style: Theme.of(context).textTheme.titleLarge,
),
const Divider(),
Item(
title: '配送偏好',
child: DropdownButtonFormField<PPShippingPreference>(
value: order.appContext?.shippingPreference,
items: PPShippingPreference.values
.map((e) => DropdownMenuItem(
value: e,
child: Text(e.name.screamingSnake),
))
.toList(),
onChanged: (value) {
order = order.copyWith(
appContext: order.appContext
?.copyWith(shippingPreference: value!));
},
),
),
Item(
title: '用户操作',
child: DropdownButtonFormField<PPUserAction>(
value: order.appContext?.userAction,
items: PPUserAction.values
.map((e) => DropdownMenuItem(
value: e,
child: Text(e.name.screamingSnake),
))
.toList(),
onChanged: (value) {
order = order.copyWith(
appContext: order.appContext
?.copyWith(userAction: value!));
},
),
),
const Divider(),
// 购买单元
Text(
'购买单元',
style: Theme.of(context).textTheme.titleLarge,
),
const Divider(),
Item(
title: '引用ID',
child: TextFormField(
initialValue: order.purchaseUnitList.first.referenceId,
onChanged: (value) {
order = order.copyWith(
purchaseUnitList: [
PPPurchaseUnit(
referenceId: value,
shipping: order.purchaseUnitList.first.shipping,
orderAmount: order.purchaseUnitList.first.orderAmount,
),
],
);
},
),
),
const Divider(),
Text(
'配送',
style: Theme.of(context).textTheme.titleMedium,
),
const Divider(),
Item(
title: '地址行1',
child: TextFormField(
initialValue: order.purchaseUnitList.first.shipping
?.address?.addressLine1,
onChanged: (value) {
order = order.copyWith(
purchaseUnitList: [
PPPurchaseUnit(
referenceId: order.purchaseUnitList.first.referenceId,
shipping: order.purchaseUnitList.first.shipping
?.copyWith(
address: order.purchaseUnitList.first.shipping
?.address
?.copyWith(
addressLine1: value,
),
),
orderAmount: order.purchaseUnitList.first.orderAmount,
),
],
);
},
),
),
// 其他字段...
// 货币代码
Item(
title: '货币代码',
child: DropdownButtonFormField<PPCurrencyCode>(
value: order.purchaseUnitList.first.orderAmount.currencyCode,
items: PPCurrencyCode.values
.map((e) => DropdownMenuItem(
value: e,
child: Text(e.name.screamingSnake),
))
.toList(),
onChanged: (value) {
order = order.copyWith(
purchaseUnitList: [
PPPurchaseUnit(
referenceId: order.purchaseUnitList.first.referenceId,
shipping: order.purchaseUnitList.first.shipping,
orderAmount: PPOrderAmount(
currencyCode: value!,
value: order.purchaseUnitList.first.orderAmount.value,
),
),
],
);
},
),
),
// 值
Item(
title: '值',
child: TextFormField(
initialValue: order.purchaseUnitList.first.orderAmount.value.toString(),
onChanged: (value) {
order = order.copyWith(
purchaseUnitList: [
PPPurchaseUnit(
referenceId: order.purchaseUnitList.first.referenceId,
shipping: order.purchaseUnitList.first.shipping,
orderAmount: PPOrderAmount(
currencyCode: order.purchaseUnitList.first.orderAmount.currencyCode,
value: value,
),
),
],
);
},
),
),
],
),
),
),
),
);
}
}
更多关于Flutter PayPal支付集成插件easy_paypal的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter PayPal支付集成插件easy_paypal的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,下面是一个关于如何在Flutter应用中集成easy_paypal
插件来实现PayPal支付的代码案例。这个插件可以让你在Flutter应用中轻松集成PayPal支付功能。
首先,确保你的Flutter项目已经创建,并且你已经安装了必要的依赖。
-
添加依赖: 在你的
pubspec.yaml
文件中添加easy_paypal
依赖:dependencies: flutter: sdk: flutter easy_paypal: ^latest_version # 请替换为最新的版本号
然后运行
flutter pub get
来安装依赖。 -
配置PayPal: 在使用
easy_paypal
之前,你需要在PayPal开发者网站创建一个应用并获取客户端ID。确保你已经完成了这一步。 -
集成PayPal支付: 下面是一个简单的Flutter应用示例,展示如何使用
easy_paypal
插件进行支付。import 'package:flutter/material.dart'; import 'package:easy_paypal/easy_paypal.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'PayPal Payment Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: PayPalPaymentScreen(), ); } } class PayPalPaymentScreen extends StatefulWidget { @override _PayPalPaymentScreenState createState() => _PayPalPaymentScreenState(); } class _PayPalPaymentScreenState extends State<PayPalPaymentScreen> { final String clientId = 'YOUR_PAYPAL_CLIENT_ID'; // 替换为你的PayPal客户端ID @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('PayPal Payment'), ), body: Center( child: ElevatedButton( onPressed: () async { try { // 创建支付配置 PayPalPayment payment = PayPalPayment( amount: '10.00', currencyCode: 'USD', shortDescription: 'Test Payment', intent: 'sale', ); // 发起支付 PayPalResponse response = await PayPal.instance.pay(payment, clientId: clientId); if (response.status == 'approved') { showDialog( context: context, builder: (BuildContext context) { return AlertDialog( title: Text('Payment Approved'), content: Text('Payment successfully approved!'), actions: <Widget>[ TextButton( child: Text('OK'), onPressed: () { Navigator.of(context).pop(); }, ), ], ); }, ); } else { showDialog( context: context, builder: (BuildContext context) { return AlertDialog( title: Text('Payment Declined'), content: Text('Payment was declined or canceled. Status: ${response.status}'), actions: <Widget>[ TextButton( child: Text('OK'), onPressed: () { Navigator.of(context).pop(); }, ), ], ); }, ); } } catch (e) { showDialog( context: context, builder: (BuildContext context) { return AlertDialog( title: Text('Error'), content: Text('An error occurred: $e'), actions: <Widget>[ TextButton( child: Text('OK'), onPressed: () { Navigator.of(context).pop(); }, ), ], ); }, ); } }, child: Text('Pay with PayPal'), ), ), ); } }
在这个示例中,当用户点击“Pay with PayPal”按钮时,会触发PayPal支付流程。你需要替换YOUR_PAYPAL_CLIENT_ID
为你的实际PayPal客户端ID。
这个示例代码展示了如何创建一个简单的PayPal支付请求,并处理支付结果。你可以根据需求进一步自定义和扩展这个示例。