Flutter如何实现Apple Pay支付功能插件
在Flutter中如何集成Apple Pay支付功能?有没有现成的插件可以使用?具体实现步骤是什么?需要注意哪些配置和权限问题?希望能分享一个完整的示例代码或教程。
2 回复
使用stripe_payment或flutter_inapp_purchase插件。配置iOS证书,调用插件API处理支付流程,监听支付结果。
更多关于Flutter如何实现Apple Pay支付功能插件的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
在Flutter中实现Apple Pay支付功能,可以通过创建自定义插件或使用现有插件来集成iOS的PassKit框架。以下是实现步骤和示例:
1. 使用现有插件(推荐)
flutter_stripe 或 apple_pay 插件提供了现成的Apple Pay集成:
# pubspec.yaml
dependencies:
flutter_stripe: ^10.4.0 # 或 apple_pay: ^2.0.0
基础代码示例(使用flutter_stripe):
import 'package:flutter_stripe/flutter_stripe.dart';
class ApplePayService {
static Future<void> init() async {
Stripe.publishableKey = "YOUR_STRIPE_PUBLISHABLE_KEY";
}
static Future<void> pay() async {
final paymentIntent = await createPaymentIntent(); // 通过后端创建支付Intent
await Stripe.instance.applePay(
const ApplePayPresentParams(
cartItems: [
ApplePayCartSummaryItem(
label: '商品名称',
amount: '10.00',
)
],
country: 'US',
currency: 'USD',
),
);
}
}
2. 自定义插件开发步骤
若需完全自定义,按以下流程:
iOS端(Swift):
- 创建插件通道:
// SwiftHandler.swift
import PassKit
public class SwiftApplePayPlugin: NSObject {
private var channel: FlutterMethodChannel?
public static func register(with registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel(name: "apple_pay", binaryMessenger: registrar.messenger())
let instance = SwiftApplePayPlugin()
instance.channel = channel
registrar.addMethodCallDelegate(instance, channel: channel)
}
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
switch call.method {
case "canMakePayments":
result(PKPaymentAuthorizationController.canMakePayments())
case "requestPayment":
requestPayment(call.arguments, result: result)
default:
result(FlutterMethodNotImplemented)
}
}
private func requestPayment(_ arguments: Any?, result: @escaping FlutterResult) {
// 配置PKPaymentRequest并弹出支付界面
let request = PKPaymentRequest()
request.merchantIdentifier = "YOUR_MERCHANT_ID"
request.countryCode = "US"
request.currencyCode = "USD"
request.supportedNetworks = [.visa, .masterCard]
request.merchantCapabilities = .capability3DS
request.paymentSummaryItems = [
PKPaymentSummaryItem(label: "商品", amount: NSDecimalNumber(string: "10.00"))
]
let controller = PKPaymentAuthorizationController(paymentRequest: request)
controller.delegate = self
controller.present { _ in }
}
}
Flutter端(Dart):
// apple_pay.dart
class ApplePay {
static const MethodChannel _channel = MethodChannel('apple_pay');
static Future<bool> get canMakePayments async {
return await _channel.invokeMethod('canMakePayments');
}
static Future<void> requestPayment(Map<String, dynamic> params) async {
await _channel.invokeMethod('requestPayment', params);
}
}
3. 必要配置
- Apple Developer配置:
- 启用Apple Pay能力
- 配置Merchant ID并关联证书
- Xcode设置:在
Info.plist中添加NSApplePayUsageDescription
注意事项
- 真机测试:Apple Pay仅支持实体设备
- 后端集成:支付需与支付网关(如Stripe)后端交互完成
- 审核要求:确保符合App Store审核指南
推荐优先使用flutter_stripe等成熟插件,可减少底层开发复杂度并确保安全性。

