• 后端接口入参:
  1. code :临时登录凭证(必传)
  2. encryptedData:密文
  3. iv:偏移量
  • 控制层接口:
 @Action(value = "findWx")
public void findWx() throws IOException {
System.out.println("开始");
//小程序返回登录相关信息(自定义返回给小程序的信息)
RequestWxAppMsg msg = new RequestWxAppMsg();
msg.setCode(AppActionResultCode.CODE_FAILURE);
System.out.println("wxcode:" + code);
System.out.println("encryptedData:" + encryptedData);
System.out.println("iv:" + iv);
/*======================================================*/
//登录凭证不能为空
if (code == null || code.length() == 0) {
msg.setCode(AppActionResultCode.CODE_FAILURE);
System.out.println("登录凭证不能为空");
}
//小程序唯一标识 (在微信小程序管理后台获取)
String wxspAppid = "***************";
//小程序的 app secret (在微信小程序管理后台获取)
String wxspSecret = "***************";
//授权(必填)
String grant_type = 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);
//解析相应内容(转换成json对象)
JSONObject json = JSONObject.fromObject(sr);
//获取会话密钥(session_key)
String session_key = json.get("session_key").toString();
//用户的唯一标识(openid)
String openid = (String) json.get("openid");
//返回的数据
msg.setOpenId(openid);
System.out.println("请求成功获取openId以及会话密钥(如果不需要unionId以及手机号此刻可以直接结束返回openId)");
/*=========2、对encryptedData加密数据进行AES解密(unionId)========================*/
try {
String result = AesCbcUtil.decrypt(encryptedData, session_key, iv, "UTF-8");
System.out.println("解密结果:"+result);
if (null != result && result.length() > 0) {
JSONObject userInfoJSON = JSONObject.fromObject(result);
//返回的数据
msg.setUnionId((String) userInfoJSON.get("unionId"));
msg.setCode(AppActionResultCode.CODE_SUCCESS);
}
} catch (Exception e) {
e.printStackTrace();
}
/*=========2、对encryptedData加密数据进行AES解密(phone)========================*/
try {
String phone = AuthLoginUtil.getPhone(encryptedData,session_key,iv);
if(!phone.equals("")){
msg.setPhone(phone);
}
} catch (InvalidAlgorithmParameterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
doOutput(msg);
}
  • 发送请求的工具类HttpRequest:
 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;
}
}
  • 解密unionId的工具类AesCbcUtil:
 import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.security.spec.InvalidParameterSpecException; public class AesCbcUtil { static {
Security.addProvider(new BouncyCastleProvider());
} /**
* AES解密
*
* @param data //密文,被加密的数据
* @param key //秘钥
* @param iv //偏移量
* @param encodingFormat //解密后的结果需要进行的编码
* @return
* @throws Exception
*/
public static String decrypt(String data, String key, String iv, String encodingFormat) throws Exception {
//被加密的数据
byte[] dataByte = Base64.decodeBase64(data);
//加密秘钥
byte[] keyByte = Base64.decodeBase64(key);
//偏移量
byte[] ivByte = Base64.decodeBase64(iv);
try {
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, encodingFormat);
return result;
}
return null;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidParameterSpecException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} return null;
} }
  • 解密手机号的工具类AuthLoginUtil:
 import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import org.apache.tomcat.util.codec.binary.Base64;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject; public class AuthLoginUtil {
//解密得到电话号码
public static String getPhone(String encryptedData,String sessionKey,String iv) throws InvalidAlgorithmParameterException, UnsupportedEncodingException{
String phone="";
byte[] resultByte = AES.decrypt(Base64.decodeBase64(encryptedData),
Base64.decodeBase64(sessionKey),
Base64.decodeBase64(iv));
if (null != resultByte && resultByte.length > 0) {
String userInfo = new String(resultByte, "UTF-8");
System.out.println(userInfo);
JSONObject userJson =JSON.parseObject(userInfo);
phone = userJson.getString("phoneNumber");
System.out.println("电话:"+phone);
//解密成功
System.out.println("解密成功");
} else {
System.out.println("解密报错");
}
return phone;
}
}
  • 参考博客:
  1. https://blog.csdn.net/wujin274/article/details/76604964
  2. https://zhuanlan.zhihu.com/p/25124713
  • 注:解密手机号与unionId分别写在2个接口中(解密的入参不同),unionId解不出来要去检查一下你的微信开放平台(微信开放平台)是否有绑定微信小程序。
05-11 18:23