小程序獲取openid

大體流程是小程序通過登錄獲取code(用戶登錄憑證,官方文檔地址:https://developers.weixin.qq.com/miniprogram/dev/api/wx.login.html ),然後訪問自己的服務器,注意是自己的服務器,在服務器端按照code2Session的說明返回從服務器端獲得的openid給小程序前端(官方文檔地址:https://developers.weixin.qq.com/miniprogram/dev/api/code2Session.html)


小程序端代碼:

//***.js
wx.login({
        success(res) {
          if (res.code) {
            wx.request({
              url: '自己的服務器地址',
              data: {
                code: res.code
              },
              success: function(res) {
                console.log(res.data.openid)
               //服務器端獲得是openid就是一個鍵值對,這裏沒有在服務器端處理直接
               //返回前端處理,可以先在服務器端處理只返回openid也是可以的
              },
              fail: function() {
                console.log("請求失敗")
              }
            })
          } else {
            console.log('登錄失敗!')
          }
        }
      })

服務器端(javaweb):

//code就是小程序從前端傳過來的
private String login(String code) throws Exception {
       String AppID = "自己的AppID";
       String AppSecret="自己的AppSecret";//這兩個都可以從微信公衆平臺中查找
		String url = "https://api.weixin.qq.com/sns/jscode2session?appid="
				+ AppID + "&secret=" + AppSecret + "&js_code="
				+ code + "&grant_type=authorization_code";
		URL reqURL = new URL(url);
		HttpsURLConnection openConnection = (HttpsURLConnection) reqURL
				.openConnection();
		openConnection.setConnectTimeout(10000);
		//這裏我感覺獲取openid的時間比較長,不過也可能是我網絡的問題,
		//所以設置的響應時間比較長
		openConnection.connect();
		InputStream in = openConnection.getInputStream();

		StringBuilder builder = new StringBuilder();
		BufferedReader bufreader = new BufferedReader(new InputStreamReader(in));
		for (String temp = bufreader.readLine(); temp != null; temp = bufreader
				.readLine()) {
			builder.append(temp);
		}
		
		String result = builder.toString();
		in.close();
		openConnection.disconnect();
		return result;
		//result就是包含openid的鍵值對,返回給小程序前端即可
	}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章