Flutter支付集成插件razorpay_flutter_31的使用

Flutter支付集成插件razorpay_flutter_31的使用

简介

Flutter插件用于Razorpay SDK。

pub package

开始使用

该Flutter插件是基于我们的Android和iOS SDK的包装器。

以下文档仅关注于我们原生Android和iOS SDK的包装。若想了解更多信息及如何在项目中链接它们,请参阅以下文档:

若要了解更多关于Razorpay支付流程及步骤,请参阅这里

前提条件

  • 学习Razorpay支付流程
  • 注册一个Razorpay账户,并在Razorpay仪表板中生成API密钥。使用测试密钥可以帮助模拟沙盒环境,在使用测试密钥时不会发生实际的资金交易。一旦你的应用经过充分测试并准备上线,可以使用生产密钥。

安装

该插件可以在Pub上找到:https://pub.dev/packages/razorpay_flutter

在你的app的pubspec.yaml文件中添加依赖项:

razorpay_flutter: ^1.2.3

注意(Android):确保你的app的最小API级别为19或更高。

ProGuard规则

如果你使用ProGuard构建,需要在ProGuard文件中添加以下行:

-keepattributes *Annotation*
-dontwarn com.razorpay.**
-keep class com.razorpay.** {*;}
-optimizations !method/inlining/
-keepclasseswithmembers class * {
  public void onPayment*(...);
}

详情请参见这里

注意(iOS):确保你的app的最小部署目标为iOS 10.0或更高版本,并且不要忘记启用Bitcode。

在app的根目录下运行flutter packages get

使用

示例代码可以在example/lib/main.dart中找到。

导入包
import 'package:razorpay_flutter/razorpay_flutter.dart';
创建Razorpay实例
_razorpay = Razorpay();
添加事件监听器

插件使用基于事件的通信方式,并在支付失败或成功时发出事件。

事件名称通过Razorpay类中的常量EVENT_PAYMENT_SUCCESSEVENT_PAYMENT_ERROREVENT_EXTERNAL_WALLET公开。

使用Razorpay实例上的on(String event, Function handler)方法来附加事件监听器。

_razorpay.on(Razorpay.EVENT_PAYMENT_SUCCESS, _handlePaymentSuccess);
_razorpay.on(Razorpay.EVENT_PAYMENT_ERROR, _handlePaymentError);
_razorpay.on(Razorpay.EVENT_EXTERNAL_WALLET, _handleExternalWallet);

处理器应该定义如下:

void _handlePaymentSuccess(PaymentSuccessResponse response) {
  // 支付成功时的操作
}

void _handlePaymentError(PaymentFailureResponse response) {
  // 支付失败时的操作
}

void _handleExternalWallet(ExternalWalletResponse response) {
  // 当选择外部钱包时的操作
}

要清除事件监听器,使用Razorpay实例上的clear方法。

_razorpay.clear(); // 移除所有监听器
设置选项
var options = {
  'key': '<YOUR_KEY_HERE>',
  'amount': 100,
  'name': 'Acme Corp.',
  'description': 'Fine T-Shirt',
  'prefill': {
    'contact': '8888888888',
    'email': 'test@razorpay.com'
  }
};

详细选项列表可以在这里找到。

打开支付界面
_razorpay.open(options);

故障排查

启用Bitcode

打开ios/Podfile并找到此部分:

post_install do |installer|
  installer.pods_project.targets.each do |target|
    target.build_configurations.each do |config|
      config.build_settings['ENABLE_BITCODE'] = 'NO'
    end
  end
end

设置config.build_settings['ENABLE_BITCODE'] = 'YES'

设置Swift版本

config.build_settings['ENABLE_BITCODE'] = 'YES'下方添加以下行:

config.build_settings['SWIFT_VERSION'] = '5.0'
CocoaPods找不到兼容版本

当运行pod install时出现错误:

Specs satisfying the `razorpay_flutter (from
    `.symlinks/plugins/razorpay_flutter/ios`)` dependency were found, but they
    required a higher minimum deployment target.

