flutter - 编写 阿里云-金融级实名认证插件

项目中有实名认证的需求,用户上传身份证反正面,进行人脸核验,后台集成的是阿里云的金融级实名认证SDK,巧合的是阿里云没有packages 需要自己造轮子。
废话不多少,直接上代码:

新建项目 ProjectType = Plugin

创建完成后,会自动为我们搭建好通信结构

编写Dart中间件

在项目下的 lib下的dart文件中定义我们的通信方法。
实名认证 需要两个方法 分别是:
获取本机信息发送给服务器 返回ID
调用实名认证,以及返回结果

import 'dart:async';

import 'package:flutter/services.dart';

class AliAuthPerson {
  static const MethodChannel _channel = MethodChannel('ali_auth_person');

  static Future<String?> get platformVersion async {
    final String? version = await _channel.invokeMethod('getPlatformVersion');
    return version;
  }

  static const EventChannel _eventChannel =
      EventChannel("ali_auth_person_plugin_event");

  ///认证结果返回监听
  static addListen(Function(String resData) onEvent) {
    _eventChannel.receiveBroadcastStream().listen((data) {
      onEvent(data);
    });
  }

  ///实名认证
  static Future<void> verify(String certifyId) async {
    await _channel.invokeMethod("verify", certifyId);
  }

  ///获取本机参数
  static Future<String> getMetaInfos() async {
    return await _channel.invokeMethod("getMetaInfos");
  }
}

Andriod 集成

参考:阿里云官方解说:https://help.aliyun.com/document_detail/163105.html

复制粘贴 AAR文件

将SDK的中的 AAR放入项目内


image.png

导入声明

dependencies {
    compileOnly files("$flutterRoot/bin/cache/artifacts/engine/android-arm/flutter.jar")
    //阿里云实人认证SDK
    implementation(name:'android-aliyunbasicstl-sdk-release-1.6.0-20220414192835', ext:'aar')
    implementation(name:'android-aliyuncomm-sdk-release-1.6.0-20220414192835', ext:'aar')
    implementation(name:'Android-AliyunDevice-FG-10022.2', ext:'aar')
    implementation(name:'android-aliyunface-sdk-release-1.6.0-20220414192835', ext:'aar')
    implementation(name:'android-aliyunocr-sdk-release-1.6.0-20220414192835', ext:'aar')
    implementation(name:'APSecuritySDK-DeepSec-7.0.1.20211220', ext:'aar')
    implementation(name:'photinus-1.0.1.220217162928', ext:'aar')
    implementation(name:'tygerservice-1.0.0.220407164130', ext:'aar')

    //三方依赖库
    implementation 'com.squareup.okhttp3:okhttp:3.11.0'
    implementation 'com.squareup.okio:okio:1.14.0'
    implementation 'com.alibaba:fastjson:1.2.62'
    implementation 'com.aliyun.dpa:oss-android-sdk:+'
}

编写Android 适配方法

代码如下

package com.lrs.ali_auth_person.ali_auth_person;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.aliyun.aliyunface.api.ZIMCallback;
import com.aliyun.aliyunface.api.ZIMFacade;
import com.aliyun.aliyunface.api.ZIMFacadeBuilder;
import com.aliyun.aliyunface.api.ZIMResponse;

import org.json.JSONException;
import org.json.JSONObject;

import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.embedding.engine.plugins.activity.ActivityAware;
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
import io.flutter.plugin.common.EventChannel;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugin.common.PluginRegistry;

/**
 * AliAuthPersonPlugin
 */
public class AliAuthPersonPlugin implements FlutterPlugin, MethodCallHandler, ActivityAware {
    /// The MethodChannel that will the communication between Flutter and native Android
    ///
    /// This local reference serves to register the plugin with the Flutter Engine and unregister it
    /// when the Flutter Engine is detached from the Activity
    private MethodChannel channel;
    // 上下文 Context
    private Context context;
    private Activity activity;
    private EventChannel.EventSink eventSink;


