微信开发服务器配置

/**
* 微信接口验证与接收
* 
* @param signature
* @param timestamp
* @param nonce
* @return
* @throws IOException
*/
@RequestMapping(value = "/wsc")
public void check(HttpServletRequest request, HttpServletResponse response) throws IOException {
boolean isGet = request.getMethod().toLowerCase().equals("get");
PrintWriter out;
if (isGet) {


String signature = request.getParameter("signature");
String timestamp = request.getParameter("timestamp");
String nonce = request.getParameter("nonce");
String echostr = request.getParameter("echostr");


// PrintWriter out = null;


if (CheckUtil.checkSignature(signature, timestamp, nonce)) {
try {


out = response.getWriter();
out.write(echostr);
out.flush();


} catch (IOException e) {
e.printStackTrace();
}
}
} else {


response.setCharacterEncoding("UTF-8");
out = response.getWriter();
// 接收消息并返回消息
// 调用核心服务类接收处理请求
String respXml = CoreService.processRequest(request);
out.print(respXml); 
out.flush();
out.close();
}



}

--------分隔符

public static String processRequest(HttpServletRequest request) {


// xml格式的消息数据
String respXml = null;
// 默认返回的文本消息内容
String respContent = "未知的消息类型";
try {
request.setCharacterEncoding("UTF-8");


// 调用parseXml方法解析请求消息
Map requestMap = MessageUtil.parseXml(request);
// 发送方帐号
String fromUserName = (String) requestMap.get("FromUserName");
// 开发者微信号
String toUserName = (String) requestMap.get("ToUserName");
// 消息类型
String msgType = (String) requestMap.get("MsgType");
// 回复文本消息
TextMessage textMessage = new TextMessage();
textMessage.setToUserName(fromUserName);
textMessage.setFromUserName(toUserName);
textMessage.setCreateTime(new Date().getTime());
textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);// 回复的类型
// textMessage.setFuncFlag(0);


// 图文消息


NewsMessage newsMessage = new NewsMessage();
newsMessage.setToUserName(fromUserName);
newsMessage.setFromUserName(toUserName);
newsMessage.setCreateTime(new Date().getTime());
newsMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);
newsMessage.setFuncFlag(0);


// 获取文本消息
// String content = (String) requestMap.get("Content");
List<Article> articleList = new ArrayList<Article>();


if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) {


// respContent = "你好啊!!!!";
// StringBuffer buffer = new StringBuffer();
// buffer.append("您好,我是Target,请回复数字选择服务:").append("\n\n");
// buffer.append("1 可查看测试单图文").append("\n");
// buffer.append("2 可测试多图文发送").append("\n");
// respContent = String.valueOf(buffer);
// textMessage.setContent(respContent);


// 测试单图文回复
Article article = new Article();
article.setTitle("巴洛伊铲射破门");
// 图文消息中可以使用QQ表情、符号表情
article.setDescription("这是测试有没有换行\n\n如果有空行就代表换行成功\n\n点击图文可以跳转到百度首页");
// 将图片置为空
article.setPicUrl(
"http://n.sinaimg.cn/sports/99_img/upload/cf0d0fdd/294/w1700h994/20180624/dx4W-heirxyf2696267.jpg");
article.setUrl("http://slide.2018.sina.com.cn/eng/slide_82_89646_439637.html#p=1");
articleList.add(article);
newsMessage.setArticleCount(articleList.size());
newsMessage.setArticles(articleList);


respXml = MessageUtil.newsMessageToXml(newsMessage);


}
// 图片消息
else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_IMAGE)) {
// respContent = "您发送的是图片消息!";
return "";
}
// 语音消息
else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_VOICE)) {
// respContent = "您发送的是语音消息!";
return "";
}
// 视频消息
else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_VIDEO)) {
//respContent = "您发送的是视频消息!";
return "";
}
// 地理位置消息
else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LOCATION)) {
//respContent = "您发送的是地理位置消息!";
return "";
}
// 链接消息
else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LINK)) {
//respContent = "您发送的是链接消息!";
return "";
}
// 事件推送
else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)) {
// 事件类型
String eventType = (String) requestMap.get("Event");
// 关注
if (eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) {
respContent = "谢谢关注Target公众号";
textMessage.setContent(respContent);
respXml = MessageUtil.textMessageToXml(textMessage);
}
// 取消关注
else if (eventType.equals(MessageUtil.EVENT_TYPE_UNSUBSCRIBE)) {
// TODO 取消订阅后用户不会再收到公众账号发送的消息,因此不需要回复
}
// 扫描带参数二维码
else if (eventType.equals(MessageUtil.EVENT_TYPE_SCAN)) {
// TODO 处理扫描带参数二维码事件
}
// 上报地理位置
else if (eventType.equals(MessageUtil.REQ_MESSAGE_TYPE_LOCATION)) {
// TODO 处理上报地理位置事件
return "";
}
// 自定义菜单
else if (eventType.equals(MessageUtil.EVENT_TYPE_CLICK)) {
// TODO 处理菜单点击事件
}
}





return respXml;
} catch (Exception e) {
e.printStackTrace();
}
return "";
}









MessageUtil 工具类

