微信公众平台官方开发文档:http://mp.weixin.qq.com/wiki/index.php?title=接入指南
正文内容
个人理解:微信服务器发送信息(包含Token内容)到这里填写的URL地址,然后我们接受到信息通过某种方式验证,是否是来着微信服务器的信息,从而进行处理。
URL填写:服务器地址+servlet的名字 注:servlet的名称结尾最好是.do,案例:http://www.xiaoyaoge.com/WeiXinServlet.do
Token值:随便填写一般在开发习惯使用为weixin,在开发结束后一定要换掉。
个人理解:微信服务器通过GET请求发送过来信息包含四个参数分别是signature、timestamp、nonce、echostr,我们利用微信中填写的Token值、获取的参数timestamp、nonce三个值按照上面方式排序、加密等与signature比较,如果一样就返回参数值echostr,这时接入就生效,可以与微信服务器发送与传递信息。
java代码(token、timestamp、nonce的加密、排序方式)
/**
* 微信接口验证֤
* */
public boolean checkSignature(HttpServletRequest request, HttpServletResponse response){
String signature = request.getParameter("signature");
log.info("signature Value:"+signature);
String timestamp = request.getParameter("timestamp");
log.info("timestamp Value:"+timestamp);
String nonce = request.getParameter("nonce");
log.info("nonce Value:"+nonce);
String[] tmpArr={useValue.token,timestamp,nonce};
Arrays.sort(tmpArr);
String tmpStr=this.ArrayToString(tmpArr);
tmpStr=this.SHA1Encode(tmpStr);
log.info("tmpStr Value:"+tmpStr);
if(tmpStr.equalsIgnoreCase(signature)){
log.info("checkSignature method is successful!");
return true;
}else{
log.info("checkSignature method is fail!");
return false;
}
}
//数组转字符串
protected String ArrayToString(String [] arr){
StringBuffer bf = new StringBuffer();
for(int i = 0; i < arr.length; i++){
bf.append(arr[i]);
}
return bf.toString();
}
//sha1加密
protected String SHA1Encode(String sourceString) {
String resultString = null;
try {
resultString = new String(sourceString);
MessageDigest md = MessageDigest.getInstance("SHA-1");
resultString = byte2hexString(md.digest(resultString.getBytes()));
} catch (Exception ex) {
}
return resultString;
}
protected final String byte2hexString(byte[] bytes) {
StringBuffer buf = new StringBuffer(bytes.length * 2);
for (int i = 0; i < bytes.length; i++) {
if (((int) bytes[i] & 0xff) < 0x10) {
buf.append("0");
}
buf.append(Long.toString((int) bytes[i] & 0xff, 16));
}
return buf.toString().toUpperCase();
}
//从输入流读取post参数
protected String readStreamParameter(ServletInputStream in){
StringBuilder buffer = new StringBuilder();
BufferedReader reader=null;
try{
reader = new BufferedReader(new InputStreamReader(in));
String line=null;
while((line = reader.readLine())!=null){
buffer.append(line);
}
}catch(Exception e){
e.printStackTrace();
}finally{
if(null!=reader){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return buffer.toString();
}
加入我们群一起学习吧!
群号:171816014(微信开发设计)群里有java项目代码