    @Override
    public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
        channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "ali_auth_person");
        channel.setMethodCallHandler(this);
        context = flutterPluginBinding.getApplicationContext();

        final EventChannel eventChannel = new EventChannel(flutterPluginBinding.getBinaryMessenger(), "ali_auth_person_plugin_event");
        eventChannel.setStreamHandler(new EventChannel.StreamHandler() {
            @Override
            public void onListen(Object o, EventChannel.EventSink eventSink) {
                AliAuthPersonPlugin.this.eventSink = eventSink;
            }

            @Override
            public void onCancel(Object o) {
                AliAuthPersonPlugin.this.eventSink = null;
            }
        });
    }


    @Override
    public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
        if (call.method.equals("getPlatformVersion")) {
            result.success("Android " + android.os.Build.VERSION.RELEASE);
        } else if (call.method.equals("getMetaInfos")) {
            //获取本机参数
            String metaInfo = ZIMFacade.getMetaInfos(context);
            result.success(metaInfo);
        } else if (call.method.equals("verify")) {
            //进行实名认证
            String certifyId = call.arguments();
            if (certifyId == null || certifyId.isEmpty()) {
                Toast.makeText(context, "certifyId 不能为空!", Toast.LENGTH_SHORT).show();
                return;
            }
            Toast.makeText(context, "" + certifyId, Toast.LENGTH_SHORT).show();
            ZIMFacade.install(context);
            ZIMFacade zimFacade = ZIMFacadeBuilder.create(activity);
            zimFacade.verify(certifyId, true, new ZIMCallback() {
                @Override
                public boolean response(ZIMResponse response) {
                    // TODO:根据实人认证回调结果处理自身的业务。
                    JSONObject jsonObject = new JSONObject();
                    try {
                        jsonObject.put("code", response.code);
                        jsonObject.put("msg", response.msg);
                        jsonObject.put("deviceToken", response.deviceToken);
                        jsonObject.put("videoFilePath", response.videoFilePath);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    eventSink.success(jsonObject.toString());
                    return true;
                }
            });
        } else {
            result.notImplemented();
        }
    }

    @Override
    public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
        channel.setMethodCallHandler(null);
    }

    @Override
    public void onAttachedToActivity(@NonNull ActivityPluginBinding binding) {
        activity = binding.getActivity();
    }

    @Override
    public void onDetachedFromActivityForConfigChanges() {

    }

    @Override
    public void onReattachedToActivityForConfigChanges(@NonNull ActivityPluginBinding binding) {

    }

    @Override
    public void onDetachedFromActivity() {

    }
}

Ios集成

参考:阿里云官方解说:https://help.aliyun.com/document_detail/163106.html

复制粘贴 frameworks

image.png

导入声明

编写 .podspec文件 如下

#
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html.
# Run `pod lib lint ali_auth_person.podspec` to validate before publishing.
#
Pod::Spec.new do |s|
  s.name             = 'ali_auth_person'
  s.version          = '0.0.1'
  s.summary          = 'A new Flutter project.'
  s.description      = <<-DESC
