Flutter PayPal支付插件paypal_native_checkout的使用

Flutter PayPal支付插件paypal_native_checkout的使用

原生PayPal集成与Flutter

介绍一个用于实现无缝PayPal支付的Flutter插件,该插件支持Android和iOS平台的原生支持。此包消除了对WebView的需求,提供了流畅高效的结账体验。

(无需WebView)

改进

  • 修复了无尽加载问题。
  • 添加了从Flutter传递收货地址的支持。
  • 提供了是否添加地址的选项。

要求

平台 支持版本
Android API级别21及以上
iOS 版本13.0及以上

有关详细设置说明,请访问 PayPal Mobile Checkout文档

GitHub仓库

示例

Android演示 iOS演示

使用

在您的 pubspec.yaml 文件中添加 paypal_native_checkout 作为依赖项。对于Android设置,确保在 AndroidManifest.xmlbuild.gradle 中有必要的权限和配置。

Android平台视图

PayPal要求您对 AndroidManifest.xml 进行更改。

准备您的应用

在应用程序的 AndroidManifest.xml 文件中定义 android.permission.INTERNET 权限:

<manifest xmlns:android="http://schemas.android.com/apk/res/android">

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

</manifest>

在您的 android/app/build.gradle 中添加以下内容:

android {
    ...

    defaultConfig {

        minSdkVersion 23
        ...
    }
}

启用SDK

要启用PayPal移动结账SDK,请执行以下步骤:

  1. 导航到开发者控制台上的我的应用与凭据页面。
  2. 转到功能 > 其他功能并选中登录PayPal复选框。
  3. 单击高级设置,在那里您将找到返回URL字段。

您可以选择以下两种方法之一来设置返回URL:

  1. 使用在开发者控制台注册的Android App Link处理SDK重定向。
  2. 另外,使用您的应用程序ID(通常通过 BuildConfig.APPLICATION_ID 引用)并附加 ://paypalpay 作为后缀以注册返回URL。例如,如果您的应用程序ID是 com.paypal.app,则输入 com.paypal.app://paypalpay

确保开发人员控制台中的返回URL与SDK设置中使用的完全匹配。

其他注意事项:

  • 应用程序ID和返回URL必须使用小写字母。
  • 如果在开发人员控制台中更改返回URL,PayPal将要求审查您的应用。
  • 在高级设置下选择全名和电子邮件复选框;这些是身份API的作用域。

现在,SDK可以在您的应用中使用了。

如何使用库

查看 /example/lib/main.dart 中的示例。

import 'dart:math';

import 'package:flutter/material.dart';
import 'package:paypal_native_checkout/paypal_native_checkout.dart';
import 'package:paypal_native_checkout/models/custom/currency_code.dart';
import 'package:paypal_native_checkout/models/custom/environment.dart';
import 'package:paypal_native_checkout/models/custom/order_callback.dart';
import 'package:paypal_native_checkout/models/custom/purchase_unit.dart';
import 'package:paypal_native_checkout/models/custom/user_action.dart';
import 'package:paypal_native_checkout/str_helper.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final _paypalNativeCheckoutPlugin = PaypalNativeCheckout.instance;
  // log queue
  List<String> logQueue = [];

  @override
  void initState() {
    super.initState();
    initPayPal();
  }

  void initPayPal() async {
    // 设置调试模式进行错误日志记录
    PaypalNativeCheckout.isDebugMode = true;

    // 初始化PayPal插件
    await _paypalNativeCheckoutPlugin.init(
      // 您的应用ID,注意不能有下划线!参阅readme.md获取帮助
      returnUrl: "com.example.example://paypalpay",
      // 开发者控制台中的客户端ID
      clientID: "ATeY...",
      // 沙盒、测试版或正式环境等
      payPalEnvironment: FPayPalEnvironment.sandbox,
      // 您打算使用的货币类型,默认为美元
      currencyCode: FPayPalCurrencyCode.usd,
      // 动作为立即付款?
      action: FPayPalUserAction.payNow,
    );

    // 支付回调
    _paypalNativeCheckoutPlugin.setPayPalOrderCallback(
      callback: FPayPalOrderCallback(
        onCancel: () {
          // 用户取消了支付
          showResult("cancel");
        },
        onSuccess: (data) {
          debugPrint("Paypal Success: $data");
          // 成功支付
          // 清除购物车中的所有项目
          _paypalNativeCheckoutPlugin.removeAllPurchaseItems();
          String visitor = data.cart?.shippingAddress?.firstName ?? 'Visitor';
          String address = data.cart?.shippingAddress?.line1 ?? 'Unknown Address';
          showResult(
            "Order successful ${data.payerId ?? ""} - ${data.orderId ?? ""} - $visitor -$address",
          );
        },
        onError: (data) {
          debugPrint("Paypal Error: ${data.reason}");
          // 发生错误
          showResult("error: ${data.reason}");
        },
        onShippingChange: (data) {
          // 用户更新了收货地址
          showResult(
            "shipping change: ${data.shippingChangeAddress?.adminArea1 ?? ""}",
          );
        },
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: const Text("Paypal Native Checkout"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            for (String t in logQueue) Text(t),
            ElevatedButton(
              style: ElevatedButton.styleFrom(
                  backgroundColor: Color.fromARGB(255, 16, 30, 227),
                  foregroundColor: Colors.white),
              child: const Text("Pay Now"),
              onPressed: () {
                // 添加1个项目到购物车。最多4个!
                if (_paypalNativeCheckoutPlugin.canAddMorePurchaseUnit) {
                  _paypalNativeCheckoutPlugin.addPurchaseUnit(
                    FPayPalPurchaseUnit(
                      // 随机价格
                      amount: Random().nextDouble() * 100,

                      /// 请使用自己的算法生成referenceId。例如,产品ID?
                      referenceId: FPayPalStrHelper.getRandomString(16),
                    ),
                  );
                }
                Map<String, dynamic>? getAddress = {
                  'line1': '456 Main Dt',
                  'line2': 'Apt 4B',
                  'city': 'San Jose',
                  'state': 'CA',
                  'postalCode': '95131',
                  'countryCode': 'US',
                };

                _paypalNativeCheckoutPlugin.makeOrder(
                    action: FPayPalUserAction.payNow, address: getAddress);
              },
            ),
          ],
        ),
      ),
    );
  }

  // 将所有信息添加到日志队列
  showResult(String text) {
    logQueue.add(text);
    setState(() {});
  }
}

