微信一直是一个比较热门的词汇,今天我主要简单的搭建一下springMVC版本的微信接口调用
废话不多说,贴代码
RequestWeiXinWXY.java
package com.beijing.wei.weixin.weixingyu;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.beijing.wei.base.BaseContractor;
import com.beijing.wei.util.common.CommonUtil1;
import com.beijing.wei.util.file.SysLogs;
import com.beijing.wei.weixin.service.WXYweixinService;
@Controller
@RequestMapping(value = "/wxyweixin")
public class RequestWeiXinWXY extends BaseContractor {
@Autowired
private WXYweixinService wxyweixinService;
/**
* 校验信息是否是从微信服务器发过来的。
*
* @param weChat
* @param out
*/
@RequestMapping(method = { RequestMethod.GET })
public void valid(WeChat weChat, PrintWriter out) {
String signature = weChat.getSignature(); // 微信加密签名
String timestamp = weChat.getTimestamp(); // 时间戳
String nonce = weChat.getNonce();// 随机数
String echostr = weChat.getEchostr();// 随机字符串
// 通过检验signature对请求进行校验,若校验成功则原样返回echostr,表示接入成功,否则接入失败
if (ValidateUtil.validate(ValidateUtil.WXY_TOKEN, weChat)) {
out.print(echostr);
} else {
System.out.println("不是微信服务器发来的请求,请小心!");
}
out.flush();
out.close();
}
/**
* 微信消息的处理
*
* @param request
* @param out
* @throws Throwable
*/
@RequestMapping(method = { RequestMethod.POST })
public void dispose(HttpServletRequest request, HttpServletResponse response)
throws Throwable {
/* 消息的接收、处理、响应 */
// 将请求、响应的编码均设置为UTF-8(防止中文乱码)
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
// 调用核心业务类接收消息、处理消息
String respMessage = ValidateUtil.automatismRestoreEntity(ValidateUtil.automatismRestoreDocument(ValidateUtil.getStringPostWeixin(request)));
SysLogs.print("INFO", "***************************$$$*** "+respMessage);
// 响应消息
PrintWriter out = response.getWriter();
out.print(respMessage);
out.flush();
out.close();
}
}
下面是处理request请求获取微信参数:
ValidateUtil.java
package com.beijing.wei.weixin.weixingyu;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import com.beijing.wei.login.model.ProjectUsers;
import com.beijing.wei.util.autoReack.XiaoDouMachine;
import com.beijing.wei.util.file.SysLogs;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
public class ValidateUtil {
public final static String WXY_TOKEN = "weixingyu";
public static boolean validate(String token,WeChat weChat){
String[] tmpArr={token,weChat.getTimestamp(),weChat.getNonce()};
Arrays.sort(tmpArr);
String tmpStr=ArrayToString(tmpArr);
tmpStr=SHA1Encode(tmpStr);
if(tmpStr.equalsIgnoreCase(weChat.getSignature())){
return true;
}else{
return false;
}
}
//数组转字符串
public static String ArrayToString(String [] arr){
StringBuffer bf = new StringBuffer();
for(int i = 0; i < arr.length; i++){
bf.append(arr[i]);
}
return bf.toString();
}
//sha1加密
public static String SHA1Encode(String sourceString) {
String resultString = null;
try {
resultString = new String(sourceString);
MessageDigest md = MessageDigest.getInstance("SHA-1");
resultString = byte2hexString(md.digest(resultString.getBytes()));
} catch (Exception ex) {
}
return resultString;
}
public static String byte2hexString(byte[] bytes) {
StringBuffer buf = new StringBuffer(bytes.length * 2);
for (int i = 0; i < bytes.length; i++) {
if (((int) bytes[i] & 0xff) < 0x10) {
buf.append("0");
}
buf.append(Long.toString((int) bytes[i] & 0xff, 16));
}
return buf.toString().toUpperCase();
}
/**
* 传值
* @param request 当前post值
* return String
*/
public static String getStringPostWeixin(HttpServletRequest request){
StringBuilder buffer = new StringBuilder();
BufferedReader reader=null;
try{
reader = new BufferedReader(new InputStreamReader(request.getInputStream(),"UTF-8"));
String line=null;
while((line = reader.readLine())!=null){
buffer.append(line);
}
}catch(Exception e){
e.printStackTrace();
SysLogs.print("INFO", "request -> InputStream 异常");
SysLogs.print("WARN", e);
}finally{
if(null!=reader){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
SysLogs.print("INFO", "IO 异常");
SysLogs.print("WARN", e);
}
}
}
return buffer.toString();
}
/**
* 传入数据转为document
* @param domStr 数据字符串
* reuturn document
*/
public static Document automatismRestoreDocument(String domStr){
Document document=null;
if(null != domStr && !domStr.isEmpty()){
try{
SysLogs.print("INFO","微信---传入数据str"+domStr);
document = DocumentHelper.parseText(domStr);
}catch(Exception e){
e.printStackTrace();
SysLogs.print("WARN", e);
}
if(null==document){
SysLogs.print("INFO","微信---传入数据有误");
return null;
}
}
return document;
}
/**
* 自动回复
* @throws Throwable
*/
public static String automatismRestoreEntity(Document document) throws Throwable{
String resultStr = "";
Element root=document.getRootElement();
String fromUsername = root.elementText("FromUserName");
String toUsername = root.elementText("ToUserName");
String keyword = root.elementTextTrim("Content");
String MsgType = root.elementTextTrim("MsgType");
String Event = root.elementTextTrim("Event");
String time = new Date().getTime()+"";
String textTpl = ""+
" "+
" "+
"%3$s "+
" "+
" "+
"0 "+
" ";
String msgType = "text";
String contentStr = "";
switch(returnTypeNumber(MsgType)){
case 1 :
if(null!=keyword&&!keyword.equals(""))
{
contentStr = XiaoDouMachine.getXiaoDouMsg(keyword);//"你说 "+keyword +"?";
}
break;
case 2 :
if(null != Event && Event.equals("subscribe")){
contentStr = "欢迎关注我、在这里我是你的朋友,你想说什么都可以,不过不可以生气奥";
}
break;
}
resultStr = textTpl.format(textTpl, fromUsername, toUsername, time, msgType, contentStr);
return resultStr;
}
/**
* 1、text 2、event
* @param type
* @return
*/
public static int returnTypeNumber(String type){
int i = 0;
if(null != type && !type.isEmpty()){
if(type.equals("text")){
i = 1;
}else if(type.equals("event")){
i = 2;
}
}
return i;
}
}
下面是实体:WeChat
package com.beijing.wei.weixin.weixingyu;
public class WeChat {
private String signature;
private String timestamp;
private String nonce;
private String echostr;
public String getSignature() {
return signature;
}
public void setSignature(String signature) {
this.signature = signature;
}
public String getTimestamp() {
return timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
public String getNonce() {
return nonce;
}
public void setNonce(String nonce) {
this.nonce = nonce;
}
public String getEchostr() {
return echostr;
}
public void setEchostr(String echostr) {
this.echostr = echostr;
}
}
以下是我做的一个小产品欢迎大家关注: