
JAVA微信公眾號開發TOKEN驗證失敗怎么辦?
JAVA微信公眾號開發TOKEN驗證失敗的解決辦法:
微信公眾平臺服務器配置時,需要引入token,但是提交的時候總是提示token驗證失敗,是因為微信后臺并未檢測到你代碼中有驗證token的代碼,那么應該按照官方文檔對token進行驗證,驗證后再將結果返回微信公眾平臺即可。
驗證的代碼為:
public class SignUtil {
private static String token = "WnbVm6GTQj4BPmLliSday4K";//這里是自定義的token,需和你提交的token一致
/**
* 校驗簽名
*
* @param signature 簽名
* @param timestamp 時間戳
* @param nonce 隨機數
* @return 布爾值
*/
public static boolean checkSignature(String signature, String timestamp, String nonce) {
String checktext = null;
if (null != signature) {
// 對ToKen,timestamp,nonce 按字典排序
String[] paramArr = new String[] { token, timestamp, nonce };
Arrays.sort(paramArr);
try {
MessageDigest md = MessageDigest.getInstance("SHA-1");
// 對接后的字符串進行sha1加密
byte[] digest = md.digest(content.toString().getBytes());
checktext = byteToStr(digest);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
// 將加密后的字符串與signature進行對比
return checktext != null ? checktext.equals(signature.toUpperCase()) : false;
}
/**
* 將字節數組轉化為16進制字符串
*
* @param byteArrays 字符數組
* @return 字符串
*/
private static String byteToStr(byte[] byteArrays) {
String str = "";
for (int i = 0; i < byteArrays.length; i++) {
str += byteToHexStr(byteArrays[i]);
}
return str;
}
/**
* 將字節轉化為十六進制字符串
*
* @param myByte 字節
* @return 字符串
*/
private static String byteToHexStr(byte myByte) {
char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
char[] tampArr = new char[2];
tampArr[0] = Digit[(myByte >>> 4) & 0X0F];
tampArr[1] = Digit[myByte & 0X0F];
String str = new String(tampArr);
return str;
}
}提交時公眾平臺會請求你的地址,并校驗你是否在后臺做了驗證,驗證部分:
if (StringUtils.isNotBlank(request.getParameter("signature"))) {
String signature = request.getParameter("signature");
String timestamp = request.getParameter("timestamp");
String nonce = request.getParameter("nonce");
String echostr = request.getParameter("echostr");
LOGGER.info("signature[{}], timestamp[{}], nonce[{}], echostr[{}]", signature, timestamp, nonce, echostr);
if (SignUtil.checkSignature(signature, timestamp, nonce)) {
LOGGER.info("數據源為微信后臺,將echostr[{}]返回!", echostr);
response.getOutputStream().println(echostr);
}
}以上就是JAVA微信公眾號開發TOKEN驗證失敗的解決辦法。






