Wechat web page to obtain user information

Posted by snday on Thu, 26 Dec 2019 16:33:44 +0100

To obtain user information through wechat webpage authorization, you only need to configure the authorized domain name on the wechat side, and the subsequent operations are all implemented on the server side.

1. Wechat background configuration authorization domain name

2. Access to user information on the server side

Write a test page with a connection,

https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx5dcb95b593046871&redirect_uri=https%3A%2F%2FDomain name you filled in on wechat%2FCatalog1%2FCatalog2&response_type=code&scope=snsapi_base&state=Callback return parameter#wechat_redirect

Pay attention to several points:

1. Domain name of wechat: the domain name address filled in step 1
2. Directory 1, 2 address: it can be a level-1 directory or a level-2 directory. This has no effect. I'm level-2 here. [it's different from payment. When you pay, you need to configure the trust directory of payment, so the level is fixed. ]
3. Callback to return parameters: when the user clicks this link, the authorization page of wechat will be called up. After the user operates, wechat will call back the address of the redirect ﹐ URI you filled in, and return the parameter state, so you can let state pass some special parameters. But the length is limited, so we need to pay attention to it.

Back end code:

    /**
     * Get user information
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/getUserInfo")
    public String getUserInfo(HttpServletRequest request,Model model){
        //When calling back, wechat will return a code parameter to get the code. If there is no code, it means failure. Pay attention to return the error page.
        String code = request.getParameter("code");
        log.info("code:" + code);
        if (StringUtils.isBlank(code)) {
            return "/pages/notice";
        }
        // If the value of state is filled in the connection address above, wechat will return the state as it is, here we get it.
        String state = request.getParameter("state");
        log.info("state:" + state);
        if (StringUtils.isBlank(state)) {
            log.info("No return state parameter");
        }
        // After getting the code, use code as a parameter to call the wechat interface in exchange for access_token.
        //oauth2_url=https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
        String oauth2_url = WeChatConfig.oauth2_url.replace("APPID", BaseController.appid).replace("SECRET", BaseController.appsecret).replace("CODE", code);
        // Write a tool class and call the interface. okhttp is recommended.
        String auth_return = WeixinHttpUtils.post(oauth2_url, null);
        log.info("auth_return:" + auth_return);
        // Get the returned json structure.
        JSONObject json = JSON.parseObject(auth_return);
        /**
         * access_token needed
         * {"access_token":"12_0g6UMlYeFtgCLT4TaGW5jS6bAt8MwxAoKYeyUmnHlqXMfICauOHMKs7k6HySOWTOhskV1BpLJ-syx3ZJbs922MWkVpuZqA_VpvL9CW7qLvs",
         * Effective time
         * "expires_in":7200,
         * "refresh_token":"12_JRqTvJnPVX_7ePOIK15qEJg_1oYvSdi4sqLzWWHyeK77LitTz-6XX1OYQjNH0rO54u-tDA_TKZTUaJKVFNXxsI5MtKE9P7_c2P6DeLF0pPU",
         * openid of the current user
         * "openid":"odXbo1Oub7qVBeptNt_kdtInQfLI",
         * "scope":"snsapi_base"
         * }
         */
        Object errorCode = json.get("errcode");
        if (errorCode != null) {
            return "400";
        } else {
            String openId = json.getString("openid");
            String access_token = json.getString("access_token");
            // Use access_token to exchange user details, avatars, names and other information.
            //userInfo_url=https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
            String userinfo_url = WeChatConfig.userInfo_url.replace("ACCESS_TOKEN", access_token).replace("OPENID", openId);
            String userinfoUrlReturn = WeixinHttpUtils.post(userinfo_url, null);
            /**
             * Last returned details
             * If the public number is bound to the open platform, it will return to unionid. If there is no binding, is there any parameter?
             * {
             * "sex":1,"nickname":"Cookie,
             * "unionid":"oTn_Ewte8QsnEIg9yWBSBzfCbBFE",
             * "privilege":[],"province":"Guangdong,
             * "openid":"odXbo1Oub7qVBeptNt_kdtInQfLI",
             * "language":"zh_CN",
             * "headimgurl":"http://thirdwx.qlogo.cn/mmopen/vi_32/WtxCbgVS8HKibRlpByx3FKdB9aibIyiboric9icqzOzH3aW5Ys7kJcDiaKkVllYybM5kiaIskC8GqEL3dib4VRsL3mn5RQ/132",
             * "country":"China "," city ": Guangzhou“
             * }
             */
            JSONObject userObj = JSON.parseObject(userinfoUrlReturn);
            log.info(userObj.toJSONString());
            request.getSession().setAttribute("checkTicketMyselfUser", userObj);
            request.getSession().setMaxInactiveInterval(0);
        }
        return "userinfo";
    }

Above.

Topics: JSON OkHttp