一、前言
最近一段时间都在进行公众号的开发,之前在实训的时候也开发过一次,但是过得太久早就忘记了如何做了,这次开发也是相当于重新开始,其实开发的步骤微信公众号开发文档上面写的也很清楚,所以总体来说开发的步骤也不是特别复杂。只要配置好需要的URL、TOKEN、和回调的域名就可以了。
二、开发过程
(1)配置服务器信息
在测试上面有两个重要信息。分别是appID 和 appsecret。这是开启公众号两个重要秘钥,一个公众号对应一个appID。有了这两个东西你就可以为所欲为为所欲为猥琐欲为了。
然后配置你的URL地址和token,其中URL是开发者用来接收微信消息和事件的接口URL。Token可由开发者可以任意填写,用作生成签名(该Token会和接口URL中包含的Token进行比对,从而验证安全性)。
URL作为开发接口,主要告诉公众号,这是属于自己的服务器,以后公众号接收到的信息都会给我的服务器。配置这个信息时,公众号会给这个接口发送一个GET请求,并要接受四个参数
开发者通过检验signature对请求进行校验(下面有校验方式)。若确认此次GET请求来自微信服务器,请原样返回echostr参数内容,则接入生效,成为开发者成功,否则接入失败。
此代码段是开放给公众号的接口。在这里接受GET请求的四个参数。
packagecom.itlink.servlet;importjava.io.IOException;importjava.io.PrintWriter;importjava.util.Calendar;importjava.util.Map;importjavax.servlet.ServletException;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importorg.junit.internal.runners.TestMethod;importcom.itlink.domain.TextMessage;importcom.itlink.utils.MessageUtil;importcom.itlink.utils.SignUtil;public class wx extendsHttpServlet {//private static final Logger logger = Logger.get
public voiddoGet(HttpServletRequest request, HttpServletResponse response)throwsServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
String signature= request.getParameter("signature");
String timestamp= request.getParameter("timestamp");
String nonce= request.getParameter("nonce");
String echostr= request.getParameter("echostr");if(echostr != null &&SignUtil.checkSignature(signature, timestamp, nonce)){
System.out.println("[signature: "+signature + "][timestamp: "+ timestamp+"][nonce: "+nonce+"][echostr: "+echostr+"]");
response.getOutputStream().println(echostr);
}
}public voiddoPost(HttpServletRequest request, HttpServletResponse response)throwsServletException, IOException {}
}
加密/校验流程如下:
1)将token、timestamp、nonce三个参数进行字典序排序
2)将三个参数字符串拼接成一个字符串进行sha1加密
3)开发者获得加密后的字符串可与signature对比,标识该请求来源于微信
packagecom.itlink.utils;importjava.security.MessageDigest;importjava.util.Arrays;public classSignUtil {private static String token = "activty";public static booleancheckSignature(String signature, String timestamp,
String nonce) {
String checktext= null;
Strin