官网:https://developers.weixin.qq.com/miniprogram/dev/api-backend/
授权登录
前端传递过来code,然后后端用code+appid+secret调用微信的auth.code2Session接口得到session_key和openID
然后再由前端来授权。
方法一:
/**
* 微信登录的原理,前段调用微信接口得到一个code,然后后端用这个code和小程序的appid以及appsecret 调用接口得到session_key和openid
* 然后再滴定仪一个状态返回给前端使用
*/
@PostMapping("/wxLogin")
public R wxLogin(@RequestParam(value = "code", required = false) String code,
@RequestParam(value = "rawData", required = false) String rawData,
@RequestParam(value = "signature",required = false) String signature) {
String wxurl = "https://api.weixin.qq.com/sns/jscode2session";
MultiValueMap<String, Object> param = new LinkedMultiValueMap();
param.add("appid", "xxx2xxxxxc");
param.add("secret", "xxxxxxxxxxxx2");
param.add("js_code", code);
param.add("grant_type", "authorization_code");
ResponseEntity<JSONObject> exchange = restTemplate.exchange(wxurl, HttpMethod.POST, null, JSONObject.class, param);
JSONObject resultJson = exchange.getBody();
Map<String, String> result = new HashMap<>();
result.put("resultJson", resultJson.toString());
if (resultJson.has("openId")) {
// 获取sessionKey和openId
String sessionKey = resultJson.get("session_key").toString();
String openId = resultJson.get("openId").toString();
// 生成自定义登录态
String session = null;
Map<String, String> sessionMap = new HashMap<>();
sessionMap.put("sessionKey", sessionKey);
sessionMap.put("openId", openId);
session = JSONObject.fromObject(sessionMap).toString();
try {
EncryptUtil encryptUtil = new EncryptUtil();
session = encryptUtil.encrypt(session);
result.put("session", session);
} catch (Exception e) {
e.printStackTrace();
}
} else {
return R.success(result, "授权失败");
}
return R.success(result, "授权成功");
}
方法二:
先导入依赖
<dependency>
<groupId>com.github.liyiorg</groupId>
<artifactId>weixin-popular</artifactId>
<version>2.8.31</version>
</dependency>
// SnsAPI 上面依赖自带的
Jscode2sessionResult jscode2sessionResult = SnsAPI.jscode2session("wxxxxc", "ab792xxxf28920c2", code);
String openid = jscode2sessionResult.getOpenid();
String session_key = jscode2sessionResult.getSession_key();
获取用户信息
2021年前是后端调用api,现在是前端调用
但是电话号码需要后端解密一下,查看我的另一篇篇文章
微信支付和退款,需要关注成为粉丝才可见哦!!
微信支付和退款,需要关注成为粉丝才可见哦!!