微信网页授权-菜单链接跳转-获取用户信息-openid

微信网页授权介绍:

相关流程入下图:

微信网页授权-菜单链接跳转-获取用户信息-openid

前端js如上图所示,然后根据获取到的code,再调用后端接口,获取openid:

代码如下:

@RequestMapping(value = "mobile/getOpenId/code")
    public void getOpenId(HttpServletRequest request, HttpServletResponse response) {
        String code = request.getParameter("code");//微信活返回code值,用code获取openid
        String state = request.getParameter("state");
        logger.info("wx-:mobile/getOpenId/code=code:{}", code);
        logger.info("wx-:mobile/getOpenId/code=state:{}", state);
        String openId = getOpendid(code);
        logger.info("wx-:mobile/getOpenId/code=openId:{}", openId);
        try {
            response.getWriter().print(openId);
            response.getWriter().flush();
        } catch (Exception e) {
            logger.error("wx-:mobile/getOpenId/code=error:{}", ExceptionUtils.getStackTrace(e));
            try {
                response.getWriter().flush();
            } catch (Exception ex) {
                logger.error("wx-:mobile/getOpenId/code=error:{}", ExceptionUtils.getStackTrace(ex));
            }
        }
    }

    /**
     * 从返回报文中获取openid
     *
     * @param code
     * @return
     */
    private String getOpendid(String code) {
        String url = Constant.WX_OAUTH;
        url = url.replace("AppId", Constant.WX_APPID) //对应的appid
                .replace("AppSecret", Constant.WX_APPSECRET)//对应的appsecret
                .replace("CODE", code);

        logger.info("wx-:mobile/getOpenId/code=url:{}", url);

        HttpsClient httpClient = HttpsClient.getAsyncHttpClient();
        String response = httpClient.get(url);
        JSONObject jsonTexts = (JSONObject) JSON.parse(response);
        logger.info("wx-:mobile/getOpenId/code=response:{}", response);
        String openid = "";
        if (jsonTexts.get("openid") != null) {
            openid = jsonTexts.get("openid").toString();
        }
        return openid;
    }


Constant类:
public class Constant {
    
    public static final String WX_OAUTH = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=AppId&secret=AppSecret&code=CODE&grant_type=authorization_code";


    public static final String GRANT = "client_credential";
    public static final String WX_ACCESS_TOKEN = "https://api.weixin.qq.com/cgi-bin/token?grant_type=Grant&appid=AppId&secret=AppSecret";




}

https请求见:

 这样就可以获取到用户的openid了,根据用户的openid可以进行帐号绑定或者绑定帐号获取的操作。