java的微信开发,先从环境配置开始。(当然先要注册微信公众号)先上个图
公众号握手原理图
可以看出开发的任务是自定义服务部分,微信服务器只不过是转发的桥梁。
所谓的握手就是在微信服务器转发请求时,第一次需要验证地址的合法性。
官方的开发文档还是很重要的
https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1465199793_BqlKA&token=&lang=zh_CN
验证(握手)的代码实现:
- 在Myeclipse中新建一个Servlet.但由于微信开发者平台配置要填写URL地址,这个URL就是微信服务器转发请求的地址,URL需要域名,可以用本机,也可以用第三方提供的服务器
- 验证需要几个参数,token(基本配置中填写,可任意字符)、timestamp、nonce
- 将 token、timestamp、nonce 然后通过一系列的算法加密之后得到密文;把明文与密文都传入指定的URL。
- 在传输的过程中如果数据没有被篡改的话.我们按照相同的流程进行加密.最后得到的结果肯定与signature相等.
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.jxy.util.SHA1;
public class WeiXinSerlvet extends HttpServlet {
private String token="world";
public WeiXinSerlvet() {
super();
}
public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
PrintWriter out = response.getWriter();
String signature = request.getParameter("signature");
//给服务器的几个参数
String timestamp = request.getParameter("timestamp");
String nonce = request.getParameter("nonce");
String echostr = request.getParameter("echostr");
String[] str={token,timestamp,nonce};
// 将token、timestamp、nonce三个参数进行字典序排序:
Arrays.sort(str);
String bigStr=str[0] + str[1] + str[2];
String signatureNew = new SHA1().getDigestOfString(bigStr.getBytes());
if(signature.equalsIgnoreCase(signatureNew)){
// 如果比对成功,则将随机字符串原样返回
out.write(echostr);
}else{
out.write("error");
}
out.flush();
out.close();
}
}
注意
signature.equalsIgnoreCase(signatureNew)
* 一定要不区分大小写比较.因为微信服务器在传入signature参数时已经转化了小写,否则验证会失败*