慕课网-初识Java微信公众号开发

来源:互联网 发布:阿里云域名备案号查询 编辑:程序博客网 时间:2024/06/06 13:18

微信开发源代码:

http://download.csdn.net/detail/fulq1234/9811270

里面有ngrok的exe文件


微信开发,需要两个前提:

1.把本地映射到外网

2.一个公共号



1.用ngrok把本地地址映射到外网

先编写接入接口


工具类

package com.imooc.util;import java.io.UnsupportedEncodingException;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;import java.util.Arrays;public class CheckUtil {private static final String token ="immoc";public static boolean checkSignature(String signature,String timestamp,String nonce) throws NoSuchAlgorithmException{String[] arr = new String[]{token,timestamp,nonce};//加密/校验流程如下://1. 将token、timestamp、nonce三个参数进行字典序排序Arrays.sort(arr);//2. 将三个参数字符串拼接成一个字符串进行sha1加密StringBuffer sb = new StringBuffer();for(int i=0;i<arr.length;i++){sb.append(arr[i]);}//sha1加密String temp = getSha1(sb.toString());//3. 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信return temp.equals(signature);}//下面四个import放在类名前面 包名后面//import java.io.UnsupportedEncodingException;//import java.security.MessageDigest;//import java.security.NoSuchAlgorithmException;//import java.util.Arrays; public static String getSha1(String str){    if (null == str || 0 == str.length()){        return null;    }    char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',             'a', 'b', 'c', 'd', 'e', 'f'};    try {        MessageDigest mdTemp = MessageDigest.getInstance("SHA1");        mdTemp.update(str.getBytes("UTF-8"));                 byte[] md = mdTemp.digest();        int j = md.length;        char[] buf = new char[j * 2];        int k = 0;        for (int i = 0; i < j; i++) {            byte byte0 = md[i];            buf[k++] = hexDigits[byte0 >>> 4 & 0xf];            buf[k++] = hexDigits[byte0 & 0xf];        }        return new String(buf);    } catch (NoSuchAlgorithmException e) {        e.printStackTrace();    } catch (UnsupportedEncodingException e) {        e.printStackTrace();    }    return str;}}


Servlet类

package com.imooc.servlet;import java.io.IOException;import java.io.PrintWriter;import java.security.NoSuchAlgorithmException;import java.util.Date;import java.util.Map;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.dom4j.DocumentException;import com.imooc.po.TextMessage;import com.imooc.util.CheckUtil;import com.imooc.util.MessageUtil;/** * Servlet implementation class WeixinServlet */public class WeixinServlet extends HttpServlet {private static final long serialVersionUID = 1L;    /**     * Default constructor.      */    public WeixinServlet() {        // TODO Auto-generated constructor stub    }/** * 参数描述signature微信加密签名,signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。timestamp时间戳nonce随机数echostr随机字符串 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String signature = request.getParameter("signature");String timestamp = request.getParameter("timestamp");String nonce = request.getParameter("nonce");String echostr = request.getParameter("echostr");PrintWriter out = response.getWriter();try {if(CheckUtil.checkSignature(signature, timestamp, nonce)){out.write(echostr);}} catch (NoSuchAlgorithmException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}

访问地址是

http://localhost:8080/weixin/WeixinServlet

用ngrok映射命令是.先跳转到ngrok目录下面,敲击名利:

ngrok http 8080



现在就可以在外网用

http://9a62752d.ngrok.io/weixin/WeixinServlet

访问写的方法


2.一个公共号

   因为公共号需要自己的微信号绑定身份证,银行卡。个人只能申请“订阅号”。“企业号”,“服务号”不是个人开的。而且发微信的数量还有限制。

   所以我找了个微信测试号

  

   测试账号申请地址

  http://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?action=showinfo&t=sandbox/index


配置 相应的url,和token

  


填写了后发现验证成功,


下面继续写可以正确接收,发送消息

先看开发文档,用最简单的text类型


还是刚才那个servlet,只不过现在是post方法


package com.imooc.util;import java.io.IOException;import java.io.InputStream;import java.util.Date;import java.util.HashMap;import java.util.List;import java.util.Map;import javax.servlet.http.HttpServletRequest;import org.dom4j.Document;import org.dom4j.DocumentException;import org.dom4j.Element;import org.dom4j.io.SAXReader;import com.imooc.po.TextMessage;import com.thoughtworks.xstream.XStream;public class MessageUtil {public static final String MESSAGE_TYPE_TEXT="text";/** * xml改成map * @param request * @return * @throws IOException * @throws DocumentException */public static Map<String,String> xmlToMap(HttpServletRequest request) throws IOException, DocumentException{Map<String,String> map = new HashMap<String,String>();SAXReader reader = new SAXReader();InputStream ins = request.getInputStream();Document doc = reader.read(ins);Element root = doc.getRootElement();List<Element> list = root.elements();for(Element e :list){map.put(e.getName(), e.getText());}ins.close();return map;}public static String textMessageToXml(TextMessage textMessage){XStream xstream=new XStream();xstream.alias("xml", textMessage.getClass());return xstream.toXML(textMessage);}public static String initText(String toUserName,String fromUserName,String content){TextMessage text=new TextMessage();text.setContent(content);text.setFromUserName(toUserName);text.setToUserName(fromUserName);text.setCreateTime(new Date().getTime());text.setMsgType(MessageUtil.MESSAGE_TYPE_TEXT);return MessageUtil.textMessageToXml(text);}/** * 天气查询 * @return String */public static String weatherMenu(){StringBuffer sb=new StringBuffer();sb.append("天气预报查询正在开发中……");return sb.toString();}}



package com.imooc.servlet;import java.io.IOException;import java.io.PrintWriter;import java.security.NoSuchAlgorithmException;import java.util.Date;import java.util.Map;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.dom4j.DocumentException;import com.imooc.po.TextMessage;import com.imooc.util.CheckUtil;import com.imooc.util.MessageUtil;/** * Servlet implementation class WeixinServlet */public class WeixinServlet extends HttpServlet {private static final long serialVersionUID = 1L;    /**     * Default constructor.      */    public WeixinServlet() {        // TODO Auto-generated constructor stub    }/** * 参数描述signature微信加密签名,signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。timestamp时间戳nonce随机数echostr随机字符串 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String signature = request.getParameter("signature");String timestamp = request.getParameter("timestamp");String nonce = request.getParameter("nonce");String echostr = request.getParameter("echostr");PrintWriter out = response.getWriter();try {if(CheckUtil.checkSignature(signature, timestamp, nonce)){out.write(echostr);}} catch (NoSuchAlgorithmException e) {// TODO Auto-generated catch blocke.printStackTrace();}}/** * 文本消息接收响应 ToUserName开发者微信号FromUserName发送方帐号(一个OpenID)CreateTime消息创建时间 (整型)MsgTypetextContent文本消息内容MsgId消息id,64位整型 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response.setCharacterEncoding("UTF-8");request.setCharacterEncoding("UTF-8");PrintWriter out = response.getWriter();try {Map<String,String> requestMap = MessageUtil.xmlToMap(request);// 发送方帐号(open_id)String fromUserName = requestMap.get("FromUserName");// 公众帐号String toUserName = requestMap.get("ToUserName");// 消息类型String MsgType = requestMap.get("MsgType");// 消息内容String content = requestMap.get("Content");String message = null;if("text".equals(MsgType)){/*TextMessage text = new TextMessage();text.setFromUserName(fromUserName);text.setToUserName(toUserName);text.setMsgType("text");text.setCreateTime(new Date().getTime());text.setContent("您发送的信息是:"+content);message = MessageUtil.textMessageToXml(text);*/message = MessageUtil.initText(toUserName, fromUserName,MessageUtil.weatherMenu());}System.out.println(message);out.print(message);} catch (DocumentException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{out.close();}}}


发送了消息后



0 0
原创粉丝点击