<pre name="code" class="java">1.由於微信的大熱,爲了更好的方便使用微信的用戶查詢一些信息,這篇文章是入門級的微信公衆平臺開發教程,需要的朋友可以參考下
簡介
公衆平臺消息接口爲開發者提供了一種新的消息處理方式。
申請消息接口
點擊申請,填寫網址url和token,其中token可由開發者可以任意填寫,用作生成簽名。
網址接入
公衆平臺用戶提交信息後,微信服務器將發送GET請求到填寫的URL上,並且帶上四個參數:
參數 | 描述 |
---|---|
signature | 微信加密簽名 |
timestamp | 時間戳 |
nonce | 隨機數 |
echostr | 隨機字符串 |
開發者通過檢驗signature對請求進行校驗(下面有校驗方式)。若確認此次GET請求來自微信服務器,請原樣返回echostr參數內容,則接入生效,否則接入失敗。
signature結合了開發者填寫的token參數和請求中的timestamp參數、nonce參數。
加密/校驗流程: 1. 將token、timestamp、nonce三個參數進行字典序排序 2. 將三個參數字符串拼接成一個字符串進行sha1加密 3. 開發者獲得加密後的字符串可與signature對比,標識該請求來源於微信1.程序驗證代碼如下
@RequestMapping("/index")
public String weixinService(HttpServletRequest request,
HttpServletResponse response) {
try {
String method = request.getMethod();
if ("GET".equals(method)) {
String signature = request.getParameter("signature");
String timestamp = request.getParameter("timestamp");
String nonce = request.getParameter("nonce");
String echostr = request.getParameter("echostr");
String token = request.getParameter("token");
if (echostr != null && !"".equals(echostr)) {
echostr = checkAuthentication(signature, timestamp, nonce,echostr,token);
// 驗證通過返回隨即字串
response.getWriter().write(echostr);
response.getWriter().flush();
}
} else {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
// 調用核心業務類接收消息、處理消息
String respMessage = coreService.processRequest(request);
// 響應消息
if (null != respMessage) {
response.getWriter().write(respMessage);
response.getWriter().flush();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* Function:微信驗證方法
*
* @author JLC
* @param signature
* 微信加密簽名
* @param timestamp
* 時間戳
* @param nonce
* 隨機數
* @param echostr
* 隨機字符串
* @return
*/
private String checkAuthentication(String signature, String timestamp,
String nonce, String echostr,String token) {
String result = "";
// 將獲取到的參數放入數組
String[] ArrTmp = { token, timestamp, nonce };
// 按微信提供的方法,對數據內容進行排序
Arrays.sort(ArrTmp);
StringBuffer sb = new StringBuffer();
for (int i = 0; i < ArrTmp.length; i++) {
sb.append(ArrTmp[i]);
}
// 對排序後的字符串進行SHA-1加密
String pwd = Encrypt(sb.toString());
if (pwd.equals(signature)) {
try {
result = echostr;
} catch (Exception e) {
e.printStackTrace();
}
} else {
System.out.println("微信平臺簽名消息驗證失敗!");
}
return result;
}
/**
* 用SHA-1算法加密字符串並返回16進制串
* @param strSrc
* @return
*/
private String Encrypt(String strSrc) {
MessageDigest md = null;
String strDes = null;
byte[] bt = strSrc.getBytes();
try {
md = MessageDigest.getInstance("SHA-1");
md.update(bt);
strDes = bytes2Hex(md.digest());
} catch (NoSuchAlgorithmException e) {
System.out.println("錯誤");
return null;
}
return strDes;
}
private String bytes2Hex(byte[] bts) {
String des = "";
String tmp = null;
for (int i = 0; i < bts.length; i++) {
tmp = (Integer.toHexString(bts[i] & 0xFF));
if (tmp.length() == 1) {
des += "0";
}
des += tmp;
}
return des;
}