A new Flutter project.
                       DESC
  s.homepage         = 'http://example.com'
  s.license          = { :file => '../LICENSE' }
  s.author           = { 'Your Company' => 'email@example.com' }
  s.source           = { :path => '.' }
  s.source_files = 'Classes/**/*'
  s.public_header_files = 'Classes/**/*.h'
  s.dependency 'Flutter'
  s.platform = :ios, '9.0'

  s.vendored_frameworks = 'frameworks/AliyunIdentityManager.framework','frameworks/AliyunOSSiOS.framework','frameworks/APBToygerFacade.framework','frameworks/APPSecuritySDK.framework','frameworks/BioAuthAPI.framework','frameworks/BioAuthEngine.framework','frameworks/deviceiOS.framework','frameworks/MPRemoteLogging.framework','frameworks/OCRDetectSDKForTech.framework','frameworks/ToygerNative.framework','frameworks/ToygerService.framework','frameworks/ZolozIdentityManager.framework','frameworks/ZolozMobileRPC.framework','frameworks/ZolozOpenPlatformBuild.framework','frameworks/ZolozSensorServices.framework','frameworks/ZolozUtility.framework'

  s.frameworks = 'CoreGraphics','Accelerate','SystemConfiguration','AssetsLibrary','CoreTelephony','QuartzCore','CoreFoundation','CoreLocation','ImageIO','CoreMedia','CoreMotion','AVFoundation','WebKit','AudioToolbox','CFNetwork','MobileCoreServices','AdSupport'

  s.libraries = 'resolv','z','c++.1','c++abi','z.1.2.8'

  s.resource_bundles = { 'Resources' => 'frameworks/*.framework/*.bundle' }


  # Flutter.framework does not contain a i386 slice.
  # s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'i386' }
  s.swift_version = '5.0'

  # s.ios.deployment_target = '9.0'
  s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', 'VALID_ARCHS[sdk=iphonesimulator*]' => 'x86_64' }
  s.pod_target_xcconfig = {'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'arm64'   }
  s.user_target_xcconfig = { 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'arm64' }
end

编写IOS适配方法

import Flutter
import UIKit
import AliyunIdentityManager

//当前视图 ViewController;
var controller : UIViewController?;
//method管道
var channel : FlutterMethodChannel?;
//event管道
var eventChannel : FlutterEventChannel?;
//回调flutter
let eventStreamHandler = EventStreamHandler()
public class SwiftAliAuthPersonPlugin: NSObject, FlutterPlugin{

  public static func register(with registrar: FlutterPluginRegistrar) {
    channel = FlutterMethodChannel(name: "ali_auth_person", binaryMessenger: registrar.messenger())
    let instance = SwiftAliAuthPersonPlugin()
    registrar.addMethodCallDelegate(instance, channel: channel!)
    eventChannel = FlutterEventChannel(name: "ali_auth_person_plugin_event", binaryMessenger: registrar.messenger())
    eventChannel?.setStreamHandler((eventStreamHandler as! FlutterStreamHandler & NSObjectProtocol))
    //初始化阿里SDK
    AliyunSdk.`init`();
  }

  public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
      //获取本机参数
      if(call.method == "getMetaInfos"){
          let info  = AliyunIdentityManager.getMetaInfo();
          var jsonData: Data? = nil
          do {
              if info != nil {
                  jsonData = try JSONSerialization.data(withJSONObject: info!, options: .prettyPrinted)
              }
          } catch  _ {
              print("(parseError.localizedDescription)");
          }
          var infoData : String? = "";
          if let jsonData = jsonData {
              infoData = String(data: jsonData, encoding: .utf8)
          };
         result(infoData);
      }else if(call.method == "verify"){
          controller = UIApplication.shared.delegate?.window??.rootViewController;
          //进行实名认证
          let  certifyId : String = String(describing: call.arguments!);
          print(certifyId);
          let extParams: [String : Any] = ["currentCtr": controller!];
          AliyunIdentityManager.sharedInstance()?.verify(with: certifyId, extParams: extParams, onCompletion: { (response) in
              DispatchQueue.main.async {
                  var resString = ""
                  switch response?.code {
                  case .ZIMResponseSuccess:
                    resString = "认证成功"
                      break;
                  case .ZIMInterrupt:
                      resString = "初始化失败"
                   break
                  case .ZIMTIMEError:
                   resString = "设备时间错误"
                   break
                  case .ZIMNetworkfail:
                   resString = "网络错误"
                   break
                  case .ZIMInternalError:
                   resString = "用户退出"
                   break
                  case .ZIMResponseFail:
                   resString = "刷脸失败"
                  default:
                      resString = "未知异常"
                      break
                  }
                  eventStreamHandler.sendEvent(event: "{'code':\(response?.code)},'msg':\(resString),'deviceToken':\(response?.deviceToken),'videoFilePath':\(response?.videoFilePath)");
              }
          })
      }else{
          result("")
      }
  }
}

class EventStreamHandler: FlutterStreamHandler {
    private var eventSink:FlutterEventSink? = nil
    func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? {
        eventSink = events
        return nil
    }
    
    func onCancel(withArguments arguments: Any?) -> FlutterError? {
        eventSink = nil
        return nil
    }
    
    public func sendEvent(event:Any) {
        eventSink?(event)
    }
}

就此完成啦

https://github.com/lurongshuang/ali_auth_person

IOS集成的时候遇见几个问题,我截图列一下,有其他问题,联系我,我们共同成长。

问题一 和解决

image.png

image.png

问题二

image.png

问题三


image.png

image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,362评论 5 477
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,330评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,247评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,560评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,580评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,569评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,929评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,587评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,840评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,596评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,678评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,366评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,945评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,929评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,165评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 43,271评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,403评论 2 342

推荐阅读更多精彩内容