1. 程式人生 > >微信小程式通過CODE換取session_key和openid

微信小程式通過CODE換取session_key和openid

微信小程式的使用者資訊獲取需要請求微信的伺服器,通過小程式提供的API在小程式端獲取CODE,然後將CODE傳入到我們自己的伺服器,用我們的伺服器來換取session_key和openid。

小程式端比較簡單,從教程的API部分把程式碼拷貝到小程式裡就好了,這裡將提供一個javaweb伺服器端換取session_key和openid的程式碼示例

@Value("${weixin.app_id}") // spring配置檔案配置了appID
    private String appId;
    
    @Value("${weixin.app_secret}") // spring配置檔案配置了secret
    private String secret;
    
    @RequestMapping("/openId")
    @ResponseBody
    public Map<String, Object> openId(String code){ // 小程式端獲取的CODE
        Map<String, Object> result = new HashMap<>();
        result.put("code", 0);
        try {
            boolean check = (StringUtils.isEmpty(code)) ? true : false;
            if (check) {
                throw new Exception("引數異常");
            }
            StringBuilder urlPath = new StringBuilder("https://api.weixin.qq.com/sns/jscode2session"); // 微信提供的API,這裡最好也放在配置檔案
            urlPath.append(String.format("?appid=%s", appId));
            urlPath.append(String.format("&secret=%s", secret));
            urlPath.append(String.format("&js_code=%s", code));
            urlPath.append(String.format("&grant_type=%s", "authorization_code")); // 固定值
            String data = HttpUtils.sendHttpRequestPOST(urlPath.toString(), "utf-8", "POST"); // java的網路請求,這裡是我自己封裝的一個工具包,返回字串
            System.out.println("請求結果:" + data);
            String openId = new JSONObject(data).getString("openid");
            System.out.println("獲得openId: " + openId);
            result.put("openId", openId);
        } catch (Exception e) {
            result.put("code", 1);
            result.put("remark", e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

請求以上這個控制器將返回openId,注意data中還有session_key也可以從這裡取出來使用,至於JSON的處理方式,根據自己專案中的jar包更改程式碼即可。