⼩程序的授权登录和获取⽤户信息
授权登录
前端传递过来code,然后后端⽤code+appid+secret调⽤的de2Session接⼝得到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 = "api.weixin.qq/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 = hange(wxurl, HttpMethod.POST, null, JSONObject.class, param); JSONObject resultJson = Body(); Map<String, String> result = new HashMap<>(); result.pu
t("resultJson", String()); if (resultJson.has("openId")) { // 获取sessionKey 和openId String sessionKey = ("session_key").toString(); String openId = ("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 = pt(session); result.put("session", session); } catch (Exception e) { e.printStackTrace(); } } else { return R.success(result, "授权失败"); } return R.success(result, "授权成功"); }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
js获取json的key和value36
37
38
39
40
41
42
43
44先导⼊依赖<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 = Openid(); String session_key = Session_key();1
2
3
4
5
6
7
8
9
10
11
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论