Flutter支付集成插件adyen_drop_in_plugin的使用

Flutter支付集成插件adyen_drop_in_plugin的使用

注意:此库并非官方来自Adyen。

这是一个Flutter插件,用于与Adyen的Android和iOS库进行集成。此库允许您仅通过调用一个函数来打开Adyen的Drop-in方法。

该插件支持3dSecure v2和一次性支付。它未在循环支付场景中进行测试。

前提条件

凭证

您需要以下信息:

  • publicKey(来自Adyen)
  • clientKey(来自Adyen)
  • 金额与货币
  • 用户参考(例如userId)
  • 后端的基础URL
  • Adyen环境(测试、LIVE_EU等)
  • 语言(de_DE、en_US等)
  • 支付后返回URL(iOS应用的URL Scheme),以便重定向回应用程序
支付方式

在调用插件之前,请确保从您的后端获取支付方式。为此,调用 /paymentMethods 端点:

一个支付方式响应示例如下:

{
    "groups": [
        {
            "name": "Credit Card",
            "types": [
                "amex",
                "mc",
                "visa"
            ]
        }
    ],
    "paymentMethods": [
        {
            "brands": [
                "amex",
                "mc",
                "visa"
            ],
            "details": [
                {
                    "key": "encryptedCardNumber",
                    "type": "cardToken"
                },
                {
                    "key": "encryptedSecurityCode",
                    "type": "cardToken"
                },
                {
                    "key": "encryptedExpiryMonth",
                    "type": "cardToken"
                },
                {
                    "key": "encryptedExpiryYear",
                    "type": "cardToken"
                },
                {
                    "key": "holderName",
                    "optional": true,
                    "type": "text"
                }
            ],
            "name": "Credit Card",
            "type": "scheme"
        },
        {
            "name": "PayPal",
            "supportsRecurring": true,
            "type": "paypal"
        }
    ]
}

应用程序使用这些端点进行支付提交和支付详情调用:

<your base url>/payment
<your base url>/payment/details

插件将把数据包装在一个对象中,并发送给支付提交调用,如下所示:

{
  payment: <所有需要发送给Adyen的支付数据>,
  additionalData: {key: value}
}

// additionalData 可以用于向您的后端发送附加数据

设置

Android

在AndroidManifest.xml中的application标签内添加此服务,这允许Adyen通知Android应用程序支付结果。

<application ...>
    ...
    <service
        android:name="app.adyen.flutter_adyen.AdyenDropinService"
        android:permission="android.permission.BIND_JOB_SERVICE"/>
</application>
Proguard

您需要将以下内容添加到您的Proguard规则中:

-keep class com.adyen.** { *; }
-keep class app.adyen.flutter_adyen.**  { *; }
iOS

如果您还没有URL Scheme,请添加一个。

如何添加一个URL Scheme

Flutter实现

要开始支付,您需要像这样调用插件:

try {
  String dropInResponse = await FlutterAdyen.openDropIn(
      paymentMethods: paymentMethods,  // 您的支付方式调用的结果
      baseUrl: 'https://your-server.com/',
      clientKey: <ADYEN_CLIENT_KEY>,
      amount: '1000', // 金额(以分为单位)
      lineItem: {'id': '您的产品ID', 'description': '您的产品描述'},
      additionalData: {
        'someKey': 'Some String'
      },
      shopperReference: <YouShopperReference>,
      returnUrl: 'yourAppScheme://payment', // iOS需要
      environment: 'TEST',  // 生产环境:liveUnitedStates, liveAustralia 或 liveEurope
      locale: 'de_DE', // 您首选的语言
      publicKey: <您的Adyen公钥>,
      currency: 'EUR');  // 您首选的货币

} on PlatformException {
  // 网络错误或其他系统错误
  return PaymentResponse.paymentError.rawValue;
}
// dropin返回以下字符串形式的响应
PAYMENT_CANCELLED
PAYMENT_ERROR
Authorised
Refused
Pending
Cancelled
Error
Received

示例代码

import 'dart:convert';
import 'dart:io';

import 'package:adyen_drop_in_plugin/adyen_drop_in_plugin.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import 'mock_data.dart';

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

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

class _MyAppState extends State<MyApp> {
  String? _payment_result = 'Unknown';

