Flutter集成HyperSDK插件hypersdkflutter的使用

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

Flutter集成HyperSDK插件hypersdkflutter的使用

Hyper SDK Flutter

Flutter插件用于通过不同的动态模块实现支付编排。

Flutter Setup

pubspec.yaml中添加Flutter插件依赖项。从pub.dev获取依赖项。

dependencies:
  hypersdkflutter: ^latest_version

Android Setup

在根(顶层)build.gradle中添加clientId ext属性:

  • 可选:通过添加hyperSDKVersion覆盖HyperSDK版本。
  • 可选:通过添加excludedMicroSDKs排除与给定clientId一起提供的microSDK。
buildscript {
    ext {
        clientId = "<clientId shared by Juspay team>"
        hyperSDKVersion = "2.1.32"
        excludedMicroSDKs = []
    }
}

注意: 您的应用程序的MainActivity应该扩展FlutterFragmentActivity而不是FlutterActivity

import io.flutter.embedding.android.FlutterFragmentActivity

class MainActivity: FlutterFragmentActivity() {}

iOS Setup

在Podfile(ios/Podfile)中添加以下post_install脚本:

post_install do |installer|
  fuse_path = "./Pods/HyperSDK/Fuse.rb"
  clean_assets = true
  if File.exist?(fuse_path)
    if system("ruby", fuse_path.to_s, clean_assets.to_s)
    end
  end
end

创建文件ios/MerchantConfig.txt,内容如下:

clientId = <clientId> shared by Juspay Team

可选:如果您想覆盖插件中的基础SDK版本,请在项目的pubspec.yaml中添加以下变量:

hyper_sdk_ios_version: "<New version>"

Usage

Import HyperSDK

import 'package:hypersdk/hypersdkflutter.dart';

Step-1: Create Juspay Object

final hyperSDK = HyperSDK();

Step-2: Initiate

await hyperSDK.initiate(initiatePayload, initiateCallbackHandler);

Step-3: Process

await hyperSDK.process(processPayload, hyperSDKCallbackHandler);

Step-3.1: Process via Container

Container(
  color: Colors.white,
  child: hyperSDK.hyperSdkView(processPayload, hyperSDKCallbackHandler),
)

Step-4: Android Hardware Back-Press Handling

onWillPop: () async {
  if (Platform.isAndroid) {
    var backpressResult = await hyperSDK.onBackPress();
    if (backpressResult.toLowerCase() == "true") {
      return false;
    } else {
      return true;
    }
  } else {
    return true;
  }
}

Step-5: Terminate

await hyperSDK.terminate();

Optional: Is Initialised

await hyperSDK.isInitialised();

Callbacks

Initiate callback handler

void initiateCallbackHandler(MethodCall methodCall) {
  if (methodCall.method == "initiate_result") {
    // check initiate result
  }
}

Process callback handler

void hyperSDKCallbackHandler(MethodCall methodCall) {
  switch (methodCall.method) {
    case "hide_loader":
      break;
    case "process_result":
      var args = {};
      try {
        args = json.decode(methodCall.arguments);
      } catch (e) {
        print(e);
      }
      var error = args["error"] ?? false;
      var innerPayload = args["payload"] ?? {};
      var status = innerPayload["status"] ?? " ";
      var pi = innerPayload["paymentInstrument"] ?? " ";
      var pig = innerPayload["paymentInstrumentGroup"] ?? " ";

      if (!error) {
        switch (status) {
          case "charged":
            // Successful Transaction
            break;
          case "cod_initiated":
            // User opted for cash on delivery option displayed on payment page
            break;
        }
      } else {
        var errorCode = args["errorCode"] ?? " ";
        var errorMessage = args["errorMessage"] ?? " ";
        switch (status) {
          case "backpressed":
            // user back-pressed from PP without initiating any txn
            break;
          case "user_aborted":
            // user initiated a txn and pressed back
            break;
          case "pending_vbv":
            break;
          case "authorizing":
            // txn in pending state
            break;
          case "authorization_failed":
            break;
          case "authentication_failed":
            break;
          case "api_failure":
            // txn failed
            break;
          case "new":
            // order created but txn failed
            break;
        }
      }
  }
}

WebView Configuration Callback (Optional)

Android

HyperSdkFlutterPlugin.webViewConfigurationCallback =
    JuspayWebViewConfigurationCallback { webview ->
        // Configure WebView here
    }

