美文网首页flutter
Flutter-微信授权获取用户信息

Flutter-微信授权获取用户信息

作者: 节庆007 | 来源:发表于2019-12-15 21:02 被阅读0次

    微信授权获取用户信息依赖两个库
    fluwx: ^1.1.3
    dio: ^3.0.7 # 网络

    废话不多,直接上代码

    import 'dart:convert';
    import 'package:dio/dio.dart';
    import 'package:fluwx/fluwx.dart' as fluwx;
    import 'package:yxk_app/constant/constant.dart';
    import 'package:yxk_app/event/wx_auth_login_event.dart';
    import 'package:yxk_app/utils/data_utils.dart';
    import 'package:yxk_app/utils/eventbus_util.dart';
    import 'package:yxk_app/utils/toast_utils.dart';
    
    /// 微信授权
    class WxAuth {
      /// 微信获取用户信息授权
      static authLogin() {
        fluwx.isWeChatInstalled().then((installed) {
          if (installed) {
            fluwx
                .sendWeChatAuth(
                    scope: "snsapi_userinfo", state: "wechat_sdk_demo_test")
                .then((data) {})
                .catchError((e) {});
          } else {
            ToastUtils.showToast("请先安装微信");
          }
        });
      }
    
      /// 获取用户信息
      static getAccessToken(String code) {
        Dio dio = new Dio();
        dio.get("https://api.weixin.qq.com/sns/oauth2/access_token",
            queryParameters: {
              "appid": Constant.APP_ID,
              "secret": Constant.APP_SECRET,
              "code": code,
              "grant_type": "authorization_code"
            }).then((response) {
          Map<String, dynamic> map = json.decode(response.data);
    
          String token = map["access_token"];
          String openid = map["openid"];
    
          if (!StringUtils.isEmpty(token) && !StringUtils.isEmpty(openid)) {
            getUserInfo(token, openid);
          }
        });
      }
    
      /// 获取用户详细信息
      static getUserInfo(String token, String openid) {
        Dio dio = new Dio();
        dio.get("https://api.weixin.qq.com/sns/userinfo", queryParameters: {
          "access_token": token,
          "openid": openid
        }).then((response) {
          Map<String, dynamic> map = json.decode(response.data);
    
          String nickname = map["nickname"];
          String openid = map["openid"];
    
          if (!StringUtils.isEmpty(nickname) && !StringUtils.isEmpty(openid)) {
            EventBusUtil.getInstance()
                .fire(WxAuthLoginEvent().setNickName(nickname).setOpenId(openid));
          }
        });
      }
    }
    
    

    流程很简单
    1.main.dart中注册微信相关项
    2.该工具类流程,微信获取用户信息授权-获取用户信息-获取用户详细信息
    3.通知在相关界面接收详细的微信个人信息。

    相关文章

      网友评论

        本文标题:Flutter-微信授权获取用户信息

        本文链接:https://www.haomeiwen.com/subject/riylnctx.html