Flutter使用fluwx包实现微信登录

2,378 阅读1分钟

我使用的是 fluwx: ^3.4.2(尽量版本号保持一致,不同版本号属性方法会有变化) 版本https://pub-web.flutter-io.cn/packages/fluwx/changelog

废话不说直接上代码 首先在main.dart进行初始化

import 'package:fluwx/fluwx.dart' as fluwx;
  fluwx.registerWxApi(
    appId: "appid", //申请微信移动端开发的appid
  );
  

在需要微信登录的文件中

  // 微信登录
 void wxlogin() async {
   fluwx
       .sendWeChatAuth(scope: "snsapi_userinfo", state: "wechat_sdk_demo_test")
       .then((data) {
     if (!data) {
       String msg = data.toString() == 'false' ? '请先下载微信app' : '请授权登录';
       Fluttertoast.showToast(msg: msg);
     }
     fluwx.weChatResponseEventHandler.distinct((a, b) => a == b).listen((res) {
       if (res is fluwx.WeChatAuthResponse) {
         int errCode = res.errCode ?? 888;
         if (errCode == 0) {
           String code = res.code ?? "";
           //把微信登录返回的code传给后台,剩下的事就交给后台处理
             //首次未注册的用户引导去手机号填写页面
             //已注册的用户直接跳转首页
             }
           });
         } else if (errCode == -4) {
           Fluttertoast.showToast(msg: "用户拒绝授权");
         } else if (errCode == -2) {
           Fluttertoast.showToast(msg: "用户取消授权");
         }
       }
     });
   });
 }