小程序 獲取openid unionid

1.根據wx.login獲取codejava

2.根據code獲取openid session_key  encryptedData  ivapi

3.根據session_key  encryptedData  iv  獲取unionidcookie

 

1.session

wx.login({app

success: res => {ide

// 發送 res.code 到後臺換取 openId, sessionKey, unionId工具

var that = this;post

var code = res.code;//登陸憑證 code獲取openid只能使用一次ui

}this

})

 

wx.getUserInfo({

success: function (res) {

var encryptedData = res.encryptedData;

var iv = res.iv;

}

})

String params = "appid = appid&secret=secret&js_code=code&grant_type=authorization_code";
String sr = HttpRequest.sendGet("https://api.weixin.qq.com/sns/jscode2session", params);

獲取到session_key

String m = decrypt2(encryptedData, sessionKey, iv, "UTF-8");

{"openId":"","nickName":"李破","gender":1,"language":"zh_CN","city":"Wuhan","province":"Hubei","country":"China","avatarUrl":"https://wx.qlogo.cn/mmopen/vi_32/1iaXQDdbeiaLMRlTUoNLOVtkTVutT8zibTOakCia1zAfFibF1Re8jr6qj4Bu8d8T46V1GGnzJB0mdo4adLjL7BdI1vw/132","unionId":"","watermark":{"timestamp":1527841103,"appid":""}}

//相關方法

 

public static String decrypt2(String encryptedData, String sessionKey, String iv, String encodingFormat)
        throws Exception {
    // 被加密的數據
    byte[] dataByte = Base64.decode(encryptedData);
    // 加密祕鑰
    byte[] keyByte = Base64.decode(sessionKey);
    // 偏移量
    byte[] ivByte = Base64.decode(iv);
    try {
        // 若是密鑰不足16位,那麼就補足. 這個if 中的內容很重要
        int base = 16;
        if (keyByte.length % base != 0) {
            int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
            byte[] temp = new byte[groups * base];
            Arrays.fill(temp, (byte) 0);
            System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
            keyByte = temp;
        }
        // 初始化
        Security.addProvider(new BouncyCastleProvider());
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
        SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
        AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
        parameters.init(new IvParameterSpec(ivByte));
        cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
        byte[] resultByte = cipher.doFinal(dataByte);
        if (null != resultByte && resultByte.length > 0) {
            String result = new String(resultByte, "UTF-8");
            System.out.print(result);
        }

    }finally {
        return null;
    }

}

 

//工具類

package com.yhhvip.utils.WxUtil;

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

public class HttpUtil {
    //private static final Log logger = Logs.get();
    private final static int CONNECT_TIMEOUT = 5000; // in milliseconds
    private final static String DEFAULT_ENCODING = "UTF-8";

    public static String postData(String urlStr, String data){
        return postData(urlStr, data, null);
    }

    public static String postData(String urlStr, String data, String contentType){
        BufferedReader reader = null;
        try {
            URL url = new URL(urlStr);
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            conn.setConnectTimeout(CONNECT_TIMEOUT);
            conn.setReadTimeout(CONNECT_TIMEOUT);
            if(contentType != null)
                conn.setRequestProperty("content-type", contentType);
            OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), DEFAULT_ENCODING);
            if(data == null)
                data = "";
            writer.write(data);
            writer.flush();
            writer.close();

            reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), DEFAULT_ENCODING));
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
                sb.append("\r\n");
            }
            return sb.toString();
        } catch (IOException e) {
            //logger.error("Error connecting to " + urlStr + ": " + e.getMessage());
        } finally {
            try {
                if (reader != null)
                    reader.close();
            } catch (IOException e) {
            }
        }
        return null;
    }
    public static String SendGET(String url,String param){
        String result="";//訪問返回結果
        BufferedReader read=null;//讀取訪問結果

        try {
            //建立url
            URL realurl=new URL(url+"?"+param);
            //打開鏈接
            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();
            // 遍歷全部的響應頭字段,獲取到cookies等
//                     for (String key : map.keySet()) {
//                         log.info(key + "--->" + map.get(key));
//                     }
            // 定義 BufferedReader輸入流來讀取URL的響應
            read = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(),"UTF-8"));
            String line;//循環讀取
            while ((line = read.readLine()) != null) {
                result += line;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(read!=null){//關閉流
                try {
                    read.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return result;
    }

}

相關文章
相關標籤/搜索