Flutter支付处理插件moyasar的使用

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

Flutter支付处理插件Moyasar的使用

Moyasar Flutter SDK

Easily accept payments through Apple Pay or Credit Card (with managed 3DS step) in your Flutter app with Moyasar.

Moyasar Flutter SDK Demo

Features

  • Apple Pay: Quickly and safely accept Apple Pay payments.
  • Credit Card: Easily accept many card companies while not worrying about managing the required 3DS step.

Getting Started

Prerequisites

Accepting Apple Pay Payments in iOS

Complete the following steps to easily accept Apple Pay payments:

  • Follow this guide to setup your Apple developer account and integrate it with Moyasar.
  • Follow this guide to enable accepting Apple Pay in your application using xCode.

Accepting Payments in Android

Due to depending on the pay package, make sure to set the correct minSdkVersion in android/app/build.gradle if it was previously lower than 21:

android {
    defaultConfig {
        minSdkVersion 21
    }
}

Installation

flutter pub add moyasar

Usage

Moyasar Widgets

Here’s a complete example of how to use the Moyasar widgets for both Apple Pay and Credit Card payments.

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

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

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

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      debugShowCheckedModeBanner: false,
      home: CoffeeShop(),
    );
  }
}

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

  @override
  State<CoffeeShop> createState() => _CoffeeShopState();
}

class _CoffeeShopState extends State<CoffeeShop> {
  final paymentConfig = PaymentConfig(
      publishableApiKey: 'YOUR_API_KEY',
      amount: 100, // SAR 1
      description: 'order #1324',
      metadata: {'size': '250g', 'code': 255},
      creditCard: CreditCardConfig(saveCard: false, manual: false),
      applePay: ApplePayConfig(
          merchantId: 'YOUR_MERCHANT_ID',
          label: 'YOUR_STORE_NAME',
          manual: false));

  void onPaymentResult(result) {
    if (result is PaymentResponse) {
      showToast(context, result.status.name);
      switch (result.status) {
        case PaymentStatus.paid:
          // handle success.
          break;
        case PaymentStatus.failed:
          // handle failure.
          break;
        case PaymentStatus.authorized:
          // handle authorized.
          break;
        default:
      }
      return;
    }

    // handle failures.
    if (result is ApiError) {}
    if (result is AuthError) {}
    if (result is ValidationError) {}
    if (result is PaymentCanceledError) {}
    if (result is UnprocessableTokenError) {}
    if (result is TimeoutError) {}
    if (result is NetworkError) {}
    if (result is UnspecifiedError) {}
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colors.white,
        resizeToAvoidBottomInset: true,
        body: Center(
          child: SizedBox(
            width: MediaQuery.of(context).size.width * 0.9,
            child: ListView(
              children: [
                PaymentMethods(
                  paymentConfig: paymentConfig,
                  onPaymentResult: onPaymentResult,
                ),
              ],
            ),
          ),
        ));
  }
}

void showToast(context, status) {
  ScaffoldMessenger.of(context).showSnackBar(SnackBar(
    content: Text(
      "Status: $status",
      style: const TextStyle(fontSize: 20),
    ),
  ));
}

class PaymentMethods extends StatelessWidget {
  final PaymentConfig paymentConfig;
  final Function onPaymentResult;

  PaymentMethods({
    super.key,
    required this.paymentConfig,
    required this.onPaymentResult,
  });

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        ApplePay(
          config: paymentConfig,
          onPaymentResult: onPaymentResult,
        ),
        const Text("or"),
        CreditCard(
          config: paymentConfig,
          onPaymentResult: onPaymentResult,
        )
      ],
    );
  }
}

Custom Widgets

If you want to create custom widgets for handling payments, here’s an example:

// Unified config for Moyasar API
final paymentConfig = PaymentConfig(
  publishableApiKey: 'YOUR_API_KEY',
  amount: 25758, // SAR 257.58
  description: 'order #1324',
  metadata: {'size': '250g'},
  creditCard: CreditCardConfig(saveCard: true, manual: false),
  applePay: ApplePayConfig(
      merchantId: 'YOUR_MERCHANT_ID',
      label: 'YOUR_STORE_NAME',
      manual: false),
);

// Callback once the user clicks on the custom Apple Pay widget
void onSubmitApplePay(applePay) async {
  final source = ApplePayPaymentRequestSource(
      applePay['token'], (paymentConfig.applePay as ApplePayConfig).manual);
  final paymentRequest = PaymentRequest(paymentConfig, source);

  final result = await Moyasar.pay(
      apiKey: paymentConfig.publishableApiKey,
      paymentRequest: paymentRequest);

  onPaymentResult(result);
}

// Callback once the user fills & submit their CC information using the custom form widget
void onSubmitCcForm() async {
  final source = CardPaymentRequestSource(
      creditCardData: CardFormModel(
          name: 'John Doe',
          number: '4111111111111111',
          month: '05',
          year: '2025'),
      tokenizeCard: (paymentConfig.creditCard as CreditCardConfig).saveCard,
      manualPayment: (paymentConfig.creditCard as CreditCardConfig).manual);

  final paymentRequest = PaymentRequest(paymentConfig, source);

  final result = await Moyasar.pay(
      apiKey: paymentConfig.publishableApiKey,
      paymentRequest: paymentRequest);

  onPaymentResult(result);
}

