【Flutter】阿里云号码认证一键登录

项目环境是flutter开发的,然而阿里云官网并没有flutter相关的SDK,所以选择了集成的插件,这里踩过的坑不多叙述,开始正题。
阿里云号码认证文档:https://help.aliyun.com/product/75010.html

一、插件选择:ali_auth: ^0.2.3

pubspec.yaml

dependencies:
  flutter:
    sdk: flutter
  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  ali_auth: ^0.2.3

二、main.dart 初始化SDK

void main() {
  runApp(const MyApp());
  if (!kIsWeb) { //判断是否是web环境
    initAliLogin();
  }
}
void initAliLogin() async {
  WidgetsFlutterBinding.ensureInitialized();
  final result;
  if (Platform.isAndroid) {
    result = await AliAuthPlugin.initSdk(
      sk: 'andriodKey',
      config: getConfig(),
    );
  } else {
    result = await AliAuthPlugin.initSdk(
      sk: 'iosKey',
      config: getConfig(), //getDislogConfig(),弹框模式与全屏模式
    );
  }
  print(result);
}

login.dart 事件绑定及监听

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

/// 我的-首页
class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  State createState() => _MyHomePageState();
}

class _MyHomePageState extends State {
  BuildContext? mContext;

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

    /// 执行相关登录
    login();
  }

  /// 相关登录
  login() async {
    /// 登录监听
    AliAuthPlugin.loginListen(
        type: false, onEvent: _onEvent, onError: _onError);
  }

  /// 登录成功处理
  void _onEvent(event) async {
    print("-------------成功分割线------------$event");
    if (event != null && event['code'] != null) {
      if (event['code'] == '600024') {
        await AliAuthPlugin.login;
      } else if (event['code'] == '600000') {
        print('获取到的token${event["data"]}');
      }
    }
  }

  /// 登录错误处理
  void _onError(error) {
    print("-------------失败分割线------------$error");
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.only(top: 100),
      child: InkWell(
        child: const Text("一键登录"),
        onTap: () async {
          final result = await AliAuthPlugin.login;
          // ignore: avoid_print
          print(result);
        },
      ),
    );
  }
}

补充

1、需要按照阿里云文档,对andriod进行相关配置(ios应该也要)
https://help.aliyun.com/document_detail/189787.html#section-vxb-jwt-sou
2、注意包名、签名、密钥的一致性。
3、重点:修改源码,直接搜索setLoggerEnable,括号里参数都改为true!!!

setLoggerEnable(true)//调试时,出现600015,手机终端不安全时修改

至此,可以正常唤起一键登录页面。

你可能感兴趣的:(【Flutter】阿里云号码认证一键登录)