Flutter支付集成插件paymongo_sdk的使用

发布于 1周前 作者 vueper 来自 Flutter

Flutter支付集成插件paymongo_sdk的使用

PayMongo SDK

PayMongo

Flutter package for paymongo

Flutter 的 PayMongo 包是独立的,以区分前端和后端 API 使用的端点。

创建账户

您可以在 [PayMongo 官方网站] 注册账户。

API Keys

在开发者设置中找到 Public KeySecret Key,复制这些密钥并在项目中使用。请注意,不要在前端使用 Secret Key。

支付方式支持情况

支付方式 文档状态 生产环境
GCash 🚧
Debit/Credit 🚧
PayMaya 🚧 🚧
Grab Pay 🚧

如果您对 SDK 有任何问题,请通过 GitHub 提交 issue。

使用示例

以下是完整的 Flutter 示例项目,展示了如何使用 paymongo_sdk 插件进行支付集成。

示例代码

main.dart

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

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: PaymentScreen(),
    );
  }
}

class PaymentScreen extends StatefulWidget {
  [@override](/user/override)
  _PaymentScreenState createState() => _PaymentScreenState();
}

class _PaymentScreenState extends State<PaymentScreen> {
  final List<Shoe> _shoes = List.generate(5, (index) {
    return Shoe(
      amount: 100 * (index + 1),
      currency: 'PHP',
      name: 'Shoe #$index',
      description: 'A smol shoe size of S-$index',
    );
  });

  final List<Shoe> _cart = [];

  double get _totalAmount => _cart.fold(0, (prev, curr) => prev + curr.amount);

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Tap to pay'),
      ),
      drawer: Drawer(
        child: ListView(
          children: [
            ListTile(
              title: Text("Payments"),
              onTap: () {
                Navigator.push(context, MaterialPageRoute(builder: (context) {
                  return PaymentOptionsScreen(cart: _cart);
                }));
              },
            ),
          ],
        ),
      ),
      body: LayoutBuilder(builder: (context, constraints) {
        return GridView.builder(
          itemCount: _shoes.length,
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 3,
          ),
          itemBuilder: (context, index) {
            final shoe = _shoes[index];
            return GestureDetector(
              onTap: () {
                setState(() {
                  if (!_cart.contains(shoe)) {
                    _cart.add(shoe);
                  }
                });
              },
              child: ShoeCard(shoe: shoe),
            );
          },
        );
      }),
      floatingActionButton: _totalAmount > 100
          ? FloatingActionButton.extended(
              onPressed: () async {
                await showModalBottomSheet(
                    context: context,
                    builder: (context) {
                      return PaymentOptionList(cart: _cart);
                    });
              },
              label: Text('Single Payment(${_cart.length})'),
              icon: const Icon(Icons.credit_card),
            )
          : null,
    );
  }
}

class Shoe {
  final int amount;
  final String currency;
  final String name;
  final String description;

  Shoe({
    required this.amount,
    required this.currency,
    required this.name,
    required this.description,
  });
}

class ShoeCard extends StatelessWidget {
  final Shoe shoe;

  ShoeCard({required this.shoe});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(shoe.name),
            Text('₱${shoe.amount}'),
            Text(shoe.description),
          ],
        ),
      ),
    );
  }
}

class PaymentOptionsScreen extends StatelessWidget {
  final List<Shoe> cart;

  PaymentOptionsScreen({required this.cart});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Payment Options'),
      ),
      body: PaymentOptionList(cart: cart),
    );
  }
}

class PaymentOptionList extends StatefulWidget {
  final List<Shoe> cart;

  PaymentOptionList({required this.cart});

  [@override](/user/override)
  _PaymentOptionListState createState() => _PaymentOptionListState();
}

class _PaymentOptionListState extends State<PaymentOptionList>
    with PaymongoEventHandler {
  final String apiKey = 'your_public_api_key'; // 替换为您的 Public Key

  Future<void> gcashPayment(List<Shoe> cart) async {
    final publicSDK = PaymongoClient<PaymongoPublic>(apiKey);
    final totalAmount = cart.fold(0, (prev, curr) => prev + curr.amount);

    final data = SourceAttributes(
      type: 'gcash',
      amount: totalAmount,
      currency: 'PHP',
      redirect: Redirect(
        success: "https://example.com/success",
        failed: "https://example.com/failed",
      ),
      billing: Billing(
        name: 'John Doe',
        email: 'john.doe@example.com',
        phone: '+639123456789',
      ),
    );

    final result = await publicSDK.instance.source.create(data);
    print('GCash Payment Result: $result');
  }

  Future<void> cardPayment(List<Shoe> cart) async {
    final publicSDK = PaymongoClient<PaymongoPublic>(apiKey);
    final totalAmount = cart.fold(0, (prev, curr) => prev + curr.amount);

    final data = SourceAttributes(
      type: 'card',
      amount: totalAmount,
      currency: 'PHP',
      redirect: Redirect(
        success: "https://example.com/success",
        failed: "https://example.com/failed",
      ),
      billing: Billing(
        name: 'John Doe',
        email: 'john.doe@example.com',
        phone: '+639123456789',
      ),
    );

    final result = await publicSDK.instance.source.create(data);
    print('Card Payment Result: $result');
  }

  Future<void> grabPayment(List<Shoe> cart) async {
    final publicSDK = PaymongoClient<PaymongoPublic>(apiKey);
    final totalAmount = cart.fold(0, (prev, curr) => prev + curr.amount);

    final data = SourceAttributes(
      type: 'grabpay',
      amount: totalAmount,
      currency: 'PHP',
      redirect: Redirect(
        success: "https://example.com/success",
        failed: "https://example.com/failed",
      ),
      billing: Billing(
        name: 'John Doe',
        email: 'john.doe@example.com',
        phone: '+639123456789',
      ),
    );

    final result = await publicSDK.instance.source.create(data);
    print('Grab Pay Payment Result: $result');
  }

  Future<void> paymayaPayment(List<Shoe> cart) async {
    final publicSDK = PaymongoClient<PaymongoPublic>(apiKey);
    final totalAmount = cart.fold(0, (prev, curr) => prev + curr.amount);

    final data = SourceAttributes(
      type: 'paymaya',
      amount: totalAmount,
      currency: 'PHP',
      redirect: Redirect(
        success: "https://example.com/success",
        failed: "https://example.com/failed",
      ),
      billing: Billing(
        name: 'John Doe',
        email: 'john.doe@example.com',
        phone: '+639123456789',
      ),
    );

    final result = await publicSDK.instance.source.create(data);
    print('PayMaya Payment Result: $result');
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Column(
        children: [
          ListTile(
            title: Text("GCash Payment"),
            onTap: () async {
              await gcashPayment(widget.cart);
            },
          ),
          ListTile(
            title: Text("Credit/Debit Payment"),
            onTap: () async {
              await cardPayment(widget.cart);
            },
          ),
          ListTile(
            title: Text('Grab Pay'),
            onTap: () async {
              await grabPayment(widget.cart);
            },
          ),
          ListTile(
            title: Text("PayMaya Payment"),
            onTap: () async {
              await paymayaPayment(widget.cart);
            },
          ),
        ],
      ),
    );
  }
}

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

