微信小程序的用戶信息獲取需要請求微信的服務器,通過小程序提供的API在小程序端獲取CODE,然后將CODE傳入到我們自己的服務器,用我們的服務器來換取session_key和openid。
小程序端比較簡單,從教程的API部分把代碼拷貝到小程序里就好了,這里將提供一個javaweb服務器端換取session_key和openid的代碼示例
1 @Value("${weixin.app_id}") // spring配置文件配置了appID 2 private String appId; 3 4 @Value("${weixin.app_secret}") // spring配置文件配置了secret 5 private String secret; 6 7 @RequestMapping("/openId") 8 @ResponseBody 9 public Map<String, Object> openId(String code){ // 小程序端獲取的CODE 10 Map<String, Object> result = new HashMap<>(); 11 result.put("code", 0); 12 try { 13 boolean check = (StringUtils.isEmpty(code)) ? true : false; 14 if (check) { 15 throw new Exception("參數異常"); 16 } 17 StringBuilder urlPath = new StringBuilder("https://api.weixin.qq.com/sns/jscode2session"); // 微信提供的API,這里最好也放在配置文件 18 urlPath.append(String.format("?appid=%s", appId)); 19 urlPath.append(String.format("&secret=%s", secret)); 20 urlPath.append(String.format("&js_code=%s", code)); 21 urlPath.append(String.format("&grant_type=%s", "authorization_code")); // 固定值 22 String data = HttpUtils.sendHttpRequestPOST(urlPath.toString(), "utf-8", "POST"); // java的網絡請求,這里是我自己封裝的一個工具包,返回字符串 23 System.out.println("請求結果:" + data); 24 String openId = new JSONObject(data).getString("openid"); 25 System.out.println("獲得openId: " + openId); 26 result.put("openId", openId); 27 } catch (Exception e) { 28 result.put("code", 1); 29 result.put("remark", e.getMessage()); 30 e.printStackTrace(); 31 } 32 return result; 33 }
請求以上這個控制器將返回openId,注意data中還有session_key也可以從這里取出來使用,至於JSON的處理方式,根據自己項目中的jar包更改代碼即可。
