微信小程序授權 獲取用戶的openid和session_key…

謝謝這個博主:(解密+post大家可以看這個博主的代碼)https://blog.csdn.net/guochanof/article/details/80189935

微信服務端api:https://developers.weixin.qq.com/miniprogram/dev/api-backend/auth.code2Session.html

請求微信api接口:GET https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code

1.根據前端用戶授權即會產生一個code用戶登陸時獲取的標識(這個code的聲明週期是存活5分鐘,5分鐘過後就沒用了)。

2.開發者服務器即我獲取到前端傳過來的code,另外還有3個固定的一個是appid(小程序的appid)、secret(小程序appSecret)、grant_type(授權類型,authorization_code)

3.根據2中的code+appid+secret+grant_type調用微信api接口返回的是JSON數據包:openid(用戶唯一標識)、session_key(會話密鑰)

a:首先我定義一個常量類,裏面寫有appid、secret、authorization_code這三個是固定不變的,也可以是前臺傳過來的。

/**
 *
 * 用於微信授權:固定不變的常量
 *
 * */

public class WeiXin {

    public static final String APPID = "xxxxxx";

    public static final String APP_SECRECT = "xxxxxx";

    public static final String AUTHORIZATION_CODE = "authorization_code";

}

添加一個工具類即獲取資源路徑的工具

b、HttpRequest.java 工具類 (整段複製即可無需修改)

package com.zzh.demo.base.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

public class HttpRequest {

    public static void main(String[] args) {
        //發送 GET 請求
        String s=HttpRequest.sendGet("http://v.qq.com/x/cover/kvehb7okfxqstmc.html?vid=e01957zem6o", "");
        System.out.println(s);

//        //發送 POST 請求
//        String sr=HttpRequest.sendPost("http://www.toutiao.com/stream/widget/local_weather/data/?city=%E4%B8%8A%E6%B5%B7", "");
//        JSONObject json = JSONObject.fromObject(sr);
//        System.out.println(json.get("data"));
    }

    /**
     * 向指定URL發送GET方法的請求
     *
     * @param url
     *            發送請求的URL
     * @param param
     *            請求參數,請求參數應該是 name1=value1&name2=value2 的形式。
     * @return 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;
    }

    /**
     * 向指定 URL 發送POST方法的請求
     *
     * @param url
     *            發送請求的 URL
     * @param param
     *            請求參數,請求參數應該是 name1=value1&name2=value2 的形式。
     * @return 所代表遠程資源的響應結果
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打開和URL之間的連接
            URLConnection conn = realUrl.openConnection();
            // 設置通用的請求屬性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 發送POST請求必須設置如下兩行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 獲取URLConnection對象對應的輸出流
            out = new PrintWriter(conn.getOutputStream());
            // 發送請求參數
            out.print(param);
            // flush輸出流的緩衝
            out.flush();
            // 定義BufferedReader輸入流來讀取URL的響應
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("發送 POST 請求出現異常!"+e);
            e.printStackTrace();
        }
        //使用finally塊來關閉輸出流、輸入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }
}

C:這個類裏我把code寫死了目的是爲了便於測試是否能獲取到微信服務器的用戶唯一標識openid和會話密鑰session_key
注意一下:要導入這個包字符串轉json格式數據時

import org.json.JSONObject;
下面是代碼:

import com.zzh.demo.base.common.WeiXin;
import com.zzh.demo.base.utils.HttpRequest;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/api/Autozi")
public class TestWxAuthorization {
    /**
         * @Title: decodeUserInfo
         * @author:lizheng
         * @date:2018年3月25日
         * @Description: 解密用戶敏感數據

     * @return
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    @RequestMapping(value = "/decodeUserInfo", method = RequestMethod.GET)
    @ResponseBody
    public Map decodeUserInfo() {

        Map map = new HashMap();

        /////////////////////////////////////////////////////////////////////////自己定義的code

        String code = "xxxxxxx";

        // 登錄憑證不能爲空
        if (code == null || code.length() == 0) {
            map.put("status", 0);
            map.put("msg", "code 不能爲空");
            return map;
        }

        // 小程序唯一標識 (在微信小程序管理後臺獲取)
        String wxspAppid = WeiXin.APPID;
        // 小程序的 app secret (在微信小程序管理後臺獲取)
        String wxspSecret = WeiXin.APP_SECRECT;
        // 授權(必填)
        String grant_type = WeiXin.AUTHORIZATION_CODE;

        //////////////// 1、向微信服務器 使用登錄憑證 code 獲取 session_key 和 openid
        // 請求參數
        String params = "appid=" + wxspAppid + "&secret=" + wxspSecret + "&js_code=" + code + "&grant_type="
                + grant_type;
        // 發送請求
        String sr = HttpRequest.sendGet("https://api.weixin.qq.com/sns/jscode2session", params);


        //////////////// 2、對encryptedData加密數據進行AES解密 ////////////////
        try {
            // 解析相應內容(轉換成json對象)
            JSONObject json = new JSONObject(sr);
            // 獲取會話密鑰(session_key)
            String session_key = json.get("session_key").toString();
            // 用戶的唯一標識(openid)
            String openid = (String) json.get("openid").toString();



            map.put( "session_key",session_key);
            map.put( "openId",openid );
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

}

原文鏈接:https://www.cnblogs.com/wym591273/p/10802970.html
如有疑問請與原作者聯繫

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