iOS

SwiftHyperSdkFlutterPlugin.setJuspayWebViewConfigurationCallback { webView in
    // Configure WebView here
}

Payload Structure

Payload类型为Map<String, Dynamic>。有关详细信息,请参阅官方文档。

License

hypersdkflutter分发在AGPL-3.0-only许可证下。

示例代码

import 'package:flutter/material.dart';
import 'dart:io';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:hypersdkflutter/hypersdkflutter.dart';
import 'package:flutter/services.dart';
import './screens/home.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  if (Platform.isAndroid) {
    await InAppWebViewController.setWebContentsDebuggingEnabled(true);
  }
  final hyperSDK = HyperSDK();
  runApp(MyApp(hyperSDK: hyperSDK));
}

class MyApp extends StatelessWidget {
  final HyperSDK hyperSDK;
  const MyApp({Key? key, required this.hyperSDK}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, overlays: [SystemUiOverlay.bottom]);
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: HomeScreen(
        hyperSDK: hyperSDK,
      ),
    );
  }
}

以上是关于如何在Flutter项目中集成和使用HyperSDK插件hypersdkflutter的详细说明。希望对您有所帮助!


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

1 回复

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


在Flutter项目中集成并使用hypersdkflutter插件通常涉及以下几个步骤:添加依赖、配置原生项目、初始化SDK以及调用SDK提供的功能。以下是一个基本的集成和使用示例。

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  hypersdkflutter: ^最新版本号  # 替换为实际可用的最新版本号

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

2. 配置原生项目

根据hypersdkflutter的官方文档,你可能需要在ios/Podfileandroid/build.gradle文件中进行一些配置。这些配置通常涉及SDK的版本和权限设置。由于具体配置可能随SDK版本变化,请参考最新的官方文档或插件的README文件。

3. 初始化SDK

在你的Flutter应用中,你需要在适当的时机初始化hypersdkflutter插件。通常,这可以在MainActivity.kt(Android)或AppDelegate.swift(iOS)中进行,但更常见的做法是在Flutter的Dart代码中完成。

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('HyperSDK Flutter Example'),
        ),
        body: Center(
          child: HyperSDKExample(),
        ),
      ),
    );
  }
}

class HyperSDKExample extends StatefulWidget {
  @override
  _HyperSDKExampleState createState() => _HyperSDKExampleState();
}

class _HyperSDKExampleState extends State<HyperSDKExample> {
  String sdkStatus = "Not Initialized";

  @override
  void initState() {
    super.initState();
    _initializeSDK();
  }

  Future<void> _initializeSDK() async {
    try {
      // 假设这里需要一些配置参数,如API Key等
      // 替换为实际的初始化代码
      await HypersdkFlutter.instance.initialize(apiKey: "your_api_key");
      setState(() {
        sdkStatus = "Initialized";
      });
    } catch (e) {
      print("Failed to initialize SDK: $e");
      setState(() {
        sdkStatus = "Failed to Initialize";
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Text("SDK Status: $sdkStatus"),
        // 其他UI组件,如按钮来调用SDK的其他功能
      ],
    );
  }
}

4. 调用SDK功能

一旦SDK初始化成功,你就可以调用SDK提供的各种功能了。例如,假设hypersdkflutter插件提供了一个支付功能,你可以这样调用:

void _makePayment() async {
  try {
    // 假设这是一个支付请求的配置
    var paymentRequest = {
      "amount": "100.00",
      "currency": "USD",
      // 其他必要的支付参数
    };

    var result = await HypersdkFlutter.instance.makePayment(paymentRequest);
    print("Payment Result: $result");
  } catch (e) {
    print("Payment failed: $e");
  }
}

你可以在UI中添加一个按钮来触发这个函数:

// 在_HyperSDKExampleState的build方法中添加
ElevatedButton(
  onPressed: _makePayment,
  child: Text("Make Payment"),
),

注意

  • 上面的代码是一个简化的示例,实际使用中你可能需要处理更多的错误情况和配置参数。
  • 请务必参考hypersdkflutter插件的官方文档和示例代码,因为SDK的具体API和初始化步骤可能会随版本更新而变化。
  • 确保你的Flutter环境和依赖都是最新的,以避免潜在的兼容性问题。
回到顶部