springMVC调微信接口实现关注时消息回复和自动回复功能

本文介绍如何使用 Spring MVC 搭建微信接口,包括校验请求来源、处理消息等核心步骤,并提供完整的代码实现。

微信一直是一个比较热门的词汇,今天我主要简单的搭建一下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();  
	    }  

	    /**
	     * <p>传值</p>
	     * @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();  
	    }
	    
	    
	   
	    
	    
	    /**
	     * <p>传入数据转为document</p>
	     * @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;
	    }
	    
	    /**
	     * <p>自动回复</p>
	     * @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 = "<xml>"+  
            "<ToUserName><![CDATA[%1$s]]></ToUserName>"+  
            "<FromUserName><![CDATA[%2$s]]></FromUserName>"+  
            "<CreateTime>%3$s</CreateTime>"+  
            "<MsgType><![CDATA[%4$s]]></MsgType>"+  
            "<Content><![CDATA[%5$s]]></Content>"+  
            "<FuncFlag>0</FuncFlag>"+  
            "</xml>";    
            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;
	    }
	    
	    /**
	     * <p>1、text 2、event</p>
	     * @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;
	}
	
	
}


以下是我做的一个小产品欢迎大家关注:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值