-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspringboot 公众号实现获取用户openid 基于SDK
66 lines (57 loc) · 2.68 KB
/
springboot 公众号实现获取用户openid 基于SDK
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
scope为snsapi_base:
https://open.weixin.qq.com/connect/oauth2/authorize?appid=你的appid&redirect_uri=你的域名加回调地址(https://你的域名/回调地址)&response_type=code&scope=snsapi_base&state=123#wechat_redirect
scope为snsapi_userinfo:
https://open.weixin.qq.com/connect/oauth2/authorize?appid=你的appid&redirect_uri=你的域名加回调地址(https://你的域名/回调地址)&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect
---------------------------------------------------------------------
maven:
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-mp</artifactId>
<version>4.4.0</version>
</dependency>
---------------------------------------------------------------------
wx mp config:
@Configuration
@RequiredArgsConstructor
public class WxMpServiceConfig {
@Bean
public WxMpService wxMpService() {
WxMpService wxMpService = new WxMpServiceImpl();
wxMpService.setWxMpConfigStorage(wxMpConfigStorage());
return wxMpService;
}
@Bean
public WxMpConfigStorage wxMpConfigStorage() {
WxMpDefaultConfigImpl wxMpDefaultConfig = new WxMpDefaultConfigImpl();
wxMpDefaultConfig.setAppId(你的appid);
wxMpDefaultConfig.setSecret(你的secret);
return wxMpDefaultConfig;
}
}
---------------------------------------------------------------------
业务代码:
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.service.WxOAuth2Service;
import me.chanjar.weixin.mp.api.WxMpService;
@RestController
@RequestMapping("/wechat")
@CrossOrigin
@RequiredArgsConstructor
public class WxMpOauthController {
private final WxMpService wxMpService;
@SneakyThrows(Exception.class)//简化try catch
@GetMapping("/auth")
@ApiOperation("回调-授权登录同意")
public WxOAuth2UserInfo callback(@RequestParam("code") String code) {
WxOAuth2Service oAuth2Service = this.wxMpService.switchoverTo(appid).getOAuth2Service();
WxOAuth2AccessToken wxOAuth2AccessToken = oAuth2Service.getAccessToken(code);
String accessToken = wxOAuth2AccessToken.getAccessToken();
String openId = wxOAuth2AccessToken.getOpenId();
log.info("[微信公众号] 授权回调 accessToken:[{}]", accessToken);
log.info("[微信公众号] 授权回调 openId:[{}]", openId);
WxOAuth2UserInfo userInfo = oAuth2Service.getUserInfo(wxOAuth2AccessToken, "zh_CN");
log.info("[微信公众号] 授权回调 用户信息:[{}]", JSONUtil.toJsonStr(userInfo));
return userInfo;
}
}