微信小程序获取手机号流程
1.先调用微信登录wx.login()获取code,通过code在后台获取session_key和openid(为了安全方面的原因,请不要直接使用这些信息作为你小程序的用户标识和session标识回传到小程序客户端中去)
2.用户点击允许授权按钮,将后台获取的session_key 和 js获取的加密数据,做为参数和自定义标识传给后台
3.后台接收到参数后,进行加密数据解密算法,最后取得手机号
1.调用微信登录wx.login()获取code,通过code调用后台,获取信息sessionId
/**
* 获取微信小程序session_key
*
* @param jsonStr
* @return
*/
@RequestMapping(value = "/getSessionKey", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
@ResponseBody
public JSONObject getSessionKey(@RequestBody String jsonStr) {
JSONObject result = new JSONObject();
JSONObject object = JSON.parseObject(jsonStr);
String code = object.getString("code");
if (StringUtil.isBlank(code)) {
return ApiResult.fail("参数为空");
}
// appid
String appId ="" //公众号appid
// 微信密匙
String appSecret ="" //密匙
String res = SendHttps.sendGet("https://api.weixin.qq.com/sns/jscode2session", "appid=" + appId + "&secret=" + appSecret + "&js_code=" + code + "&grant_type=authorization_code");
net.sf.json.JSONObject resultObject = net.sf.json.JSONObject.fromObject(res);
if (resultObject.containsKey("errcode")) {
int errcode = resultObject.getInt("errcode");
result.put("message","获取access_token出错!错误信息为:" + resultObject.get("errmsg").toString(), "" + errcode);
} else {
String sessionKey = resultObject.get("session_key").toString();
String openId = resultObject.get("openid").toString();
RedisClient.set(openId + "session_key", sessionKey, 600);
result.put("sessionId", openId + "session_key");
}
return result;
}
2.前台通过js获取到微信服务器返回的加密数据,结合sessionId解密得到手机号。官方连接:https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/getPhoneNumber.html
/**
* 微信小程序获取手机号
*
* @param jsonStr
* @return
*/
@RequestMapping(value = "/getPhoneNumber", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
@ResponseBody
public JSONObject getPhoneNumber(@RequestBody String jsonStr) {
JSONObject object = JSON.parseObject(jsonStr);
String encryptedData = object.getString("encryptedData");
String iv = object.getString("iv");
String sessionId = object.getString("sessionId");
// 获取session_key
String session_key = RedisClient.get(sessionId);
if (StringUtil.isEmpty(session_key)) {
return ApiResult.fail("session已失效,请重试");
}
// 被加密的数据
byte[] dataByte = Base64.decode(encryptedData);
// 加密秘钥
byte[] keyByte = Base64.decode(session_key);
// 偏移量
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/PKCS5Padding");
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 "获取手机号失败";
}
3.后台通过url请求
public class SendHttps {
/**
* 向指定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(), "utf-8"));
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;
}
}