微信官方授權及獲取OpenId的方法,服務器通過SpringBoot實現

主要步驟:

  1. 前端獲取到code(wx.login),傳入服務器
  2. 服務器通過參數AppID和AppSecret訪問官方接口,獲取到OpenId
  3. 服務器將OpenId進行相應的業務處理並返回給前端

在服務器訪問微信官方接口: https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code

主要邏輯流程如下:
image

後臺Java實現如下:

public static String getWXProfile(String code) throws JSONException {
        //請求參數
        String params = "appid=" + StaticData.appId + "&secret=" + StaticData.appSecret + "&js_code=" + code + "&grant_type=authorization_code";
        //發送請求
        String sr = sendGet("https://api.weixin.qq.com/sns/jscode2session", params);
        //解析相應內容(轉換成json對象)
        JSONObject json = new JSONObject(sr);

        //獲取會話密鑰(session_key)
        String session_key = json.get("session_key").toString();
        //用戶的唯一標識(openid)
        String openId = (String) json.get("openid");
        return openId;
    }
    
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;
    }

#親測有效

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