  String? dropInResponse;

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        floatingActionButton: FloatingActionButton(
          child: Icon(Icons.add),
          onPressed: () async {
            try {
              final List<Map<String, String>> items = [];
              items.add({'id': '1', 'quantity': '1', 'description': 'ABC'});

              dropInResponse = await AdyenDropInPlugin.openDropIn(
                  paymentMethods: jsonEncode(examplePaymentMethods2),
                  baseUrl: 'https://f1d234e5783a85cd-Venchi-checkout-live.adyenpayments.com/checkout/v69/',
                  clientKey: 'live_25TYODACSVHW7JLKJ5FREHSE74P6GDKM',
                  accessToken: 'LSv5pFnLN4Wux3lR0r5Azy2e0Rd7aHVzD6tM4uXORz',
                  publicKey: 'AQEohmfxK4vJaBBCw0m/n3Q5qf3Vfo5DDptDCqtk0lCY6hEQzvnXBQFHsBDBXVsNvuR83LVYjEgiTGAH-ZrgOm8DKCodiAKIpW3joQzWSpNyp6+wdK2ePmr7ggxI=-Ce@RxxeB@>q34{SR',
                  locale: 'HK',
                  shopperReference: 'asdasda',
                  returnUrl: 'appscheme://payment',
                  amount: '1500',
                  lineItem: items,
                  currency: 'HKD',
                  merchantAccount: 'Venchi_HK_app',
                  reference: '${Platform.isIOS ? 'ios' : 'android'}-components_${DateTime.now().millisecondsSinceEpoch}',
                  threeDS2RequestData: {
                    "deviceChannel": "app",
                    "challengeIndicator": "requestChallenge"
                  },
                  additionalData: {"allow3DS2": "true", "executeThreeD": "false"},
                  storePaymentMethod: true,
                  appleMerchantID: 'merchant.hk.com.venchi.crm',
                  environment: "EUROPE"
              );
            } on PlatformException catch (e) {
              if (e.code == 'PAYMENT_CANCELLED')
                dropInResponse = 'Payment Cancelled';
              else
                dropInResponse = 'Payment Error';
            }

            setState(() {
              _payment_result = dropInResponse;
            });
          },
        ),
        appBar: AppBar(
          title: const Text('Flutter Adyen'),
        ),
        body: Center(
          child: Text('Payment Result: $_payment_result\n'),
        ),
      ),
    );
  }
}

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

1 回复

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


adyen_drop_in_plugin 是一个 Flutter 插件,用于集成 Adyen 的支付解决方案。通过这个插件,你可以在 Flutter 应用中快速集成 Adyen 的 Drop-in 支付界面,支持多种支付方式。

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  adyen_drop_in_plugin: ^latest_version

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

2. 初始化插件

在你的 Flutter 应用中,首先需要初始化 adyen_drop_in_plugin 插件。通常,你可以在 main.dart 文件中进行初始化:

import 'package:adyen_drop_in_plugin/adyen_drop_in_plugin.dart';

void main() {
  AdyenDropInPlugin.initialize();
  runApp(MyApp());
}

3. 配置支付参数

在使用 Adyen Drop-in 界面之前,你需要配置支付参数。这些参数通常包括支付金额、货币、支付方式等。

final paymentParams = {
  'amount': {
    'value': 1000, // 支付金额(单位:分)
    'currency': 'USD', // 货币代码
  },
  'reference': 'your_order_reference', // 订单参考号
  'returnUrl': 'your_return_url', // 支付完成后的返回URL
  'countryCode': 'US', // 国家代码
  'shopperLocale': 'en_US', // 用户语言和地区
  'shopperEmail': 'user@example.com', // 用户邮箱
  'shopperReference': 'user_reference', // 用户参考号
};

4. 启动 Drop-in 支付界面

使用 AdyenDropInPlugin 启动 Drop-in 支付界面,并处理支付结果。

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

class PaymentScreen extends StatelessWidget {
  Future<void> startPayment() async {
    final paymentParams = {
      'amount': {
        'value': 1000,
        'currency': 'USD',
      },
      'reference': 'your_order_reference',
      'returnUrl': 'your_return_url',
      'countryCode': 'US',
      'shopperLocale': 'en_US',
      'shopperEmail': 'user@example.com',
      'shopperReference': 'user_reference',
    };

    try {
      final result = await AdyenDropInPlugin.startPayment(paymentParams);
      if (result['isSuccess'] == true) {
        // 支付成功
        print('Payment successful: ${result['result']}');
      } else {
        // 支付失败
        print('Payment failed: ${result['result']}');
      }
    } catch (e) {
      // 处理异常
      print('Payment error: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Adyen Payment'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: startPayment,
          child: Text('Pay Now'),
        ),
      ),
    );
  }
}

5. 处理支付结果

AdyenDropInPlugin.startPayment 方法返回一个包含支付结果的 Map。你可以根据 isSuccess 字段来判断支付是否成功,并根据 result 字段获取详细的支付信息。

6. 配置 Android 和 iOS

Android

android/app/src/main/AndroidManifest.xml 文件中,确保你有以下配置:

<application
    android:label="YourAppName"
    android:usesCleartextTraffic="true">
    <activity
        android:name=".MainActivity"
        android:launchMode="singleTop"
        android:theme="@style/LaunchTheme"
        android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|screenLayout|density|uiMode"
        android:hardwareAccelerated="true"
        android:windowSoftInputMode="adjustResize">
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>
            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
    </activity>
</application>

iOS

ios/Runner/Info.plist 文件中,确保你有以下配置:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>
回到顶部