`

微信平台申请消息接口时Signature校验的Servlet实现

阅读更多
看到一个朋友弄了微信公众帐号,我自己也弄了一个。根据说明,要想成为开发者,需要有一个自己的网站,并且处理校验一个微信传来的GET请求。我就按要求弄了一个。
具体的要求如下:
http://mp.weixin.qq.com/wiki/index.php?title=消息接口指南

下面是我的实现。先写一个Servlet
package me.gimli.wx.echo;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import me.gimli.wx.util.SignatureChecker;

@SuppressWarnings("serial")
public class EchoServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		
		String signature = req.getParameter("signature");
		String timestamp = req.getParameter("timestamp");
		String nonce = req.getParameter("nonce");
		String echostr = req.getParameter("echostr");
		
		SignatureChecker checker = new SignatureChecker();
		
		if (checker.checkSigature(signature, timestamp, nonce)){
			resp.getWriter().print(echostr);
		}else {
			resp.getWriter().print("validation failed. Bye");
		}
		
	}

		
}




SignatureChecker 工具类:


package me.gimli.wx.util;

import java.security.MessageDigest;
import java.util.Arrays;

public class SignatureChecker {

	public boolean checkSigature(String signature,String timestamp,String nonce){
		
		//Define token
		String token = "ABC123def456";
		
		//Sort array
		String[] tmparr = {token,timestamp,nonce};
		try {
			Arrays.sort(tmparr);
		} catch (NullPointerException e){
			return false;
		}
		
		//implode array
		StringBuilder builder = new StringBuilder();
		for (int i=0;i<tmparr.length;i++){
			builder.append(tmparr[i]);
		}
		String raw = builder.toString();
		
		//SHA-1
	    MessageDigest md = null;
	    byte[] b = null;
	    try {
	        md = MessageDigest.getInstance("SHA-1");
	        b = md.digest(raw.getBytes("UTF-8"));
	    }
	    catch(Exception e) {
	        e.printStackTrace();
	    } 
	    
	    //Turn sha-1 result to HexString
		String result = "";
		for (int i=0; i < b.length; i++) {
		    result += Integer.toString( ( b[i] & 0xff ) + 0x100, 16).substring( 1 );
		}
		
		//Compare and return
		if (result.equals(signature)){
			return true;
		}else{
			return false;
		}		
	}
}





然后再在web.xml中部署上就可以了
  <servlet>
  	<servlet-name>echo</servlet-name>
  	<servlet-class>me.gimli.wx.echo.EchoServlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
  	<servlet-name>echo</servlet-name>
  	<url-pattern>/saldar/*</url-pattern>
  </servlet-mapping>


最后以微信广告语结束:再小的个体,也有自己的品牌。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics