微信授权获取用户信息依赖两个库
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.通知在相关界面接收详细的微信个人信息。
网友评论