1. 程式人生 > >微信公眾號開發之開發者模式驗證

微信公眾號開發之開發者模式驗證

可用測試號進行開發測試

1.填寫伺服器配置(我使用測試號進行開發的),如下圖所示


2.驗證訊息來自微信伺服器

傳送請求,請求地址:http://cmy.ngrok.xiaomiqiu.cn/wechat/chat (自己在微信中配置的URL地址,微信公眾號介面必須以http://或https://開頭,分別支援80埠和443埠)可進行內網穿透,具體可百度(我使用的小米球,測試完全ok)


具體驗證請求程式碼如下:

@Controller
@RequestMapping("/wechat")
public class WxController {

    private final static String MEDIATYPE_CHARSET_JSON_UTF8 = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8";
    @RequestMapping(value = "/chat", method = {RequestMethod.GET, RequestMethod.POST}, produces = MEDIATYPE_CHARSET_JSON_UTF8)
    public void get(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //如果為get請求,則為開發者模式驗證
        if ("get".equals(request.getMethod().toLowerCase())) {
            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);
            }
        }else{
            doPost();//具體程式碼之後文章會有講解
        }
    }
}

驗證工具類CheckUtil.java

public class CheckUtil {
    public static final String  token = "xiaodou"; //開發者自行定義Token

    public static boolean checkSignature(String signature,String timestamp,String nonce){
        //1.定義陣列存放tooken,timestamp,nonce
        String[] arr = {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);
    }

    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) {
            // TODO: handle exception
            return null;
        }
    }
}

執行程式碼,在測試號輸入對應的URL和Token,點選提交。

出現配置成功字樣,則表明已進入開發者模式,可以開始開發了。