Spring boot 獲取微信用戶信息

@ApiOperation(value="微信登陸",notes="微信登陸")
    @ResponseBody
    @RequestMapping(value="/login",method= RequestMethod.GET)
    public void wxCallBack(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //獲取access_token
        String code = request.getParameter("code");
        SysUserEntity dto=null;
        Object user=null;
        MsgEntity msg=new MsgEntity();
        log.info("回調方法....獲取用戶信息註冊");
        log.info(code);
        String  avatar="";
         System.out.println("沒有user:"+user);
        log.info(env.getProperty("wxopen.appid"));
        log.info(env.getProperty("wxpay.appsecret"));
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid=" + env.getProperty("wxlog.appid") +
                "&secret=" + env.getProperty("wxlog.appsecret") +
                "&code=" + code +
                "&grant_type=authorization_code";
        log.info(url);
        String result =  MyHttpUtils.doPost(url, "", Charset.forName("UTF-8").toString());

        System.out.println("請求獲取access_token:" + result);
        //返回結果的json對象
        JSONObject resultObject = JSON.parseObject(result);

        SessionUtil.setSessionAttribute("OAuthAccessTokenStartTime", new Date());
        SessionUtil.setSessionAttribute("OAuthAccessToken", resultObject.getString("access_token"));
        //請求獲取userInfo
        String infoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                "?access_token=" + resultObject.getString("access_token") +
                "&openid=" + resultObject.getString("openid") +
                "&lang=zh_CN";
        String resultInfo = MyHttpUtils.doPost(infoUrl, "", Charset.forName("UTF-8").toString());
        JSONObject userMessageJsonObject = JSON.parseObject(resultInfo);
        System.out.println(userMessageJsonObject);

        if (userMessageJsonObject != null) {
            try {

                //此時已獲取到userInfo,再根據業務進行處理
                System.out.println("請求獲取userInfo:" + userMessageJsonObject);
                //用戶暱稱
                String username = userMessageJsonObject.getString("nickname");
                username = EmojiUtils.emojiChange(username);
                //進行解碼
                System.out.println("username"+username);
                String nickname = userMessageJsonObject.getString("nickname");
                System.out.println("nickname"+nickname);
}}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章