Flutter支付处理插件flutter_stripe_payment的使用

Flutter支付处理插件flutter_stripe_payment的使用

flutter_stripe_payment

将 Stripe 添加到您的 Flutter 应用程序中,以使用 Payment Intents 和最新的 SCA 合规性 3DS 要求接受卡支付。

Getting Started

强客户认证 (SCA) 是 PSD2 法规在欧洲生效的新规则的一部分,于 2019 年 9 月 14 日开始实施。这将要求对您的欧洲客户的在线支付认证方式进行更改。卡支付将需要不同的用户体验,即 3D Secure,以满足 SCA 要求。不符合新认证指南的交易可能会被客户的银行拒绝。

Payment Intents API 是构建动态支付流程的新方法。它跟踪客户结账流程的生命周期,并在法规要求、自定义 Radar 欺诈规则或重定向支付方式需要时触发额外的认证步骤。

Initialize

final _stripePayment = FlutterStripePayment();
_stripePayment.onCancel = (){
  print("User Cancelled the Payment Method Form");
};

Setup Stripe Environment

_stripePayment.setStripeSettings(
        appConfig.values.stripePublishableKey,
        appConfig.values.applePayMerchantId);

Show Payment Form

var paymentResponse = await _stripePayment.addPaymentMethod();
if(paymentResponse.status == PaymentResponseStatus.succeeded)
  {
    print(paymentResponse.paymentMethodId);
  }

Create Payment Intent On Server

var intent = PaymentIntent();
    intent.amount = widget.order.cart.total;
    intent.isManual = true;
    intent.isConfirmed = false;
    intent.paymentMethodId = paymentResponse.paymentMethodId;
    intent.currency = "usd";
    intent.isOnSession = true;
    intent.isSuccessful = false;
    intent.statementDescriptor = "Dorm Mom, Inc";
    var response = await widget.clientDataStore.createPaymentIntent(intent);

Confirm Payment Intent to Kick Off 3D Authentication

var intentResponse = await _stripePayment.confirmPaymentIntent(
          response.clientSecret, paymentResponse.paymentMethodId, widget.order.cart.total);

      if (intentResponse.status == PaymentResponseStatus.succeeded) {
        widget.order.paymentIntentId = intentResponse.paymentIntentId;
        widget.order.paymentMethodId = paymentResponse.paymentMethodId;
        _submitOrder();
      } else if (intentResponse.status == PaymentResponseStatus.failed) {
        setState(() {
          hideBusy();
        });
        globals.Utility.showAlertPopup(
            context, "Error Occurred", intentResponse.errorMessage);
      } else {
        setState(() {
          hideBusy();
        });
      }

Setup Payment Intent For Future Payments

var intentResponse = await _stripePayment.setupPaymentIntent(
        response.clientSecret, paymentResponse.paymentMethodId);

    if (intentResponse.status == PaymentResponseStatus.succeeded) {
      await _addCardToAccount(paymentResponse.paymentMethodId);
    } else if (intentResponse.status == PaymentResponseStatus.failed) {
      setState(() {
        hideBusy();
      });
      globals.Utility.showAlertPopup(
          context, "Error Occurred", intentResponse.errorMessage);
    } else {
      setState(() {
        hideBusy();
      });
    }

Screenshots

iOS View Android View
iOS View Android View

To Do

  • [DONE] Android Implementation
  • STPaymentCardTextField Inline Embedding

示例代码

