1. 程式人生 > >java微信授權獲取OPENID,ACCESS_TOKEN,用戶信息

java微信授權獲取OPENID,ACCESS_TOKEN,用戶信息

err parameter static onf 唯一標識 leg let ava 接口

獲取微信的openId流程

1.獲取微信code

  

  使用接口 : appId 是當前開發者的appId 不是用戶的

        path 是回調地址

     這個鏈接是授權鏈接,當重定向這個鏈接的時候,會展示授權頁,點擊授權之後 跳入你path的請求接口 回調中帶了一個參數code獲取到就行

https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appId+"&redirect_uri="+path+"&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect
@RequestMapping(value = "/scanCode")
    public String scanCode(Integer id, HttpServletRequest request){
        String path = AdvancedUtil.authorization(WeiXinConfig.WEB_APPID, Activity.getAuthorizationUrl(request), Activity.getAuthorizationParam(id));
        return "redirect:" + path;
    }
String code = request.getParameter("code");

獲取openId和access_token

/**
     * 獲取網頁授權憑證
     * 
     * @param appId 公眾賬號的唯一標識
     * @param appSecret 公眾賬號的密鑰
     * @param code
     * @return WeixinAouth2Token
     */
    public static WeixinOauth2Token getOauth2AccessToken(String appId, String appSecret, String code) {
        WeixinOauth2Token wat 
= null; // 拼接請求地址 String requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code"; requestUrl = requestUrl.replace("APPID", appId); requestUrl = requestUrl.replace("SECRET", appSecret); requestUrl = requestUrl.replace("CODE", code); // 獲取網頁授權憑證 JSONObject jsonObject = CommonUtil.httpsRequest(requestUrl, "GET", null); if (null != jsonObject) { try { wat = new WeixinOauth2Token(); wat.setAccessToken (jsonObject.getString("access_token")); wat.setExpiresIn (jsonObject.getInt("expires_in")); wat.setRefreshToken (jsonObject.getString("refresh_token")); wat.setOpenId (jsonObject.getString("openid")); wat.setScope (jsonObject.getString("scope")); } catch (Exception e) { wat = null; int errorCode = jsonObject.getInt("errcode"); String errorMsg = jsonObject.getString("errmsg"); log.error("獲取網頁授權憑證失敗 errcode:{} errmsg:{}", errorCode, errorMsg); } } return wat; }
/**
     * 刷新網頁授權憑證
     * 
     * @param appId 公眾賬號的唯一標識
     * @param refreshToken
     * @return WeixinAouth2Token
     */
    public static WeixinOauth2Token refreshOauth2AccessToken(String appId, String refreshToken) {
        WeixinOauth2Token wat = null;
        // 拼接請求地址
        String requestUrl     = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=APPID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN";
        requestUrl             = requestUrl.replace("APPID", appId);
        requestUrl             = requestUrl.replace("REFRESH_TOKEN", refreshToken);
        // 刷新網頁授權憑證
        JSONObject jsonObject = CommonUtil.httpsRequest(requestUrl, "GET", null);
        if (null != jsonObject) {
            try {
                wat = new WeixinOauth2Token();
                wat.setAccessToken    (jsonObject.getString("access_token"));
                wat.setExpiresIn    (jsonObject.getInt("expires_in"));
                wat.setRefreshToken    (jsonObject.getString("refresh_token"));
                wat.setOpenId        (jsonObject.getString("openid"));
                wat.setScope        (jsonObject.getString("scope"));
            } catch (Exception e) {
                wat = null;
                int errorCode = jsonObject.getInt("errcode");
                String errorMsg = jsonObject.getString("errmsg");
                log.error("刷新網頁授權憑證失敗 errcode:{} errmsg:{}", errorCode, errorMsg);
            }
        }
        return wat;
    }
/**
     * 通過網頁授權獲取用戶信息
     * @param accessToken 網頁授權接口調用憑證
     * @param openId 用戶標識
     * @return SNSUserInfo
     */
    @SuppressWarnings( { "deprecation", "unchecked" })
    public static SNSUserInfo getSNSUserInfo(String accessToken, String openId) {
        SNSUserInfo snsUserInfo = null;
        // 拼接請求地址
        String requestUrl         = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID";
        requestUrl                   = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);
        // 通過網頁授權獲取用戶信息
        JSONObject jsonObject     = CommonUtil.httpsRequest(requestUrl, "GET", null);

        if (null != jsonObject) {
            try {
                snsUserInfo = new SNSUserInfo();
                // 用戶的標識
                snsUserInfo.setOpenId(jsonObject.getString("openid"));
                // 昵稱
                snsUserInfo.setNickname(jsonObject.getString("nickname"));
                // 性別(1是男性,2是女性,0是未知)
                snsUserInfo.setSex(jsonObject.getInt("sex"));
                // 用戶所在國家
                snsUserInfo.setCountry(jsonObject.getString("country"));
                // 用戶所在省份
                snsUserInfo.setProvince(jsonObject.getString("province"));
                // 用戶所在城市
                snsUserInfo.setCity(jsonObject.getString("city"));
                // 用戶頭像
                snsUserInfo.setHeadImgUrl(jsonObject.getString("headimgurl"));
                // 用戶特權信息
                snsUserInfo.setPrivilegeList(JSONArray.toList(jsonObject.getJSONArray("privilege"), List.class));
            } catch (Exception e) {
                snsUserInfo = null;
                int errorCode = jsonObject.getInt("errcode");
                String errorMsg = jsonObject.getString("errmsg");
                log.error("獲取用戶信息失敗 errcode:{} errmsg:{}", errorCode, errorMsg);
            }
        }
        return snsUserInfo;
    }

java微信授權獲取OPENID,ACCESS_TOKEN,用戶信息