故障排除技巧

如果您遇到此库的问题,请阅读以下内容:

  • 如果在使用包后遇到 <code>android:label</code> 的问题,请在您的 <code>Androidmanifest.xml</code> 的应用程序标签中添加以下内容:
   <application
        tools:replace="android:label" 
        xmlns:tools="http://schemas.android.com/tools"

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

1 回复

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


当然,下面是一个关于如何在Flutter项目中使用paypal_native_checkout插件进行PayPal支付的示例代码。这个插件允许你通过PayPal的原生SDK进行支付,从而提供更好的用户体验和更高的支付成功率。

首先,确保你已经在pubspec.yaml文件中添加了paypal_native_checkout依赖:

dependencies:
  flutter:
    sdk: flutter
  paypal_native_checkout: ^2.0.0  # 请注意版本号,这里使用的是假设的版本号,实际使用时请查看最新版本

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

接下来,你需要进行一些配置。对于iOS,你需要在Info.plist中添加以下配置来允许PayPal SDK正常工作:

<key>LSApplicationQueriesSchemes</key>
<array>
    <string>paypal</string>
    <string>paypalhere</string>
    <string>braintree</string>
    <string>braintree-sdk</string>
    <string>venmo</string>
</array>

对于Android,你需要在AndroidManifest.xml中添加以下权限和网络配置:

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

<application>
    <!-- 其他配置 -->
    <activity android:name="com.paypal.android.sdk.payments.PaymentActivity"
        android:configChanges="orientation|keyboardHidden|screenSize"
        android:screenOrientation="behind"
        android:windowSoftInputMode="adjustResize"/>
    <activity android:name="com.paypal.android.sdk.payments.LoginActivity"
        android:configChanges="orientation|keyboardHidden|screenSize"
        android:screenOrientation="behind"
        android:windowSoftInputMode="adjustResize"/>
    <activity android:name="com.paypal.android.sdk.payments.PaymentMethodActivity"
        android:configChanges="orientation|keyboardHidden|screenSize"
        android:screenOrientation="behind"
        android:windowSoftInputMode="adjustResize"/>
    <activity android:name="io.card.payment.CardIOActivity"
        android:configChanges="orientation|keyboardHidden|screenSize"
        android:screenOrientation="behind"
        android:windowSoftInputMode="stateHidden|adjustResize"/>
    <activity android:name="io.card.payment.DataEntryActivity"/>
</application>

现在,你可以在你的Flutter代码中使用paypal_native_checkout插件进行支付了。下面是一个简单的示例:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('PayPal Payment Example'),
        ),
        body: Center(
          child: ElevatedButton(
            onPressed: () async {
              try {
                final PayPalConfiguration config = PayPalConfiguration(
                  clientId: 'YOUR_PAYPAL_CLIENT_ID', // 请替换为你的PayPal客户端ID
                  environment: PayPalEnvironment.sandbox, // 如果是生产环境,请使用PayPalEnvironment.production
                  returnUrl: 'yourapp://paypal', // 请确保这个URL在你的应用中注册过
                );

                final result = await PayPalCheckout.start(
                  context: context,
                  configuration: config,
                  payment: PayPalPayment(
                    amount: '10.00',
                    currencyCode: 'USD',
                    shortDescription: 'Test payment',
                    intent: PayPalPaymentIntent.sale,
                  ),
                );

                if (result.status == PayPalPaymentStatus.approved) {
                  // 支付成功,处理支付结果
                  print('Payment approved: ${result.response?.confirmation?.id}');
                } else if (result.status == PayPalPaymentStatus.cancelled) {
                  // 支付取消
                  print('Payment cancelled');
                } else {
                  // 支付失败
                  print('Payment failed');
                }
              } catch (e) {
                // 处理错误
                print('Error: $e');
              }
            },
            child: Text('Pay with PayPal'),
          ),
        ),
      ),
    );
  }
}

在这个示例中,我们创建了一个简单的Flutter应用,其中包含一个按钮。当用户点击按钮时,将启动PayPal支付流程。你需要将YOUR_PAYPAL_CLIENT_ID替换为你从PayPal开发者控制台获取的客户端ID。

请确保你已经正确设置了PayPal的客户端ID,并且你的应用已经在PayPal开发者控制台中注册过。此外,对于生产环境,请确保将PayPalEnvironment.sandbox更改为PayPalEnvironment.production

希望这个示例能帮你顺利集成PayPal支付功能!

回到顶部