import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_stripe_payment/flutter_stripe_payment.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String? _paymentMethodId;
  String? _errorMessage = "";
  final _stripePayment = FlutterStripePayment();
  var _isNativePayAvailable = false;

  @override
  void initState() {
    super.initState();
    _stripePayment.setStripeSettings(
        "{STRIPE_PUBLISHABLE_KEY}", "{STRIPE_APPLE_PAY_MERCHANTID}");
    _stripePayment.onCancel = () {
      print("the payment form was cancelled");
    };
    checkIfAppleOrGooglePayIsAvailable();
  }

  void checkIfAppleOrGooglePayIsAvailable() async {
    var available = await _stripePayment.isNativePayAvailable();
    setState(() {
      _isNativePayAvailable = available;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Stripe App Example'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              _paymentMethodId != null
                  ? Text(
                      "Payment Method Returned is $_paymentMethodId",
                      textAlign: TextAlign.center,
                    )
                  : Container(
                      child: Text(_errorMessage ?? ""),
                    ),
              ElevatedButton(
                child: Text("Create a Card Payment Method"),
                onPressed: () async {
                  var paymentResponse = await _stripePayment.addPaymentMethod();
                  setState(() {
                    if (paymentResponse.status ==
                        PaymentResponseStatus.succeeded) {
                      _paymentMethodId = paymentResponse.paymentMethodId;
                    } else {
                      _errorMessage = paymentResponse.errorMessage;
                    }
                  });
                },
              ),
              ElevatedButton(
                child: Text(
                    "Get ${Platform.isIOS ? "Apple" : (Platform.isAndroid ? "Google" : "Native")} Pay Token"),
                onPressed: !_isNativePayAvailable ? null : () async {
                  var paymentItem =
                      PaymentItem(label: 'Air Jordan Kicks', amount: 249.99);
                  var taxItem =
                      PaymentItem(label: 'NY Sales Tax', amount: 21.87);
                  var shippingItem =
                      PaymentItem(label: 'Shipping', amount: 5.99);
                  var stripeToken =
                      await _stripePayment.getPaymentMethodFromNativePay(
                          countryCode: "US",
                          currencyCode: "USD",
                          paymentNetworks: [
                            PaymentNetwork.visa,
                            PaymentNetwork.mastercard,
                            PaymentNetwork.amex,
                            PaymentNetwork.discover
                          ],
                          merchantName: "Nike Inc.",
                          isPending: false,
                          paymentItems: [paymentItem, shippingItem, taxItem]);
                  print("Stripe Payment Token from Apple Pay: $stripeToken");
                },
              )
            ],
          ),
        ),
      ),
    );
  }
}

更多关于Flutter支付处理插件flutter_stripe_payment的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter支付处理插件flutter_stripe_payment的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中集成和使用flutter_stripe_payment插件来处理支付的示例代码。

1. 添加依赖

首先,在你的pubspec.yaml文件中添加flutter_stripe_payment依赖:

dependencies:
  flutter:
    sdk: flutter
  flutter_stripe_payment: ^x.y.z  # 请替换为最新版本号

然后运行flutter pub get来安装依赖。

2. 配置iOS和Android

iOS

ios/Runner/Info.plist中添加Stripe的支付权限:

<key>NSPaymentRequestMerchantCapabilities</key>
<array>
    <string>supports3DSecure</string>
</array>
<key>StripePublishableKey</key>
<string>你的Stripe发布密钥</string>

确保你的项目配置有适当的支付权限。

Android

android/app/src/main/AndroidManifest.xml中添加必要的权限:

<uses-permission android:name="android.permission.INTERNET"/>

3. 初始化Stripe并处理支付

在你的Flutter代码中,你可以这样初始化Stripe并处理支付:

import 'package:flutter/material.dart';
import 'package:flutter_stripe_payment/flutter_stripe_payment.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Stripe Payment Example'),
        ),
        body: Center(
          child: StripePaymentExample(),
        ),
      ),
    );
  }
}

class StripePaymentExample extends StatefulWidget {
  @override
  _StripePaymentExampleState createState() => _StripePaymentExampleState();
}

class _StripePaymentExampleState extends State<StripePaymentExample> {
  final StripePayment _stripePayment = StripePayment();

  @override
  void initState() {
    super.initState();
    _stripePayment.setOptions(
      StripePaymentOptions(
        publishableKey: '你的Stripe发布密钥',  // 在这里替换为你的Stripe发布密钥
      ),
    );
  }

  void handlePayment() async {
    try {
      StripePaymentIntentResult result = await _stripePayment.createPaymentIntent(
        amount: 1000,  // 单位为美分,这里表示10美元
        currency: 'usd',
      );

      if (result.status == 'succeeded') {
        print('Payment succeeded!');
        // 处理支付成功后的逻辑
      } else {
        print('Payment failed: ${result.error?.localizedMessage}');
        // 处理支付失败后的逻辑
      }
    } catch (e) {
      print('Error during payment: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: handlePayment,
      child: Text('Pay with Stripe'),
    );
  }
}

4. 运行应用

确保你的设备或模拟器已经配置好,然后运行应用:

flutter run

注意事项

  1. 安全性:不要在客户端代码中硬编码敏感信息,如Stripe密钥。最好使用安全存储(如环境变量或密钥管理服务)来管理这些信息。
  2. 测试:在开发过程中使用Stripe的测试密钥和测试卡来测试支付流程。
  3. 生产环境:在发布到生产环境之前,确保使用正确的Stripe密钥,并测试所有支付场景。

这个示例代码展示了如何在Flutter应用中使用flutter_stripe_payment插件来处理支付。根据你的需求,你可能需要添加更多的错误处理和用户交互逻辑。

回到顶部