这是由于你的最低部署目标低于iOS 10.0。要更改此设置,请打开ios/Podfile并添加/取消注释顶部的这一行:

# platform :ios, '9.0'

将其更改为:

platform :ios, '10.0'

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

1 回复

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


当然,以下是如何在Flutter项目中集成并使用razorpay_flutter_31插件的示例代码。这个插件允许你集成Razorpay支付网关到你的Flutter应用中。

步骤 1: 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  razorpay_flutter_31: ^1.2.8  # 请检查最新版本号并替换

然后运行flutter pub get来获取依赖。

步骤 2: 配置Android

android/app/src/main/AndroidManifest.xml中添加以下权限和Activity声明:

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

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

    <application
        ...>
        
        <activity
            android:name="com.razorpay.CheckoutActivity"
            android:theme="@style/Theme.AppCompat.Light.NoActionBar"
            android:screenOrientation="portrait"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize"
            android:windowSoftInputMode="adjustResize" />

        <activity
            android:name="com.razorpay.PrePaymentActivity"
            android:theme="@style/Theme.AppCompat.Light.NoActionBar"
            android:screenOrientation="portrait"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize"
            android:windowSoftInputMode="adjustResize" />
            
        <!-- Add more activities if needed -->
        
    </application>

</manifest>

android/app/build.gradle文件中,确保你的minSdkVersion是16或更高:

android {
    compileSdkVersion 30

    defaultConfig {
        applicationId "com.example.yourapp"
        minSdkVersion 16
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"
    }
    ...
}

步骤 3: 配置iOS

ios/Runner/Info.plist中添加以下键:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

ios/Podfile中,确保你有使用最新的Cocoapods版本,并添加以下post_install脚本(如果需要):

post_install do |installer|
  installer.pods_project.targets.each do |target|
    flutter_additional_ios_build_settings(target)
    target.build_configurations.each do |config|
      config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] ||= [
        '$(inherited)',
        'RAZORPAY_VERSION=@"1.2.8"'  # 请检查最新版本号并替换
      ]
    end
  end
end

然后运行pod install在iOS目录下。

步骤 4: 初始化并使用Razorpay

在你的Flutter代码中,初始化并使用Razorpay进行支付:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Razorpay Integration'),
        ),
        body: Center(
          child: ElevatedButton(
            onPressed: _initRazorpay,
            child: Text('Pay Now'),
          ),
        ),
      ),
    );
  }

  Future<void> _initRazorpay() async {
    final Razorpay _razorpay = Razorpay();
    
    _razorpay.on(Razorpay.EVENT_PAYMENT_SUCCESS, (paymentId) {
      print("Payment Success: $paymentId");
    });

    _razorpay.on(Razorpay.EVENT_PAYMENT_ERROR, (code, message, description) {
      print("Payment Error: $code, $message, $description");
    });

    _razorpay.on(Razorpay.EVENT_EXTERNAL_WALLET, (walletName) {
      print("External Wallet: $walletName");
    });

    var options = {
      "key": "your_key_id_here", // Replace with your Razorpay Key ID
      "amount": "1000", // Amount in currency subunits. 1000 subunits = ₹10
      "currency": "INR",
      "name": "Merchant Name",
      "description": "Payment Description",
      "image": "https://example.com/your_logo.png",
      "prefill": {
        "email": "test@example.com",
        "contact": "9199999999",
      },
      "theme": {
        "color": "#F37254"
      }
    };

    try {
      _razorpay.open(options);
    } catch (e) {
      print(e);
    }
  }
}

请确保将"your_key_id_here"替换为你的Razorpay Key ID。

注意事项

  1. 安全性:不要在客户端代码中硬编码敏感信息,如API密钥。考虑使用环境变量或安全存储。
  2. 测试环境:在生产环境中使用前,请在Razorpay的测试环境中彻底测试你的集成。
  3. 错误处理:在生产代码中添加更多的错误处理和用户反馈。

这样,你就成功地在Flutter应用中集成了Razorpay支付插件。

回到顶部