微信开发——3、微信接入(javaweb)

来源:互联网 发布:柯洁评论黑嘉嘉 知乎 编辑:程序博客网 时间:2024/06/02 04:24

简单说明:可以参考微信公众平台的开发文档:百度搜素“微信公众平台”,进入官网后,点击“开发者工具”—”开发者文档”—“开始开发”—“接入指南”(可以从接入指南开始看),这里主要说服务器的代码,具体操作可以看开发文档。

所用的技术为servlet,如果想看懂下述代码需要一定的servlet基础。可参考 http://blog.csdn.net/zhengyikuangge/article/details/50581952


验证主代码如下:

/*     * check.do 验证消息的确来自微信服务器     */    public void check(HttpServletRequest req, HttpServletResponse resp)            throws IOException {            /* token写入自己设置的token即可 */        String token = Common.token, timestamp = "", nonce = "", signature = "", echostr = "";        try {            timestamp = req.getParameter("timestamp");            nonce = req.getParameter("nonce");            signature = req.getParameter("signature");            echostr = req.getParameter("echostr");            System.out.println("获取的数据如下:");            System.out.println("token=" + token + ";timestamp=" + timestamp                    + ",nonce=" + nonce + ",signature=" + signature                    + ",echostr=" + echostr);            boolean if_check_pass = SignUtil.checkSignature(signature,                    timestamp, nonce);                    /* checkSignature方法在下面 */            if (if_check_pass) {                System.out.println("验证通过");                PrintWriter pw = resp.getWriter();                /* 这里和微信开发者文档有点出入,这里返回echostr即可 */                pw.print(echostr);                System.out.println("提交完成!!!!!");                pw.close();            } else {                System.out.println("验证失败");            }        } catch (NullPointerException e) {            System.out.println("获取数据出错");        } catch (IOException e) {            e.printStackTrace();        }        resp.getWriter().print("");    }

注:绑定URL后在公众号上做的操作,例如点击菜单、发送信息等,都会给这个URL发送数据。微信接入绑定的时候也会给这个URL发送数据,要注意做好判断。我会在第4篇博客中具体说明。另外注意绑定的URL的端口限制,推荐使用ngrok外网映射工具


checkSignature方法代码如下:

public static boolean checkSignature(String signature, String timestamp,            String nonce) {        // 将传入参数变成一个String数组然后进行字典排序        String[] arr = new String[] { Common.token, timestamp, nonce };        Arrays.sort(arr);        // 创建一个对象储存排序后三个String的结合体        StringBuilder content = new StringBuilder();        for (int i = 0; i < arr.length; i++) {            content.append(arr[i]);        }        // 启动sha1加密法的工具        MessageDigest md = null;        String tmpStr = null;        try {            md = MessageDigest.getInstance("SHA-1");            // md.digest()方法必须作用于字节数组            byte[] digest = md.digest(content.toString().getBytes());            // 将字节数组弄成字符串            tmpStr = byteToStr(digest);        } catch (NoSuchAlgorithmException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        content = null;        return tmpStr != null ? tmpStr.equals(signature.toUpperCase()) : false;    }

注:这个方法是从网上复制粘贴的,据测试后能用

原创粉丝点击