Java实现微信小程序登录授权

一般的微信小程序登录都会先前端调用wx.login生成code传给后端,后端通过code获取到openid和session_key并返回给前端,前端调用wx.getUserInfo获取对象参数等信息。

Java实现微信小程序登录授权_第1张图片

由于需求问题,我所写的小程序登录直接由前端调用wx.login生成code,wx.getUserProfile获取到iv和encrytedData作为参数进行接口调用。

在这里要注意wx.getUserInfo和wx.getUserProfile做出了调整,具体调整可查看小程序登录、用户信息相关接口调整说明 | 微信开放社区

//通过code获取微信授权信息
            String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + AuthUtil.APPID +"&secret=" + AuthUtil.APPSECRET + "&js_code=" + code + "&grant_type=authorization_code";
JSONObject jsonObject = AuthUtil.doGetJson(url);
String openId = jsonObject.getString("openid");
String sessionKey = jsonObject.getString("session_key");
JSONObject obj = new AuthUtil().getUserInfo(encryptedData, sessionKey, iv);

APPID和APPAECRET通过登录小程序开发平台获取,前后端务必保持一致。

/**
 * 微信授权登录调用Util
 */
public class AuthUtil {
    public static final String APPID = "*****";//自己的微信APPID
    public static final String APPSECRET = "*****";//自己的微信APPSECRET
 
    public static JSONObject doGetJson(String URL) throws IOException {
        JSONObject jsonObject = null;
        HttpURLConnection conn = null;
        InputStream is = null;
        BufferedReader br = null;
        StringBuilder result = new StringBuilder();
        try {
            //创建远程url连接对象
            java.net.URL url = new URL(URL);
            //通过远程url连接对象打开一个连接,强转成HTTPURLConnection类
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            //设置连接超时时间和读取超时时间
            conn.setConnectTimeout(15000);
            conn.setReadTimeout(60000);
            conn.setRequestProperty("Accept", "application/json");
            //发送请求
            conn.connect();
            //通过conn取得输入流,并使用Reader读取
            if (200 == conn.getResponseCode()) {
                is = conn.getInputStream();
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                String line;
                while ((line = br.readLine()) != null) {
                    result.append(line);
                }
            } else {
                System.out.println("ResponseCode is an error code:" + conn.getResponseCode());
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
                if (is != null) {
                    is.close();
                }
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
            conn.disconnect();
        }
        jsonObject = JSONObject.parseObject(result.toString());
        return jsonObject;
    }
 
    public static JSONObject getUserInfo(String encryptedData, String sessionKey, String iv){
        // 被加密的数据
        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","BC");
            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");
                return JSONObject.parseObject(result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
 
}

以上,就完成了! 

转载自微信小程序登录授权_Aguai229的博客-CSDN博客_微信小程序登录授权

感谢!

你可能感兴趣的:(Java,微信小程序,小程序)