小程序開發文檔:https://mp.weixin.qq.com/debug/wxadoc/dev/
參考文章:http://www.jb51.net/article/117352.htm
微信小程序登錄獲取用戶信息
WeChaConnView.java
@RestController
@RequestMapping(value = "/wechat")
public class WeChaConnView {
/**
* 解密用戶敏感數據
*
* @param encryptedData 明文,加密數據
* @param iv 加密算法的初始向量
* @param code 用戶允許登錄後,回調內容會帶上 code(有效期五分鐘),開發者需要將 code 發送到開發者服務器後臺,使用code 換取 session_key api,將 code 換成 openid 和 session_key
* @return
*/
@ResponseBody
@RequestMapping(value = "/decodeUser", method = RequestMethod.POST)
public DataResponse decodeUser(@RequestParam("encryptedData")String encryptedData,
@RequestParam("iv")String iv,
@RequestParam("code")String code) {
DataResponse response = new DataResponse();
Map<String, Object> map = new HashMap<>();
//登錄憑證不能爲空
if (code == null || code.length() == 0) {
/*map.put("status", 0);
map.put("msg", "code 不能爲空");
return map;*/
response.setResult_code("failed");
response.setResult_msg("code 不能爲空");
return response;
}
//小程序唯一標識 (在微信小程序管理後臺獲取)
String wxspAppid = "xxxxxx";
//小程序的 app secret (在微信小程序管理後臺獲取)
String wxspSecret = "xxxxxx";
//授權(必填)
String grant_type = "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);
//解析相應內容(轉換成json對象)
Gson gson = new Gson();
JsonObject json = gson.fromJson(sr, JsonObject.class);
System.out.println(json);
// JSONObject json = JSONObject.fromObject(sr);
if (json.get("session_key") == null) {
/*map.put("status", 0);
map.put("msg", "解密失敗");
return map;*/
response.setResult_code("failed");
response.setResult_msg("解密失敗:" + json.get("errmsg").toString().replaceAll("\"", ""));
return response;
}
//獲取會話密鑰(session_key)
String session_key = json.get("session_key").toString();
//用戶的唯一標識(openid)
// String openid = (String) json.get("openid");
String openid = json.get("openid").toString();
//////////////// 2、對encryptedData加密數據進行AES解密 ////////////////
try {
String result = AesCbcUtil.decrypt(encryptedData, session_key, iv, "UTF-8");
if (null != result && result.length() > 0) {
/*map.put("status", 1);
map.put("msg", "解密成功"); */
JsonObject userInfoJSON = gson.fromJson(result, JsonObject.class);
// JSONObject userInfoJSON = JSONObject.fromObject(result);
System.out.println("user: " + userInfoJSON);
Map<String, Object> userInfo = new HashMap<>();
userInfo.put("openId", openid.replaceAll("\"", ""));
userInfo.put("phoneNumber", userInfoJSON.get("phoneNumber").toString().replaceAll("\"", ""));
userInfo.put("purePhoneNumber", userInfoJSON.get("purePhoneNumber").toString().replaceAll("\"", ""));
userInfo.put("countryCode", userInfoJSON.get("countryCode").toString().replaceAll("\"", ""));
map.put("userInfo", userInfo);
System.out.println("map: " + map);
response.setResult_code("success");
response.setResult_msg("解密成功");
response.setData(userInfo);
return response;
}
} catch (Exception e) {
e.printStackTrace();
}
/*map.put("status", 0);
map.put("msg", "解密失敗");
return map;*/
response.setResult_code("failed");
response.setResult_msg("解密失敗");
return response;
}
}
返回結果封裝類DataResponse.java
package com.hi.util;
/**
* Created by Andy on 16/11/15.
*
* 返回數據封裝
*/
public class DataResponse {
//信息詳情
private String result_msg;
//成功失敗信息
private String result_code;
//公共通知編碼
private String result_num;
private PageInfo page;
private Object data;
public DataResponse(){}
public DataResponse(Object data){
this.data = data;
}
public DataResponse(String result_code,String result_msg){
this.result_code = result_code;
this.result_msg = result_msg;
}
public DataResponse(String result_code,String result_msg,String result_num){
this.result_code = result_code;
this.result_msg = result_msg;
this.result_num = result_num;
}
public String getResult_num() {
return result_num;
}
public void setResult_num(String result_num) {
this.result_num = result_num;
}
public String getResult_msg() {
return result_msg;
}
public void setResult_msg(String result_msg) {
this.result_msg = result_msg;
}
public String getResult_code() {
return result_code;
}
public void setResult_code(String result_code) {
this.result_code = result_code;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public PageInfo getPage() {
return page;
}
public void setPage(PageInfo page) {
this.page = page;
}
}
Http請求封裝類HttpRequest.java
package com.hi.util.http;
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;
/**
* Created by lsh on 2017/6/22.
*/
public class HttpRequest {
/**
* 向指定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;
}
}
對返回用戶信息進行加密解密的工具類AesCbcUtil.java
package com.hi.util;
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;
/**
* Created by lsh
* AES-128-CBC 加密方式
* 注:
* AES-128-CBC可以自己定義“密鑰”和“偏移量“。
* AES-128是jdk自動生成的“密鑰”。
*/
public class AesCbcUtil {
static {
//BouncyCastle是一個開源的加解密解決方案,主頁在http://www.bouncycastle.org/
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 {
// initialize();
//被加密的數據
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;
}
}
至此,Java獲取微信用戶信息的功能完成。