微信公眾號開發(一) 提供自己的url給微信伺服器進行驗證
阿新 • • 發佈:2019-02-20
俗話說,萬事開頭難。對於剛剛接觸微信公眾號開發的小白來說,進行伺服器驗證往往難住了一大片開發者。在這裡為大家展示一下我的驗證方法。希望能幫助到大家!
1、需要擁有自己的伺服器。在這裡我使用的是ngrok內網對映工具,雖然效能不穩定,但勝在簡單、方便。
注意:微信服務端需要使用者提供的埠必須是80埠。
2、填寫token,這個是開發者自己任意填寫的。
3、後端關鍵程式碼
@ResponseBody @RequestMapping(value = "test") public void checkSignature(HttpServletRequest request, HttpServletResponse response) throws Exception{ String signature = request.getParameter("signature"); String timestamp = request.getParameter("timestamp"); String nonce = request.getParameter("nonce"); String echostr = request.getParameter("echostr"); PrintWriter out = response.getWriter(); if(CheckUtil.checkSignature(signature, timestamp, nonce)){ //如果校驗成功,將得到的隨機字串原路返回 out.print(echostr); } }
package com.nk.wechat; import java.security.MessageDigest; import java.util.Arrays; import com.nk.common.Constant; /** * 接收來自微信伺服器端的驗證 * * @author jj * */ public class CheckUtil { public static boolean checkSignature(String signature, String timestamp, String nonce) { //1.定義陣列存放tooken,timestamp,nonce String[] arr = {Constant.wechat_token,timestamp,nonce}; //2.對陣列進行排序 Arrays.sort(arr); //3.生成字串 StringBuffer sb = new StringBuffer(); for(String s : arr){ sb.append(s); } //4.sha1加密 String temp = getSha1(sb.toString()); //5.將加密後的字串,與微信傳來的加密簽名比較,返回結果 return temp.equals(signature); } /** * sha1加密 * * http://blog.csdn.net/guanhang89/article/details/51259283 * * @param str * @return */ public static String getSha1(String str){ if(str==null||str.length()==0){ return null; } char hexDigits[] = {'0','1','2','3','4','5','6','7','8','9', 'a','b','c','d','e','f'}; try { MessageDigest mdTemp = MessageDigest.getInstance("SHA1"); mdTemp.update(str.getBytes("UTF-8")); byte[] md = mdTemp.digest(); int j = md.length; char buf[] = new char[j*2]; int k = 0; for (int i = 0; i < j; i++) { byte byte0 = md[i]; buf[k++] = hexDigits[byte0 >>> 4 & 0xf]; buf[k++] = hexDigits[byte0 & 0xf]; } return new String(buf); } catch (Exception e) { return null; } } }
就是這麼簡單,希望對讀者有幫助。