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

/ 1评 / 4

如果有疑问或者有更好的写法,欢迎大家留言

根据微信公众平台接入指南给出的接入方法:

第一步:申请消息接口

需要申请消息接口,很简单只需要在微信公众平台后台填写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对比,标识该请求来源于微信

/**
 * 微信公众平台 成为开发者验证入口
 * 
 * @param request
 *            the request send by the client to the server
 * @param response
 *            the response send by the server to the client
 * @throws ServletException
 *             if an error occurred
 * @throws IOException
 *             if an error occurred
 */
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    // 微信加密签名
    String signature = request.getParameter("signature");
    // 随机字符串
    String echostr = request.getParameter("echostr");
    // 时间戳
    String timestamp = request.getParameter("timestamp");
    // 随机数
    String nonce = request.getParameter("nonce");

    String[] str = { TOKEN, timestamp, nonce };
    Arrays.sort(str); // 字典序排序
    String bigStr = str[0] + str[1] + str[2];
    // SHA1加密
    String digest = new SHA1().getDigestOfString(bigStr.getBytes())
            .toLowerCase();

    // 确认请求来至微信
    if (digest.equals(signature)) {
        response.getWriter().print(echostr);
    }
}

SHA1.java 下载

  1. […] 为了确保正确获取微信服务器的POST数据,首先要成功接入,微信公众平台接入可以参考:微信公众平台接入Java示例代码 […]

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注