獲取微信用戶的openId

 

第一步:用戶贊成受權,獲取code 引導用戶進入受權的URL 修改一些參數

在確保微信公衆帳號擁有受權做用域(scope參數)的權限的前提下(服務號得到高級接口後,默認帶有scope參數中的snsapi_base和snsapi_userinfo),引導關注者打開以下頁面:本做者用菜單的方式引導用戶點擊進入。json

https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect

個人代碼以下:一個Servlet請求 獲取codeapi

/**
     * 根據code取得openId
     * 
     * @param appid   公衆號的惟一標識
     * @param secret    公衆號的appsecret密鑰
     * @param code    code爲換取access_token的票據          
     * @return 
     */public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //參數
        String code = request.getParameter("code");

        
        if(null != code && !"".equals(code)){
            log.info("==============[OAuthServlet]獲取網頁受權code不爲空,code="+code);
            //根據code換取openId
            OAuthInfo oa = WeixinUtil.getOAuthOpenId(Constants.appId,Constants.appSecret,code);
            UserInfo info = WeixinUtil.getUserInfo(oa.getAccessToken(), oa.getOpenId());
            if(!"".equals(oa) && null != oa){
                 request.setAttribute("openid", oa.getOpenId());
                 request.setAttribute("nickname", info.getNickname());
                 request.getRequestDispatcher("/index.jsp").forward(request, response);
                 
            }else{
                log.info("==============[OAuthServlet]獲取網頁受權openId失敗!");
            }
        }else{
            log.info("==============[OAuthServlet]獲取網頁受權code失敗!");
        }
    }

替換相應的APPID APPSECRET SCOPE微信

第二步:經過code換取網頁受權access_token  這裏的access_token與基礎獲取的access_token不一樣

獲取code後,請求如下連接獲取access_token: 
https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code

具體作法與上面基本一致。更換相對應的值。須要注意的是code能夠寫一個Servlet獲取。String code = request.getParameter("code");get/post均可以。app

這樣子就會返回一下json格式數據jsp

{
   "access_token":"ACCESS_TOKEN",
   "expires_in":7200,
   "refresh_token":"REFRESH_TOKEN",
   "openid":"OPENID",
   "scope":"SCOPE"
}

具體代碼以下。獲取的code換取的access_token post

https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code;
    public static OAuthInfo getOAuthOpenId(String appid, String secret, String code ) {
        OAuthInfo oAuthInfo = null;
        String o_auth_openid_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code;";
        String requestUrl = o_auth_openid_url.replace("APPID", appid).replace("SECRET", secret).replace("CODE", code);
       
        JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
        
        //oAuthInfo是做者本身把那幾個屬性參數寫在一個類裏面了。
        // 若是請求成功
        if (null != jsonObject) {
            try {
                oAuthInfo = new OAuthInfo();
                oAuthInfo.setAccessToken(jsonObject.getString("access_token"));
                oAuthInfo.setExpiresIn(jsonObject.getInt("expires_in"));
                oAuthInfo.setRefreshToken(jsonObject.getString("refresh_token"));
                oAuthInfo.setOpenId(jsonObject.getString("openid"));
                oAuthInfo.setScope(jsonObject.getString("scope"));
            } catch (JSONException e) {
                oAuthInfo = null;
                // 獲取token失敗
                log.error("網頁受權獲取openId失敗 errcode:{} errmsg:{}", jsonObject
                        .getInt("errcode"), jsonObject.getString("errmsg"));
            }
        }
        return oAuthInfo;
    }

根據上面代碼獲取的access_token  openid 而後再請求獲取userinfo的接口。就能獲得微信用戶的全部信息了。url

這就獲取到用戶的openid。應用受權做用域,snsapi_base (不彈出受權頁面,直接跳轉,只能獲取用戶openid),snsapi_userinfo (彈出受權頁面,可經過openid拿到暱稱、性別、所在地。而且,即便在未關注的狀況下,只要用戶受權,也能獲取其信息)我本身用的做用域爲snsapi_userinfo。用戶點擊跳轉頁面爲spa

https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect

替換連接裏面的大寫字母的信息爲你本身公衆號的。state能夠不改。code

寫一個Servlet專門接收傳遞過來的code。進行相應的操做。token

1.OAuthServlet 對code進行access——token的驗證

2.一個Servlet的方法調用接口地址。獲得相應code。

3.OAuthInfo 返回數據相應的參數的PO類。set/get方法

4.WeiXinUtil添加一個方法 publicOAuth  getOAuthInfo(String appid, String secret, String code)獲得json格式。並使用JSONObject讀取出本身想要的數據。

 

參考微信文檔地址:https://mp.weixin.qq.com/paymch/readtemplate?t=mp/business/course3_tmpl&lang=zh_CN

相關文章
相關標籤/搜索