微信小程序之獲取用戶openid

獲取openid分兩種方法,一種直接在小程序裏獲取,另一種在後臺獲取

1.小程序中獲取openid

onLaunch: function () {
     var user=wx.getStorageSync('user') || {};  
     var userInfo=wx.getStorageSync('userInfo') || {}; 
     if((!user.openid || (user.expires_in || Date.now()) < (Date.now() + 600))&&(!userInfo.nickName)){ 
        wx.login({  
        success: function(res){ 
            if(res.code) {
                wx.getUserInfo({
                    success: function (res) {
                        app.globalData.userInfo = res.userInfo//微信用戶的暱稱頭像信息
                    }
                });

                wx.request({  
                    url: 'https://api.weixin.qq.com/sns/jscode2session?appid='+app.globalData.appid+'&secret='+app.globalData.secret+'&js_code='+res.code+'&grant_type=authorization_code',  
                    data: {},  
                    method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT  
                    // header: {}, // 設置請求的 header  
                    success: function(res){ 
                       
                       var openids = res.data.openid //返回openid
                        console.log('openid爲' + openids);
                        app.globalData.openId = openids
                    }  
                });
            }else {
                console.log('獲取用戶登錄態失敗!' + res.errMsg)
            }          
        }  
      }); 
    } 
   },

2.後臺獲取openid(這裏用的java代碼)

 /**
	     * 向指定URL發送GET方法的請求
	     *
	     * @param url
	     *            發送請求的URL
	     * @param param
	     *            請求參數,請求參數應該是 name1=value1&name2=value2 的形式。
	     * [url=home.php?mod=space&uid=67594]@Return[/url] URL 所代表遠程資源的響應結果
	     */
	    public static String sendGet(String url, String param) {
	        String result = "";
	        BufferedReader in = null;
	        try {
	            String urlNameString = url + "?" + param;
	            URL realUrl = new URL(urlNameString);
	            // 打開和URL之間的連接
	            URLConnection connection = realUrl.openConnection();
	            // 設置通用的請求屬性
	            connection.setRequestProperty("accept", "*/*");
	            connection.setRequestProperty("connection", "Keep-Alive");
	            connection.setRequestProperty("user-agent",
	                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
	            // 建立實際的連接
	            connection.connect();
	            // 獲取所有響應頭字段
	            Map<String, List<String>> map = connection.getHeaderFields();
	            // 遍歷所有的響應頭字段
	            for (String key : map.keySet()) {
	                System.out.println(key + "--->" + map.get(key));
	            }
	            // 定義 BufferedReader輸入流來讀取URL的響應
	            in = new BufferedReader(new InputStreamReader(
	                    connection.getInputStream()));
	            String line;
	            while ((line = in.readLine()) != null) {
	                result += line;
	            }
	        } catch (Exception e) {
	            System.out.println("發送GET請求出現異常!" + e);
	            e.printStackTrace();
	        }
	        // 使用finally塊來關閉輸入流
	        finally {
	            try {
	                if (in != null) {
	                    in.close();
	                }
	            } catch (Exception e2) {
	                e2.printStackTrace();
	            }
	        }
	        return result;
	    }

public static void main(String[] args) {

		  String params = "appid=appid&secret=secret&js_code=js_code&grant_type=authorization_code";
		    //發送請求
		    String sr = sendGet("https://api.weixin.qq.com/sns/jscode2session", params);
		    //解析相應內容(轉換成json對象)
		    JSONObject json = JSONObject.fromObject(sr);
		    System.out.println(json.toString());//openid在json中
		 	
	}

這裏的appid、secret和js_code都是從小程序傳過來的,這裏說明一下,我測試的時候使用頁面獲取openid正常,但是小程序上線後用頁面獲取openid拿不到值,所以改用後臺獲取了,後臺獲取openid是線上線下都可以的,你們可以結合自身情況測試

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