两步实现微信小程序登录 获取openid和session_key
Posted 一个抓手
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了两步实现微信小程序登录 获取openid和session_key相关的知识,希望对你有一定的参考价值。
1.前端调用 wx.login() 获取临时登录凭证code,并回传到后台服务。
wx.login({
success (res) {
if (res.code) {
//发起网络请求
wx.request({
url: 'https://example.com/onLogin',
data: {
code: res.code
}
})
} else {
console.log('登录失败!' + res.errMsg)
}
}
})
2.后台拿到code调用auth.code2Session接口完成登录流程,可获取到openid、unionid、session_key
public static JSONObject code2Session(String code) {
// 发送http请求
HttpRequest httpRequest = HttpUtil.createGet("https://api.weixin.qq.com/sns/jscode2session");
httpRequest.form("appid", "wx6f525598409b1cd0");
httpRequest.form("secret", "ab6e2190846612ef8ef1ccfd42dedcf9");
httpRequest.form("js_code", code);
httpRequest.form("grant_type", "authorization_code");
HttpResponse execute = httpRequest.execute();
String body = execute.body();
execute.close();
JSONObject jsonObject = JSONObject.parseObject(body);
Integer errcode = jsonObject.getInteger("errcode");
// -1:系统繁忙,此时请开发者稍候再试
// 0:请求成功
// 40029:code 无效
// 45011:频率限制,每个用户每分钟100次
if (errcode != 0) {
throw new BusinessException(errcode, jsonObject.getString("errmsg"));
}
return jsonObject;
}
public static void main(String[] args) {
JSONObject jsonObject = code2Session("xxx");
// 用户唯一标识
System.out.println(jsonObject.getString("openid"));
// 会话密钥
System.out.println(jsonObject.getString("session_key"));
// 用户在开放平台的唯一标识符,若当前小程序已绑定到微信开放平台帐号下会返回
System.out.println(jsonObject.getString("unionid"));
// 错误码
System.out.println(jsonObject.getInteger("errcode"));
// 错误信息
System.out.println(jsonObject.getString("errmsg"));
}
以上是关于两步实现微信小程序登录 获取openid和session_key的主要内容,如果未能解决你的问题,请参考以下文章