java+flutter实现微信登录
这篇文章很简单,讲的是微信登录,app端用flutter实现,服务端用java实现。
app负责拿到微信用户的code,服务端通过code拿到openId。
一、准备工作
1.微信应用平台创建应用 点击创建
2.创建通过后你会你会获得appId、appSecret以及微信登录的使用权。如下图所示:
二、app端
1、导包
fluwx: ^3.4.3
2、build.gradle文件
上述是build.gradle里的配置,要注意微信应用平台的包名和应用签名和这里配置的要一致。
3、调用微信客户端
bindWechat() async {
fluwx
.sendWeChatAuth(scope: "snsapi_userinfo", state: "wechat_sdk_demo_test")
.then(
(data) {
G.showToast(
data.toString() == 'false' ? '请先下载微信app' : '请授权登录',
);
},
);
}
回调
fluwx.weChatResponseEventHandler.distinct((a, b) => a == b).listen((res) {
print('code为:' + res.code)
});
到这里就可以拿到微信的code了。
三、服务端
拿到code后服务端主要有两个访问地址,如下:
1、
https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code
微信认证地址:appId和appSecret去微信应用平台拿,code是app端传来的。通过该地址可以拿到openId和token等。
2、https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN
微信用户信息查询地址:通过第一步得到的token和openId拿到微信用户信息
其他地址:
https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=%s&grant_type=refresh_token&refresh_token=%s
微信token刷新地址
四、知识点
在一个项目中可能需要多次拉起微信,但是默认每个回调都会执行。这里我教大家怎么保证回调正确。
bindWechat() async {
fluwx
.sendWeChatAuth(scope: "snsapi_userinfo", state: "wechat_sdk_demo_test")
.then(
(data) {
G.showToast(
data.toString() == 'false' ? '请先下载微信app' : '请授权登录',
);
},
);
}
在以上代码中的wechat_sdk_demo_test是可以传任意值的,并且在回调时是可以取到的,可以用该参数作为标记判断。