OTPLess Flutter 插件

集成 OTPless “使用 WhatsApp 登录” 功能

入门

原生部分(权限)

1. 复制应用程序名称、包名称和 Bundle Id,然后创建一个 OTPLess 账户

Copy the application name, Package Name and Bundle Id and create an OTPLess account

2. 转到侧边栏中的“Applications”选项卡并复制回调 URI

  • 回调 URI 应该是您应用程序的深度链接

Copy the application name, Package Name and Bundle Id and create an OTPLess account

2. 添加了必需的权限

对于 iOS

  • 在 Info.plist 文件中添加以下键以成功深度链接回调 URI
  • 回调 URI 分为两部分:一部分是 scheme,另一部分是 domain
  • 例如:对于 URI “exam://example.com”,*“exam”* 是 scheme,*“example.com”* 是 domain
  • 我们需要将 domain 和 scheme 添加到 Info.Plist 文件中

<key>FlutterDeepLinkingEnabled</key>
<true/>
<key>CFBundleURLTypes</key>
<array>
    <dict>
    <key>CFBundleTypeRole</key>
    <string>Editor</string>
    <key>CFBundleURLName</key>
    <string>your_app_domain</string>
    <key>CFBundleURLSchemes</key>
    <array>
    <string>your_app_scheme</string>
    </array>
    </dict>
</array>
  • 示例(查询权限) iOS 深度链接示例

  • 我们还需要查询权限来检查用户设备上是否安装了 WhatsApp

<key>LSApplicationQueriesSchemes</key>
<array>
    <string>whatsapp</string>
</array>
  • 示例(查询权限) iOS 查询权限示例

对于 Android

  • AndroidMainfest.xml 也必须进行修改以支持深度链接
  • 将此 xml 片段粘贴到 `android/app/src/main/AndroidManifest.xml` 中的 `AndroidManifest.xml` 文件里,位于 `<activity>` 标签内

<intent-filter android:autoVerify="true">
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="android.intent.category.BROWSABLE" />
    <data android:scheme="your_app_scheme" android:host="your_app_domain"  />
</intent-filter>
  • 如果您有更多疑问,请查看示例应用程序的 AndroidManifest

Flutter 部分(实现)

安装 OTPless Flutter 插件

  • 在您的 flutter 应用的根目录的终端中输入此命令
flutter pub add otpless_flutter

在您的 Flutter 项目中导入插件

注意:在应用程序的入口点使用插件,例如在根路由(起始页面)“/”

import 'package:otpless_flutter/otpless_flutter.dart';

创建插件实例并将其存储在局部变量中

final _otplessFlutterPlugin = Otpless();

用于启动登录流程的函数

 // ** Function to initiate the login process
  void initiateWhatsappLogin(String intentUrl) async{
    var result = await _otplessFlutterPlugin.loginUsingWhatsapp(intentUrl: intentUrl);
    switch (result['code']) {
      case "581":
        print(result['message']);
        //TODO: handle whatsapp not found
        break;
      default:
    }
  }

监听 token 变化

  • 注意:在 `initState()` 方法中监听 token 变化,如下面的示例所示

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

  // ** Function that is called when page is loaded
  // ** We can check the auth state in this function
  Future<void> initPlatformState() async {
    _otplessFlutterPlugin.authStream.listen((token) {
      // TODO: Handle user token like storing in SharedPreferences or navigation
      print(token)
    });
  }

OTPless 使用 ❤️ 制作

GitHub

查看 Github