关注微信公众号实现自动回复功能
接入微信公众平台开发,开发者需要按照如下步骤完成:
1.填写服务器配置
2.创建CoreServlet文件
package com.jlc.action;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Random;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;
import com.jlc.bean.longya.WXCode;
import com.jlc.service.WXCodeService;
import com.jlc.util.wxsms.MessageUtil;
import com.jlc.util.wxsms.SignUtil;
/**
* 核心请求处理类
*
*/
public class CoreServlet extends HttpServlet {
@Override
public void init(ServletConfig config) throws ServletException {
SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, config.getServletContext());
}
@Autowired
private WXCodeService wXCodeService;
private static final long serialVersionUID = 4440739483644821986L;
/**
* 确认请求来自微信服务器
*/
public 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();
// 通过检验signature对请求进行校验,若校验成功则原样返回echostr,表示接入成功,否则接入失败
if (SignUtil.checkSignature(signature, timestamp, nonce)) {
out.print(echostr);
}
out.close();
out = null;
}
/**
* 处理微信服务器发来的消息
*/
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println("进入doPost方法==========================");
req.setCharacterEncoding("UTF-8");
resp.setCharacterEncoding("UTF-8");
PrintWriter out = resp.getWriter();
try {
Map<String,String> map = MessageUtil.xmlToMap(req);
String toUserName = map.get("ToUserName");
String fromUserName = map.get("FromUserName");
String msgType = map.get("MsgType");
String content = map.get("Content");
String message = "123456";
//判断请求是否事件类型 event
if(MessageUtil.MESSAGE_EVENT.equals(msgType)){
String eventType = map.get("Event");
//若是关注事件 subscribe
if(MessageUtil.EVENT_SUB.equals(eventType)){
// String mycontent = MessageUtil.menuText();
String mycontent ="验证码:"+getRandom();
System.out.println(mycontent);
WXCode wxCode = new WXCode();
wxCode.setCode(getRandom());
wXCodeService.insert(getRandom());
message = MessageUtil.initText(toUserName, fromUserName, mycontent);
}
}
out.print(message);
System.out.println("doPost方法结束-------------");
} catch (Exception e) {
e.printStackTrace();
out.close();
}
}
//生成5位随机数
public static String getRandom(){
SimpleDateFormat simpleDateFormat;
simpleDateFormat=new SimpleDateFormat("yyyyMMdd");
String date=simpleDateFormat.format(new Date());
Random random=new Random();
int rannum= (int)(random.nextDouble()*(99999-10000 + 1))+ 10000;
return rannum+"";
}
}
3.创建 MessageUtil 文件
package com.jlc.util.wxsms;
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.jlc.common.message.request.TextMessage;
import com.thoughtworks.xstream.XStream;
public class MessageUtil {
public static final String MESSAGE_TEXT = "text";
public static final String MESSAGE_IMAGE = "image";
public static final String MESSAGE_VOICE = "voice";
public static final String MESSAGE_VIDEO = "video";
public static final String MESSAGE_LINK = "link";
public static final String MESSAGE_LOCATION = "location";
public static final String MESSAGE_EVENT = "event";
public static final String EVENT_SUB = "subscribe";
public static final String EVENT_UNSUB = "unsubscribe";
public static final String EVENT_CLICK = "CLICK";
public static final String EVENT_VIEW = "VIEW";
/**
* xml转为map
* @param request
* @return
* @throws DocumentException
* @throws IOException
*/
public static Map<String, String> xmlToMap(HttpServletRequest request ) throws DocumentException, IOException
{
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.setFromUserName(toUserName);
text.setToUserName(fromUserName);
text.setMsgType(MESSAGE_TEXT);
text.setCreateTime(new Date().getTime());
text.setContent(content);
return textMessageToXml(text);
}
public static String menuText(){
StringBuffer sb = new StringBuffer();
sb.append(" 你关注,\n");
return sb.toString();
}
}
4.创建 SignUtil 文件
package com.jlc.util.wxsms;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
/**
* 请求校验工具类
*
* @date 2013-05-18
*/
public class SignUtil {
// 与接口配置信息中的Token要一致
private static String token = "immco";
/**
* 验证签名
*
* @param signature
* @param timestamp
* @param nonce
* @return
*/
public static boolean checkSignature(String signature, String timestamp, String nonce) {
String[] arr = new String[] { token, timestamp, nonce };
// 将token、timestamp、nonce三个参数进行字典序排序
Arrays.sort(arr);
StringBuilder content = new StringBuilder();
for (int i = 0; i < arr.length; i++) {
content.append(arr[i]);
}
MessageDigest md = null;
String tmpStr = null;
try {
md = MessageDigest.getInstance("SHA-1");
// 将三个参数字符串拼接成一个字符串进行sha1加密
byte[] digest = md.digest(content.toString().getBytes());
tmpStr = byteToStr(digest);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
content = null;
// 将sha1加密后的字符串可与signature对比,标识该请求来源于微信
return tmpStr != null ? tmpStr.equals(signature.toUpperCase()) : false;
}
/**
* 将字节数组转换为十六进制字符串
*
* @param byteArray
* @return
*/
private static String byteToStr(byte[] byteArray) {
String strDigest = "";
for (int i = 0; i < byteArray.length; i++) {
strDigest += byteToHexStr(byteArray[i]);
}
return strDigest;
}
/**
* 将字节转换为十六进制字符串
*
* @param mByte
* @return
*/
private static String byteToHexStr(byte mByte) {
char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
char[] tempArr = new char[2];
tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
tempArr[1] = Digit[mByte & 0X0F];
String s = new String(tempArr);
return s;
}
}
5.CoreServlet在web.xml中的配置
<servlet>
<servlet-name>coreServlet</servlet-name>
<servlet-class>
com.jlc.action.CoreServlet
</servlet-class>
</servlet>
<!-- url-pattern中配置的/coreServlet用于指定该Servlet的访问路径 -->
<servlet-mapping>
<servlet-name>coreServlet</servlet-name>
<url-pattern>/coreServlet</url-pattern>
</servlet-mapping>
6.参考地址
1. https://blog.****.net/Santiago_M/article/details/79111364?utm_source=blogkpcl15&utm_medium=distribute.pc_relevant_download.none-task-blog-baidujs-4.nonecase&depth_1-utm_source=distribute.pc_relevant_download.none-task-blog-baidujs-4.nonecase
2. https://blog.****.net/coco2d_x2014/article/details/78045527