项目背景
为了方便用户登录,需要一键登录的功能,经过调研,比较成熟的是极光公司提供的号码验证flutter插件JVerification,集成了联通、移动、电信三大运营商SDK,使用非常方便,但是这次开发却没有使用它,而是采用的阿里云号码认证服务。
相比于阿里云,极光号码认证服务费用更高,更主要原因,公司一直是使用的阿里云的服务,处于维护方面考虑,所以一键登录功能仍然采用阿里云服务,而阿里云并没有提供flutter插件,需要自己开发个flutter plugins集成Android 以及 IOS SDK。
插件开发
1、获取SDK秘钥
首先需要去控制台下载SDK,需要开通企业认证的账号,个人账号是无法进入的,然后购买认证方案,获取App android、ios的SDK秘钥。
2、flutter插件
Android studio新建一个flutter plugins项目ali_auth,然后在pubspec.yaml
引入
dependencies:
ali_auth:
path: lib/plugins/ali_auth
ali_auth.dart注册一些调用方法
import 'dart:async';
import 'package:flutter/services.dart';
class AliAuthPlugin {
static const MethodChannel _channel = const MethodChannel('ali_auth');
// 初始化SDK
static Future<dynamic> initSdk(String sk) async {
Map<String, String> params = {'sk': sk};
return await _channel.invokeMethod("init", params);
}
/// SDK判断网络环境是否支持
static Future<bool> get checkVerifyEnable async {
return await _channel.invokeMethod("checkVerifyEnable");
}
// 一键登录
static Future<dynamic> get login async {
return await _channel.invokeMethod('login');
}
// 预取号
static Future<dynamic> get preLogin async {
return await _channel.invokeMethod('preLogin');
}
}
3、集成android SDK
获取android 原生的context,activity
@Override
public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
channel = new MethodChannel(flutterPluginBinding.getFlutterEngine().getDartExecutor(), "ali_auth");
mContext = flutterPluginBinding.getApplicationContext();
channel.setMethodCallHandler(this);
}
@Override
public void onAttachedToActivity(@NonNull ActivityPluginBinding activityPluginBinding) {
activity = activityPluginBinding.getActivity();
}
有些App可能获取到的值都是null,这与App插件注册方式有关,需要在registerWith方法内获取
public static void registerWith(Registrar registrar) {
mContext = registrar.context();
activity = registrar.activity();
final MethodChannel channel = new MethodChannel(registrar.messenger(), "ali_auth");
channel.setMethodCallHandler(new AliAuthPlugin());
}
下载SDK的时候,提供了demo,先把demo跑起来,如果是用android studio开发,可以在demo内阅读详细的Android SDK提供的方法,照着demo开发就好了,这里不解释。
注册一些方法,用于flutter与 android通信
@Override
public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
switch (call.method) {
case "init":
init(call, result);
break;
case "preLogin":
preLogin(call, result);
break;
case "login":
login(call, result);
break;
case "checkVerifyEnable":
checkVerifyEnable(call, result);
break;
default:
throw new IllegalArgumentException("Unkown operation" + call.method);
}
}
通过获取token回调,可以获取各种SDK返回码,做相应处理即可
mTokenListener = new TokenResultListener() {
@Override
public void onTokenSuccess(final String ret) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
Log.e("xxxxxx", "onTokenSuccess:" + ret);
TokenRet tokenRet = null;
try {
tokenRet = JSON.parseObject(ret, TokenRet.class);
} catch (Exception e) {
e.printStackTrace();
}
JSONObject jsonObject = new JSONObject();
if (tokenRet != null && ("600024").equals(tokenRet.getCode())) {
jsonObject.put("returnCode", tokenRet.getCode());
jsonObject.put("returnMsg", "终端自检成功!");
jsonObject.put("returnData", "");
}
if (tokenRet != null && ("600001").equals(tokenRet.getCode())) {
jsonObject.put("returnCode", tokenRet.getCode());
jsonObject.put("returnMsg", "唤起授权页成功!");
jsonObject.put("returnData", "");
}
if (tokenRet != null && ("600000").equals(tokenRet.getCode())) {
token = tokenRet.getToken();
mAlicomAuthHelper.quitLoginPage();
jsonObject.put("returnCode", tokenRet.getCode());
jsonObject.put("returnMsg", "获取token成功!");
jsonObject.put("returnData", token);
if (loginResult != null) {
loginResult.success(jsonObject);
}
}
}
});
}
@Override
public void onTokenFailed(final String ret) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
Log.e("xxxxxx", "onTokenFailed:" + ret);
TokenRet tokenRet = null;
try {
tokenRet = JSON.parseObject(ret, TokenRet.class);
} catch (Exception e) {
e.printStackTrace();
}
// 处理飞行模式、获取token失败、手机欠费、运营商服务异常、IO异常、等特殊情况
if (tokenRet != null && !(("700000").equals(tokenRet.getCode()))) {
token = tokenRet.getToken();
JSONObject jsonObject = new JSONObject();
jsonObject.put("returnCode", "600002");
jsonObject.put("returnMsg", tokenRet.getMsg());
jsonObject.put("returnData", "");
if (loginResult != null) {
loginResult.success(jsonObject);
}
}
}
});
}
};
监听授权页内的点击
// 监听点击授权页UI
public void listenUIClick(final MethodCall call, final MethodChannel.Result methodResult) {
mAlicomAuthHelper.setUIClickListener(new AuthUIControlClickListener() {
@Override
public void onClick(String code, Context context, JSONObject jsonObj) {
JSONObject jsonObject = new JSONObject();
if (code == "700001") {
jsonObject.put("returnCode", code);
jsonObject.put("returnMsg", "用户切换其他登录方式");
jsonObject.put("returnData", "");
mAlicomAuthHelper.quitLoginPage();
methodResult.success(jsonObject);
}
}
});
}
4、集成ios SDK
需要配置ali_auth.podspec,文件的目录与配置项要对应
#
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html.
# Run `pod lib lint ali_auth.podspec' to validate before publishing.
#
Pod::Spec.new do |s|
s.name = 'ali_auth'
s.version = '0.0.1'
s.summary = 'A new Flutter plugin.'
s.description = <<-DESC
A new Flutter plugin.
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, '8.0'
s.vendored_frameworks = 'libs/ATAuthSDK.framework'
# Flutter.framework does not contain a i386 slice. Only x86_64 simulators are supported.
s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', 'VALID_ARCHS[sdk=iphonesimulator*]' => 'x86_64' }
end
插件具体源码代码见github -> ali_auth
一些总结:
1、app调整到授权页,有一个类似跳转到外部的App的过程,通过didChangeAppLifecycleState生命周期
是可以监控到的,可以做一些toast的取消操作。
2、移动卡会出现闪退问题,需要在pods -> TARGETS -> ali_auth -> Build Settings -> Linking -> Other Linker Flags 里面加上 -ObjC(因为AuthSDK是通过pod依赖进去的,所有对应的target里面要加这个配置,不然移动网络会crash) ,打包的时候一定要注意,否则问题很严重。
3、IOS的SDK是通过pod依赖进去的, Runner -> Frameworks(文件)下面的 ATAuthSDK.framework是没有必要引入的,-ObjC也没必要加。
4、android 的协议页会出现黑边问题
在application的节点添加android:theme="@style/LaunchTheme",并在styles.xml取消黑边显示。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="LaunchTheme" parent="@android:style/Theme.Black.NoTitleBar">
<!-- Show a splash screen on the activity. Automatically removed when
Flutter draws its first frame -->
<item name="android:windowFullscreen">true</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowBackground">@drawable/launch_background</item>
<item name="android:windowDrawsSystemBarBackgrounds">false</item>
</style>
</resources>