使用stripe_payment集成苹果支付时,由于官方文档写的不清楚,照着给的用例怎么也调不起苹果支付,自己琢磨了一遍api的调用顺序才将其调用成功。
stripe_payment地址: pub.flutter-io.cn/packages/st…
#stripe 项目是2020年做的,插件应该已经更新了很多版本,所以后面调用的API可能也有变化
stripe_payment: ^1.1.4
代码如下:
//国家码
String countryCode;
//货币单位
String currency;
//支付金额
String amount;
//标签
String label;
//客户秘钥,从后端拿
String clientSecret;
//轮训次数
int n = 0;
//判断设备是否支持支付
void doPay(){
StripePayment.deviceSupportsNativePay().then((value) async {
if (value != null && value) {
//调用支付
StripePayment.paymentRequestWithNativePay(
//苹果支付配置
applePayOptions: ApplePayPaymentOptions(
countryCode: countryCode,
currencyCode: currency,
items: [
ApplePayItem(
label: label,
amount: amount,
)
],
),
//谷歌支付配置
androidPayOptions: AndroidPayPaymentRequest(
totalPrice: amount,
currencyCode: currency,
),
).then((token) {
//生成confirmPaymentIntent,通知后台
StripePayment.createPaymentMethod(
PaymentMethodRequest(
card: CreditCard(
token: token.tokenId,
),
),
).then((paymentMethod) {
StripePayment.confirmPaymentIntent(
PaymentIntent(
clientSecret: data.clientSecret,
paymentMethodId: paymentMethod.id,
),
).then((paymentIntent) {
//完成支付
StripePayment.completeNativePayRequest();
//支付成功开始轮询查询后台支付状态
checkStripePayType(
paymentIntent.paymentIntentId!);
}).catchError((onError) {
StripePayment.cancelNativePayRequest();
payFailure();
});
}).catchError((onError) {
StripePayment.cancelNativePayRequest();
payFailure();
});
}).catchError((onError) {
StripePayment.cancelNativePayRequest();
payFailure();
});
} else {
payFailure();
}
}).catchError((onError) {
payFailure();
});
}
void checkStripePayType(String id) {
//调自己后端的接口,查询支付是否成功。
//stripe好像没有主动推消息告知支付是否成功的api,所以此处选择了轮训七次的方式
//方式有点蠢,如果有相应api,望告知。
Api.checkStripePayType(id).then((value) {
n = 0;
paySuccess();
}).catchError((error) {
//最多询问后台七次:后台数据是否同步更改,否则认为后台数据同步失败
if (n >= 7) {
n = 0;
payFailure();
} else {
n++;
//延迟两秒继续请求
Future.delayed(Duration(milliseconds: 2000), () {
checkStripePayType(id);
});
}
});
}
//支付失败的操作
void payFailure(){}
//支付成功的操作
void paySuccess(){}
```