微信公众平台接入java示例代码

来源:互联网 发布:java api怎么导入 编辑:程序博客网 时间:2024/05/16 10:55

第一步:申请消息接口

需要申请消息接口,很简单只需要在微信公众平台后台填写Servlet地址即可,这里不多说。

第二步:验证URL有效性

需要编写URL有效性验证代码,这里以Java代码做示例,官网已给出PHP示例

开发者提交信息后,微信服务器将发送GET请求到填写的URL上,GET请求携带四个参数:

参数描述signature微信加密签名,signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。timestamp时间戳nonce随机数echostr随机字符串

开发者通过检验signature对请求进行校验(下面有校验方式)。若确认此次GET请求来自微信服务器,请原样返回echostr参数内容,则接入生效,成为开发者成功,否则接入失败。
加密/校验流程如下:

1. 将token、timestamp、nonce三个参数进行字典序排序
2. 将三个参数字符串拼接成一个字符串进行sha1加密
3. 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信

[java] 预览复制
  1. /** 
  2.   * 微信公众平台 成为开发者验证入口 
  3.   *  
  4.   * @param request 
  5.   *            the request send by the client to the server 
  6.   * @param response 
  7.   *            the response send by the server to the client 
  8.   * @throws ServletException 
  9.   *             if an error occurred 
  10.   * @throws IOException 
  11.   *             if an error occurred 
  12.   */  
  13.  public void doGet(HttpServletRequest request, HttpServletResponse response)  
  14.          throws ServletException, IOException {  
  15.   
  16.      // 微信加密签名  
  17.      String signature = request.getParameter("signature");  
  18.      // 随机字符串  
  19.      String echostr = request.getParameter("echostr");  
  20.      // 时间戳  
  21.      String timestamp = request.getParameter("timestamp");  
  22.      // 随机数  
  23.      String nonce = request.getParameter("nonce");  
  24.   
  25.      String[] str = { TOKEN, timestamp, nonce };  
  26.      Arrays.sort(str); // 字典序排序  
  27.      String bigStr = str[0] + str[1] + str[2];  
  28.      // SHA1加密  
  29.      String digest = new SHA1().getDigestOfString(bigStr.getBytes())  
  30.              .toLowerCase();  
  31.   
  32.      // 确认请求来至微信  
  33.      if (digest.equals(signature)) {  
  34.          response.getWriter().print(echostr);  
  35.      }  
  36.  }  
0 0