Flutter PayPal支付插件paypal_mobile_web的使用

Flutter PayPal支付插件paypal_mobile_web的使用

本文档介绍了如何在Flutter应用中使用paypal_mobile_web插件进行支付。该插件允许通过PayPal的API接收支付请求,并在Web端展示支付页面。

简介

paypal_mobile_web 是一个用于在Flutter Web应用程序中集成PayPal支付功能的插件。它允许开发者通过简单的配置实现PayPal支付流程,支持沙盒模式测试和实际支付环境。


插件功能概述

  1. 获取PayPal支付URL
    使用插件可以生成支付所需的URL。

  2. 跳转到PayPal支付页面
    用户可以通过生成的URL跳转到PayPal的支付页面完成支付。

  3. 处理支付结果
    在用户完成支付后,可以处理返回的支付结果并执行后续逻辑。


使用步骤

以下是一个完整的示例,展示如何在Flutter Web应用中使用 paypal_mobile_web 插件。

1. 添加依赖

首先,在项目的 pubspec.yaml 文件中添加 paypal_mobile_web 依赖:

dependencies:
  paypal_mobile_web: ^0.0.1

然后运行以下命令安装依赖:

flutter pub get

2. 配置PayPal账户

在开始开发之前,确保你已经在PayPal开发者门户网站上创建了一个账户,并获取了以下信息:

  • Client ID: 应用程序的客户端ID。
  • Secret Key: 应用程序的密钥。

这些信息将在支付过程中用于生成支付URL。


3. 编写代码

以下是一个完整的示例代码,展示了如何使用 paypal_mobile_web 插件进行支付。

示例代码

import 'dart:developer';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:paypal_mobile_web/paypal_mobile_web.dart';
import 'package:flutter_custom_tabs/flutter_custom_tabs.dart';
import 'package:url_launcher/url_launcher_string.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  // 启动PayPal支付流程
  _launchURL() async {
    // 调用插件方法获取支付URL
    Map resultPaypal = await PaypalCheckout().getMapCheckout(
        clientId: "AXs_4ClaWWjkdXbcD7mzGwvcs7Z8sXRuPL_OnQvE8p-3EI4F-uq5iSupvSYAafEXXGLjv9GCv2pK1Oqn", // 替换为你的Client ID
        secretKey: "EGRlbRFxz8dXke-wrRxN0RMITZZtSb6R9l_SBp-G7xl_guT1jZTYl5wXUsJkhiApYAO986bhaFGG7_3L", // 替换为你的Secret Key
        note: "Contact us for any questions on your order",
        transactions: [
          {
            "amount": {
              "total": '100', // 支付金额
              "currency": "BRL", // 币种
              "details": {
                "subtotal": '100',
                "shipping": '0',
                "shipping_discount": 0
              }
            },
            "description": "The payment transaction description.",
            "item_list": {
              "items": [
                {
                  "name": "Apple",
                  "quantity": 4,
                  "price": '10',
                  "currency": "BRL"
                },
                {
                  "name": "Pineapple",
                  "quantity": 5,
                  "price": '12',
                  "currency": "BRL"
                }
              ]
            }
          }
        ],
        sandboxMode: true, // 是否启用沙盒模式
        returnURL: "http://localhost:60560/aprov?id=605656", // 支付成功后的回调地址
        cancelURL: "http://localhost:60560/cancelpag?id=05404"); // 支付取消后的回调地址

    // 打印生成的支付URL
    print("url Aproval: ${resultPaypal['approvalUrl']}");
    print("url execute: ${resultPaypal['executeUrl']}");
    print("MMap: ${resultPaypal}");

    // 检查是否可以打开URL
    if (await canLaunchUrlString(resultPaypal['approvalUrl'])) {
      await launchUrlString(resultPaypal['approvalUrl'], mode: LaunchMode.inAppBrowserView);
    } else {
      throw 'Could not launch ${resultPaypal['approvalUrl']}';
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            ElevatedButton(
                onPressed: _launchURL, child: const Text("发起支付")),
          ],
        ),
      ),
    );
  }
}

4. 运行应用

将上述代码保存到 lib/main.dart 文件中,然后运行以下命令启动应用:

flutter run -d chrome

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

1 回复

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


paypal_mobile_web 是一个 Flutter 插件,用于在 Flutter 应用中集成 PayPal 支付功能。该插件使用 PayPal 的移动网页支付 SDK,允许用户通过 PayPal 账户或信用卡进行支付。

以下是如何在 Flutter 项目中使用 paypal_mobile_web 插件的步骤:

1. 添加依赖

首先,在 pubspec.yaml 文件中添加 paypal_mobile_web 依赖:

dependencies:
  flutter:
    sdk: flutter
  paypal_mobile_web: ^1.0.0  # 请使用最新版本

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

2. 初始化 PayPal 支付

在你的 Dart 文件中,导入 paypal_mobile_web 插件并初始化 PayPal 支付。

import 'package:paypal_mobile_web/paypal_mobile_web.dart';

void initPayPal() async {
  try {
    await PaypalMobileWeb.init(
      clientId: 'YOUR_CLIENT_ID',
      environment: Environment.sandbox, // 使用沙盒环境进行测试
    );
  } catch (e) {
    print('PayPal initialization failed: $e');
  }
}

3. 创建支付订单

创建一个支付订单并启动 PayPal 支付流程。

void makePayment() async {
  try {
    final order = PaymentOrder(
      intent: 'sale',
      payer: Payer(paymentMethod: 'paypal'),
      transactions: [
        Transaction(
          amount: Amount(total: '10.00', currency: 'USD'),
          description: 'Test Payment',
        ),
      ],
    );

    final result = await PaypalMobileWeb.pay(order: order);

    if (result.status == PaymentStatus.completed) {
      print('Payment completed successfully');
    } else {
      print('Payment failed or was cancelled');
    }
  } catch (e) {
    print('Payment error: $e');
  }
}

4. 处理支付结果

makePayment 方法中,你可以根据 result.status 来处理支付结果。常见的状态包括:

  • PaymentStatus.completed: 支付成功。
  • PaymentStatus.cancelled: 用户取消了支付。
  • PaymentStatus.error: 支付过程中发生错误。

5. 在 UI 中触发支付

你可以在按钮的 onPressed 回调中调用 makePayment 方法来触发支付流程。

ElevatedButton(
  onPressed: makePayment,
  child: Text('Pay with PayPal'),
)
回到顶部