1. 程式人生 > >微信公眾平臺 java 接入 1

微信公眾平臺 java 接入 1

/**

*

* 微信驗證token

*

*/

@RequestMapping(value = "/verifyToken", method = RequestMethod.GET)

public void verifyToken(HttpServletRequest request, HttpServletResponse response) throws Exception {

PrintWriter out = null;

try{

// 隨機字串

String echostr = request.getParameter("echostr");

if(echostr!=null){

// 微信加密簽名

String signature = request.getParameter("signature");

// 時間戮

String timestamp = request.getParameter("timestamp");

// 隨機數

String nonce = request.getParameter("nonce");

out = response.getWriter();

// 通過檢驗 signature 對請求進行校驗,若校驗成功則原樣返回 echostr,表示接入成功,否則接入失敗

if (checkSignature(signature, timestamp, nonce

)) {

logger.info("echostrresult", echostr);

out.print(echostr);

}

}

}catch(Exception e){

e.printStackTrace();

}finally{

out.close();

out = null;

}

}

/**

* 驗證簽名

*

* @param signature

* @param timestamp

* @param nonce

* @return

*/

public static boolean checkSignature(String signature, String timestamp

, String nonce) {

String[] arr = new String[] { token, timestamp, nonce };

// 將 token, timestamp, nonce 三個引數進行字典排序

sort(arr);

StringBuilder content = new StringBuilder();

for (int i = 0; i < arr.length; i++) {

content.append(arr[i]);

}

MessageDigest md = null;

String tmpStr = null;

try {

md = MessageDigest.getInstance("SHA-1");

// 將三個引數字串拼接成一個字串進行 shal 加密

byte[] digest = md.digest(content.toString().getBytes());

tmpStr = byteToStr(digest);

} catch (NoSuchAlgorithmException e) {

e.printStackTrace();

}

content = null;

// 將sha1加密後的字串可與signature對比,標識該請求來源於微信

return tmpStr != null ? tmpStr.equals(signature.toUpperCase()) : false;

}

/**

* 將位元組陣列轉換為十六進位制字串

*

* @param digest

* @return

*/

private static String byteToStr(byte[] digest) {

String strDigest = "";

for (int i = 0; i < digest.length; i++) {

strDigest += byteToHexStr(digest[i]);

}

return strDigest;

}

/**

* 將位元組轉換為十六進位制字串

*

* @param b

* @return

*/

private static String byteToHexStr(byte b) {

char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

char[] tempArr = new char[2];

tempArr[0] = Digit[(b >>> 4) & 0X0F];

tempArr[1] = Digit[b & 0X0F];

String s = new String(tempArr);

return s;

}

public static void sort(String a[]) {

for (int i = 0; i < a.length - 1; i++) {

for (int j = i + 1; j < a.length; j++) {

if (a[j].compareTo(a[i]) < 0) {

String temp = a[i];

a[i] = a[j];

a[j] = temp;

}

}

}

}