WeChat open platform access, official website: https://open.weixin.qq.com, you can obtain APP_ID and APP_SECRET after registering and adding applications on the official website.
Step 1: Create an interface that inherits AuthService, WeChatAuthService, as follows
public interface WeChatAuthService extends AuthService { public JSONObject getUserInfo(String accessToken, String openId);}Step 2: The specific implementation of WeChatService is as follows
@Servicepublic class WeChatAuthServiceImpl extends DefaultAuthServiceImpl implements WeChatAuthService { private Logger logger = LoggerFactory.getLogger(WeChatAuthServiceImpl.class);//Request this address and jump to the QR code login interface private static final String AUTHORIZATION_URL = "https://open.weixin.qq.com/connect/qrconnect?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=%s#wechat_redirect"; // Get the URL of the user openid and access-toke private static final String ACCESSTOKE_OPENID_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code"; private static final String REFRESH_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=%s&grant_type=refresh_token&refresh_token=%s"; private static final String USER_INFO_URL = "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN"; private static final String APP_ID="xxxxxx"; private static final String APP_SECRET="xxxxxx"; private static final String SCOPE = "snsapi_login"; private String callbackUrl = "https://www.xxx.cn/auth/wechat"; //Calling domain name @Override public String getAuthorizationUrl() throws UnsupportedEncodingException { callbackUrl = URLEncoder.encode(callbackUrl,"utf-8"); String url = String.format(AUTHORIZATION_URL,APP_ID,callbackUrl,SCOPE,System.currentTimeMillis()); return url; } @Override public String getAccessToken(String code) { String url = String.format(ACCESSTOKE_OPENID_URL,APP_ID,APP_SECRET,code); UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url); URI uri = builder.build().encode().toUri(); String resp = getRestTemplate().getForObject(uri, String.class); logger.error("getAccessToken resp = "+resp); if(resp.contains("openid")){ JSONObject jsonObject = JSONObject.parseObject(resp); String access_token = jsonObject.getString("access_token"); String openId = jsonObject.getString("openid");; JSONObject res = new JSONObject(); res.put("access_token",access_token); res.put("openId",openId); res.put("refresh_token",jsonObject.getString("refresh_token")); return res.toJSONString(); }else{ throw new ServiceException("access token failed, msg = "+resp); } } //In the WeChat interface, token and openId return together, so this method does not need to be implemented @Override public String getOpenId(String accessToken) { return null; } @Override public JSONObject getUserInfo(String accessToken, String openId){ String url = String.format(USER_INFO_URL, accessToken, openId); UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url); URI uri = builder.build().encode().toUri(); String resp = getRestTemplate().getForObject(uri, String.class); logger.error("getUserInfo resp = "+resp); if(resp.contains("errcode")){ throw new ServiceException("Error getting user information, msg = "+resp); }else{ JSONObject data =JSONObject.parseObject(resp); JSONObject result = new JSONObject(); result.put("id",data.getString("unionid")); result.put("nickName",data.getString("nickname")); result.put("avatar",data.getString("headimgurl")); return result; } } //WeChat's token has only a 2-hour validity period, and it needs to be re-acquisitioned from time to time, so the official provides a method to refresh and obtain the token according to refresh_token. This project only obtains user//information and stores the information into the library, so two hours is enough @Override public String refreshToken(String refresh_token) { String url = String.format(REFRESH_TOKEN_URL,APP_ID,refresh_token); UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url); URI uri = builder.build().encode().toUri(); ResponseEntity<JSONObject> resp = getRestTemplate().getForEntity(uri,JSONObject.class); JSONObject jsonObject = resp.getBody(); String access_token = jsonObject.getString("access_token"); return access_token; }}Step 3:
Called in Controller, the code is as follows:
@RequestMapping(value = "/wxLoginPage",method = RequestMethod.GET) public JSONObject wxLoginPage() throws Exception { String uri = weChatAuthService.getAuthorizationUrl(); return loginPage(uri); } @RequestMapping(value = "/wechat") public void callback(String code,HttpServletRequest request,HttpServletResponse response) throws Exception { String result = weChatAuthService.getAccessToken(code); JSONObject jsonObject = JSONObject.parseObject(result); String access_token = jsonObject.getString("access_token"); String openId = jsonObject.getString("openId");// String refresh_token = jsonObject.getString("refresh_token"); // Save access_token to cookie, expired for two hours Cookie accessTokencookie = new Cookie("accessToken", access_token); accessTokencookie.setMaxAge(60 *2); response.addCookie(accessTokencookie); Cookie openIdCookie = new Cookie("openId", openId); openIdCookie.setMaxAge(60 *2); response.addCookie(openIdCookie); //Judge whether the user has logged in based on openId. KmsUser user = userService.getUserByCondition(openId); if (user == null) { response.sendRedirect(request.getContextPath() + "/student/html/index.min.html#/bind?type="+Constants.LOGIN_TYPE_WECHAT); } else { //If the user already exists, log in directly to response.sendRedirect(request.getContextPath() + "/student/html/index.min.html#/app/home?open_id=" + openId); } } Step 4:
In the front desk js, first request auth/wxLoginPage, obtain the authorization address, and call back /auth/wechat after the user authorization, and then perform logical processing in this method.
Troubles encountered:
1. When configuring the callback domain name in the official WeChat website, you do not need some http or https protocols. You only need to write the domain. For example, http://baidu.com, you only need to fill in baidu.com. If you want to jump to a controller below the project, such as baidu.com/auth/wechat, you only need to configure baidu.com, and you do not need to specify the subsequent auth/wechat. The subsequent address can be written on the address of the callback in the code. The code should be configured as https://baidu.com/auth/wechat.
2. When jumping to the authorized QR code interface, you will encounter the situation where the QR code cannot be released. This is because of the callback address in the code. There should be no problem in configuring the method in the above code.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.