如何獲取微信openId

獲取微信openid

openid定義

爲了識別用戶,每一個用戶針對每一個公衆號會產生一個安全的OpenID,若是須要在多公衆號、移動應用之間作用戶共通,則需前往微信開放平臺,將這些公衆號和應用綁定到一個開放平臺帳號下,綁定後,一個用戶雖然對多個公衆號和應用有多個不一樣的OpenID。因此一個微信號在一個公衆號下的openid是不變的,若是換了一個對應的公衆號,那就是另外一個openid了。且只有在微信自帶瀏覽器中打開的項目纔可獲取到。html

準備條件

由於一個openid對應一個微信用戶一個公衆號,因此首先你要有一個公衆號,還有一個外網可訪問的域名,個人公衆號類型是企業號,這裏就以企業號爲例。前端

獲取openid須要的公衆號的 appid 和 secret(登錄公衆平臺 開發----->基本配置中的開發者ID(AppID)和 開發者密碼(AppSecret)就是)。web

5b2ca57c0c12b
5b2ca57c0c12b

其次是設置網頁受權域名(登錄公衆平臺 設置----->公衆號設置------>功能設置----->網頁受權域名 按步驟操做並設置就好),這個域名就是你獲取openid的web項目發佈的域名,這裏注意服務器請必定跑在80端口ajax

基本流程:

openid做爲用戶信息的一部分,要獲取到須要調用微信兩個開放受權接口,接口遵循OAuth 2.0協議。開放受權標準容許用戶讓第三方應用訪問該用戶在某一網站上存儲的私密的資源(如照片,視頻,聯繫人列表),而無需將用戶名和密碼提供給第三方應用,也就是咱們經常使用的微信登陸、微博登陸等等,英文好的同窗能夠看看OAuth 2.0 Authorization Frameworkjson

我整理了一下總體的流程,畫了一個時序圖。後端

[圖片上傳失敗...(image-88fd53-1530609529394)][圖片上傳失敗...(image-dbf507-1530609470358)]api

其中兩次調用了微信嗯驗證服務器。瀏覽器

  1. 調用open.weixin.qq.com/connect/oau… 接口獲取到code,注意這個接口只獲取openid,scope參數設置爲snsapi_base,這樣不須要用戶確認和關注公衆號。

不知道你有沒有疑問,爲何不直接獲取openId,還須要獲取一個code呢?安全

是由於code至關於一個臨時票據,可以驗證失效時間、可獲取信息的內容、微信用戶、appid等等。bash

  1. 獲得code做爲一個參數,加上appId和appsecret,調用api.weixin.qq.com/sns/oauth2/… 接口獲取到openid。

注意,appsecret是比較重要的參數要放到後臺進行請求。返回的重要參數又openId和access_token,用openId和access_token能夠獲取用戶的基本信息,位置性別等等等,咱們這裏只講獲取openId,原理相似,想看參考微信網頁受權

代碼

前端

function openId(){
	    //測試
	    var callbackUrl = link.skip + itemId;
	    var appid = link.appid;
	    var redirect_uri = encodeURI(callbackUrl);
		var code = requestUtil.getParameter('code');
	    if (code && localStorage.getItem('code') != code) {
	      //微信回調含code調用免登錄接口,不然跳轉微信驗證
	      $.ajax({
	        type: 'get',
	        url: link.path+"/v1/wechatUser/info?code=" + code,
	        async: false,
	        success: function (res) {
				if(res.code == 1000) {
					localStorage.setItem('code', code);
					var openId = res.data.openId;
					localStorage.setItem('openId', openId);
				}
	        }
	      });
	    } else {
	      	window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + appid + '&redirect_uri=' + redirect_uri  + '&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect';
	    }
	}
複製代碼

後端

public void getOpenId(HttpServletRequest request, HttpServletResponse response,String code) throws UnsupportedEncodingException {
        response.setContentType("text/html");
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        Map params = new HashMap();
        params.put("secret", "");
        params.put("appid", "");
        params.put("grant_type", "authorization_code");
        params.put("code", code);
        String result = HttpGetUtil.httpRequestToString(
                "https://api.weixin.qq.com/sns/oauth2/access_token", params);
        JSONObject jsonObject = JSONObject.parseObject(result);

        String openid = jsonObject.get("openid").toString();
        System.out.println("獲得的openid爲:"+openid);
    }
複製代碼
static class HttpGetUtil {

        public static String httpRequestToString(String url,
                                                 Map params) {
            String result = null;
            try {
                InputStream is = httpRequestToStream(url,  params);
                BufferedReader in = new BufferedReader(new InputStreamReader(is,
                        "UTF-8"));
                StringBuffer buffer = new StringBuffer();
                String line = "";
                while ((line = in.readLine()) != null) {
                    buffer.append(line);
                }
                result = buffer.toString();
            } catch (Exception e) {
                return null;
            }
            return result;
        }

        private static InputStream httpRequestToStream(String url,
                                                       Map params) {
            InputStream is = null;
            try {
                String parameters = "";
                boolean hasParams = false;
                for(String key : params.keySet()){
                    String value = URLEncoder.encode(params.get(key), "UTF-8");
                    parameters += key +"="+ value +"&";
                    hasParams = true;
                }
                if(hasParams){
                    parameters = parameters.substring(0, parameters.length()-1);
                }

                url += "?"+ parameters;

                URL u = new URL(url);
                HttpURLConnection conn = (HttpURLConnection) u.openConnection();
                conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                conn.setRequestProperty("Accept-Charset", "UTF-8");
                conn.setRequestProperty("contentType", "utf-8");
                conn.setConnectTimeout(50000);
                conn.setReadTimeout(50000);
                conn.setDoInput(true);
                //設置請求方式,默認爲GET
                conn.setRequestMethod("GET");

                is = conn.getInputStream();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return is;
        }

    }
複製代碼

問題補充

authorize接口:

  1. authorize接口,只能經過微信,或者微信開發這工具打開(須要加開發權限)。

access_token接口:

  1. 若是返回40163錯誤,是由於code已經被用過,code只有一次生命,用完做廢。若是出現了code請檢查一下接口1相關的代碼,是否是對code進行了保存等等。

感謝

感謝各位看完這篇文章,若是有問題或不清楚直接留言,或者加vx34108314。

相關文章
相關標籤/搜索