// Unified payment result processor
void onPaymentResult(result) {
  if (result is PaymentResponse) {
    switch (result.status) {
      case PaymentStatus.initiated:
        // handle 3DS redirection.
        break;
      case PaymentStatus.paid:
        // handle success.
        break;
      case PaymentStatus.failed:
        // handle failure.
        break;
    }
  }
}

Testing

Credit Cards

Moyasar provides a sandbox environment for testing credit card payments without charging any real money. This allows you to test your integration and ensure that everything is working correctly before going live with actual payments. Learn more about our testing cards here.

Apple Pay

Testing using a simulator will not work! Learn more about Apple Pay testing here.

Migration Guide

From 1.0 to 2.0

This upgrade changes how Apple Pay is configured. Do the following changes to complete the upgrade:

  • Delete the default_payment_profile_apple_pay.json file under your assets file.
  • Update the paymentConfig instance to include the new applePay configuration.
final paymentConfig = PaymentConfig(
    publishableApiKey: 'YOUR_API_KEY',
    amount: 25758, // SAR 257.58
    description: 'order #1324',
    metadata: {'size': '250g'},
+   applePay: ApplePayConfig(merchantId: 'YOUR_MERCHANT_ID', label: 'YOUR_STORE_NAME'),
);

By following these steps, you can effectively integrate Moyasar into your Flutter application for secure and easy payment processing.


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

1 回复

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


当然,以下是一个关于如何在Flutter应用中使用Moyasar支付处理插件的示例代码。请注意,实际项目中你需要替换示例中的API密钥和支付参数。

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

dependencies:
  flutter:
    sdk: flutter
  moyasar_flutter: ^latest_version  # 请替换为最新的版本号

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

接下来,你需要配置Moyasar的API密钥。通常,这会在你的应用启动时完成。以下是一个示例:

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

void main() {
  // 配置Moyasar API密钥
  Moyasar.configure(apiKey: 'your_api_key_here'); // 请替换为你的API密钥

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Moyasar Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

接下来,在你的MyHomePage类中,你可以添加支付功能。下面是一个简单的示例,展示如何创建一个支付请求并处理支付结果:

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

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final _formKey = GlobalKey<FormState>();
  String? _description;
  String? _amount;
  String? _currency;
  String? _sourceId;

  void _submit() async {
    if (_formKey.currentState!.validate()) {
      _formKey.currentState!.save();

      try {
        // 创建支付请求
        var paymentResponse = await Moyasar.createPayment(
          description: _description!,
          amount: int.parse(_amount!),
          currency: _currency!,
          sourceId: _sourceId!,
        );

        // 处理支付响应
        if (paymentResponse.status == 'paid') {
          showDialog(
            context: context,
            builder: (context) => AlertDialog(
              title: Text('支付成功'),
              content: Text('支付ID: ${paymentResponse.id}'),
              actions: <Widget>[
                TextButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                  child: Text('确定'),
                ),
              ],
            ),
          );
        } else {
          showDialog(
            context: context,
            builder: (context) => AlertDialog(
              title: Text('支付失败'),
              content: Text('支付状态: ${paymentResponse.status}'),
              actions: <Widget>[
                TextButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                  child: Text('确定'),
                ),
              ],
            ),
          );
        }
      } catch (e) {
        print('支付请求失败: $e');
        showDialog(
          context: context,
          builder: (context) => AlertDialog(
            title: Text('错误'),
            content: Text('请求失败: $e'),
            actions: <Widget>[
              TextButton(
                onPressed: () {
                  Navigator.of(context).pop();
                },
                child: Text('确定'),
              ),
            ],
          ),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Moyasar支付示例'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Form(
          key: _formKey,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              TextFormField(
                decoration: InputDecoration(labelText: '描述'),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入描述';
                  }
                  return null;
                },
                onSaved: (value) {
                  _description = value;
                },
              ),
              TextFormField(
                decoration: InputDecoration(labelText: '金额'),
                keyboardType: TextInputType.number,
                validator: (value) {
                  if (value == null || value.isEmpty || !int.tryParse(value!)!.isValidInt()) {
                    return '请输入有效的金额';
                  }
                  return null;
                },
                onSaved: (value) {
                  _amount = value;
                },
              ),
              TextFormField(
                decoration: InputDecoration(labelText: '货币'),
                validator: (value) {
                  if (value == null || value.isEmpty || !['USD', 'SAR'].contains(value!)) {
                    return '请输入有效的货币(USD 或 SAR)';
                  }
                  return null;
                },
                onSaved: (value) {
                  _currency = value;
                },
              ),
              TextFormField(
                decoration: InputDecoration(labelText: 'Source ID'),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入Source ID';
                  }
                  return null;
                },
                onSaved: (value) {
                  _sourceId = value;
                },
              ),
              SizedBox(height: 20),
              ElevatedButton(
                onPressed: _submit,
                child: Text('支付'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

在这个示例中,我们创建了一个简单的Flutter表单,用户可以输入支付描述、金额、货币和Source ID。当用户点击“支付”按钮时,应用会使用Moyasar插件创建一个支付请求,并根据支付响应显示相应的对话框。

请确保你已经正确设置了Moyasar账户,并且已经生成了有效的API密钥和Source ID。同时,你可能需要根据实际需求调整支付参数和UI设计。

回到顶部