1 回复

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


当然,以下是一个关于如何在Flutter项目中集成并使用paymongo_sdk插件进行支付的示例代码。这个示例将涵盖基本的支付流程,包括初始化Paymongo客户端、创建支付意图以及处理支付结果。

首先,确保你的Flutter项目已经设置好,并且已经添加了paymongo_sdk依赖。你可以在pubspec.yaml文件中添加以下依赖:

dependencies:
  flutter:
    sdk: flutter
  paymongo_sdk: ^最新版本号  # 请替换为实际的最新版本号

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

接下来,在你的Flutter应用中,你可以按照以下步骤进行支付集成:

  1. 初始化Paymongo客户端

在你的主文件(通常是main.dart)或者你需要进行支付操作的Dart文件中,首先导入paymongo_sdk包,并初始化Paymongo客户端。

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Paymongo SDK Demo'),
        ),
        body: PaymongoDemo(),
      ),
    );
  }
}

class PaymongoDemo extends StatefulWidget {
  @override
  _PaymongoDemoState createState() => _PaymongoDemoState();
}

class _PaymongoDemoState extends State<PaymongoDemo> {
  late PaymongoClient paymongoClient;

  @override
  void initState() {
    super.initState();
    // 替换为你的Paymongo公钥
    String publicKey = 'your_paymongo_public_key';
    paymongoClient = PaymongoClient(publicKey: publicKey);
  }

  // ... 其他代码,如支付按钮和处理函数
}
  1. 创建支付意图

在支付流程中,你通常需要先在服务器端创建一个支付意图(Payment Intent),然后将意图ID传递给前端。为了简化示例,这里假设你已经在服务器端创建了支付意图,并且已经获取到了意图ID。

  1. 启动支付流程

在你的UI中添加一个按钮来启动支付流程,并在按钮点击事件中调用Paymongo的支付函数。

class _PaymongoDemoState extends State<PaymongoDemo> {
  late PaymongoClient paymongoClient;
  String? paymentIntentId = 'your_payment_intent_id';  // 替换为实际的支付意图ID

  @override
  void initState() {
    super.initState();
    String publicKey = 'your_paymongo_public_key';
    paymongoClient = PaymongoClient(publicKey: publicKey);
  }

  void startPayment() async {
    try {
      // 创建支付配置
      final paymentConfiguration = PaymentConfiguration(
        paymentIntentId: paymentIntentId!,
        amount: 1000,  // 金额,单位是分(例如1000表示10.00美元)
        currencyCode: 'usd',  // 货币代码
        successUrl: Uri.parse('https://your-success-url.com'),
        cancelUrl: Uri.parse('https://your-cancel-url.com'),
      );

      // 启动支付流程
      final result = await paymongoClient.startPayment(context, paymentConfiguration);

      if (result.status == PaymentStatus.completed) {
        // 支付成功处理
        print('Payment completed!');
      } else if (result.status == PaymentStatus.failed) {
        // 支付失败处理
        print('Payment failed: ${result.errorMessage}');
      } else if (result.status == PaymentStatus.canceled) {
        // 支付取消处理
        print('Payment canceled');
      }
    } catch (e) {
      // 错误处理
      print('Error: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: ElevatedButton(
        onPressed: startPayment,
        child: Text('Start Payment'),
      ),
    );
  }
}

注意:

  • 在实际应用中,支付意图ID(paymentIntentId)通常是从你的服务器获取的,而不是硬编码在客户端代码中。
  • amount字段的值需要根据你的业务逻辑进行设置,这里假设使用的是美元(USD),并且金额单位是“分”。
  • successUrlcancelUrl是用户在支付完成后被重定向到的URL,你应该替换为你自己的URL。

这个示例代码展示了如何在Flutter应用中使用paymongo_sdk插件进行支付集成。根据你的实际需求,你可能需要对代码进行一些调整,比如处理更多的支付状态、添加更多的错误处理等。

回到顶部