// public static final String RESP_MESSAGE_TYPE_TEXT = "text";
// public static final Object REQ_MESSAGE_TYPE_TEXT = "text";
// public static final Object REQ_MESSAGE_TYPE_IMAGE = "image";
// public static final Object REQ_MESSAGE_TYPE_VOICE = "voice";
// public static final Object REQ_MESSAGE_TYPE_VIDEO = "video";
// public static final Object REQ_MESSAGE_TYPE_LOCATION = "location";
// public static final Object REQ_MESSAGE_TYPE_LINK = "link";
// public static final Object REQ_MESSAGE_TYPE_EVENT = "event";
// public static final Object EVENT_TYPE_SUBSCRIBE = "SUBSCRIBE";
// public static final Object EVENT_TYPE_UNSUBSCRIBE = "UNSUBSCRIBE";
// public static final Object EVENT_TYPE_SCAN = "SCAN";
// public static final Object EVENT_TYPE_LOCATION = "LOCATION";
// public static final Object EVENT_TYPE_CLICK = "CLICK";


/**
* 返回消息类型:文本
*/
public static final String RESP_MESSAGE_TYPE_TEXT = "text";


/**
* 返回消息类型:音乐
*/
public static final String RESP_MESSAGE_TYPE_MUSIC = "music";


/**
* 返回消息类型:图文
*/
public static final String RESP_MESSAGE_TYPE_NEWS = "news";


/**
* 请求消息类型:视频
*/
public static final Object REQ_MESSAGE_TYPE_VIDEO = "video";
/**
* 请求消息类型:文本
*/
public static final String REQ_MESSAGE_TYPE_TEXT = "text";


/**
* 请求消息类型:图片
*/
public static final String REQ_MESSAGE_TYPE_IMAGE = "image";


/**
* 请求消息类型:链接
*/
public static final String REQ_MESSAGE_TYPE_LINK = "link";


/**
* 请求消息类型:地理位置
*/
public static final String REQ_MESSAGE_TYPE_LOCATION = "location";


/**
* 请求消息类型:音频
*/
public static final String REQ_MESSAGE_TYPE_VOICE = "voice";


/**
* 请求消息类型:推送
*/
public static final String REQ_MESSAGE_TYPE_EVENT = "event";


/**
* 事件类型:subscribe(订阅)and 未关注群体扫描二维码
*/
public static final String EVENT_TYPE_SUBSCRIBE = "subscribe";


/**
* 事件类型:已关注群体扫描二维码
*/
public static final String EVENT_TYPE_SCAN = "SCAN";
/**
* 事件类型:unsubscribe(取消订阅)
*/
public static final String EVENT_TYPE_UNSUBSCRIBE = "unsubscribe";


/**
* 事件类型:CLICK(自定义菜单点击事件)
*/
public static final String EVENT_TYPE_CLICK = "CLICK";
/**
* 事件类型:VIEW(点击自定义菜单跳转链接时的事件)
*/
public static final String EVENT_TYPE_VIEW = "VIEW";


/**
* 事件类型:transfer_customer_service(把消息推送给客服)
*/
public static final String EVENT_TYPE_TRANSFER_CUSTOMER_SERVICE = "transfer_customer_service";
public static String PREFIX_CDATA = "<![CDATA[";
public static String SUFFIX_CDATA = "]]>";


/**
* 扩展xstream,使其支持CDATA块 CDATA[不解析块内容]
*/
private static XStream xstream = new XStream(new XppDriver() {
public HierarchicalStreamWriter createWriter(Writer out) {
return new PrettyPrintWriter(out) {
// 对所有xml节点的转换都增加CDATA标记
boolean cdata = true;


@SuppressWarnings("unchecked")
public void startNode(String name, Class clazz) {
super.startNode(name, clazz);
}


protected void writeText(QuickWriter writer, String text) {
if (cdata) {
writer.write(PREFIX_CDATA);
writer.write(text);
writer.write(SUFFIX_CDATA);
} else {
super.writeText(writer, text);
}
}
};
}
});


@SuppressWarnings({ "unchecked", "rawtypes" })
public static Map parseXml(HttpServletRequest request) throws Exception {
// 将解析结果存储在HashMap中
Map map = new HashMap();


// 从request中取得输入流
InputStream inputStream = request.getInputStream();
// 读取输入流
SAXReader reader = new SAXReader();
Document document = reader.read(inputStream);
// 得到xml根元素
Element root = document.getRootElement();
// 得到根元素的所有子节点
List<Element> elementList = root.elements();
// 遍历所有子节点
for (Element e : elementList)
map.put(e.getName(), e.getText());


// 释放资源
inputStream.close();
inputStream = null;
return map;
}


/**
* 文本消息转为xml
* 
* @param textMessage
* @return
*/
public static String textMessageToXml(BaseMessage textMessage) {
xstream.alias("xml", textMessage.getClass());


return xstream.toXML(textMessage);
}


/**
* 图文消息对象转换成xml
*
* @param newsMessage
*            图文消息对象
* @return xml
*/
public static String newsMessageToXml(BaseMessage newsMessage) {
xstream.alias("xml", newsMessage.getClass());
xstream.alias("item", new Article().getClass());
return xstream.toXML(newsMessage);
}







private static final String token = "***";//微信里自己的设置




public static boolean checkSignature(String signature, String timestamp, String nonce) {
String[] str = new String[] { token, timestamp, nonce };
// 排序
Arrays.sort(str);
// 拼接字符串
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < str.length; i++) {
buffer.append(str[i]);
}
// 进行sha1加密
String temp = encode(buffer.toString());
// 与微信提供的signature进行匹对
return signature.equals(temp);
}


private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
'e', 'f' };


private static String getFormattedText(byte[] bytes) {
int len = bytes.length;
StringBuilder buf = new StringBuilder(len * 2);
// 把密文转换成十六进制的字符串形式
for (int j = 0; j < len; j++) {
buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
}
return buf.toString();
}


public static String encode(String str) {
if (str == null) {
return null;
}
try {
MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
messageDigest.update(str.getBytes());
return getFormattedText(messageDigest.digest());
} catch (Exception e) {
throw new RuntimeException(e);
}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值