WeChat authorization to obtain openid through code

When doing official account development, it is necessary to obtain the user's openid as a unique identifier. When WeChat authorizes, the front-end calls the WeChat authorization interface to obtain the code and transmits it to the back-end. After the back-end gets the code, it calls the WeChat interface to obtain the openid 
. You can view it in the account background 
/** 
 * @param 
 * @Description: Get WeChat official account user login information 
 * @date 
 */ 
@GetMapping("getInfoByCode") 
public JSONObject selectWxUser(String code) { 
    JSONObject jsonWxUser = new JSONObject(); 
    Map map = new HashMap<>(); 
    String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=appid+ 
            "&secret=" + secret+ "&code=" + code + "&grant_type= authorization_code"; 
    RestTemplate restTemplate = new RestTemplate(); 
    String response = restTemplate.getForObject(url, String.class); 
    JSONObject jsonObject = JSON.parseObject(response);
    String refresh_token = jsonObject.getString("refresh_token");
    String accessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=" + appid+ "&grant_type=refresh_token&refresh_token=" + refresh_token;
    String responseAccessTokenUrl = restTemplate.getForObject(accessTokenUrl, String.class);
    JSONObject jsonObjectAccessTokenUrl = JSON.parseObject(responseAccessTokenUrl);
    String openid = jsonObjectAccessTokenUrl.getString("openid");
    if (StringUtils.isEmpty(openid)) {
        jsonWxUser.put("code", 201);
        jsonWxUser.put("data","code has expired"); 
    }
        return jsonWxUser;

    map.put("openid", openid);
    jsonWxUser.put("code", 200);
    jsonWxUser.put("data", map);
    return jsonWxUser;
}

Guess you like

Origin blog.csdn.net/m0_57666466/article/details/131741897