欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

weichat 微信开发之接受普通消息

程序员文章站 2022-05-11 21:59:52
...

 

 

 接入微信  使用 ngrok

 http://knight-black-bob.iteye.com/blog/2244830

 

接受普通消息

 源码下载 : http://download.csdn.net/download/knight_black_bob/9123671

WeichatServlet.java

package com.curiousby.cn;

import java.io.IOException;
import java.io.PrintWriter;
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 com.curiousby.cn.entity.TextMessage;
import com.curiousby.cn.util.CommonUtils;
import com.curiousby.cn.util.MessageUtil;
import com.curiousby.cn.util.WeichatCheckUtils;
 

/**
 * @author baoyou  E-mail:curiousby@163.com
 * @version 创建时间:2015年9月20日 下午2:06:42 
 * des:
 */
public class WeichatServlet extends HttpServlet{

	 
	private static final long serialVersionUID = 1L;
	private String signature; //微信加密签名,signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
	private String timestamp; // 时间戳
	private String nonce; //随机数
	private String echostr; //随机字符串
	
	

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException { 
		signature = req.getParameter("signature");
		timestamp = req.getParameter("timestamp");
		nonce = req.getParameter("nonce");
		echostr = req.getParameter("echostr");
		System.out.println("signature timestamp  nonce  echostr  " + signature +" " + timestamp +" " + nonce  + " " + echostr ); 
		PrintWriter out = resp.getWriter();
        if (WeichatCheckUtils.checkSignature(signature, timestamp, nonce)) {
            out.print(echostr);
        }

	}
	 
	
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		resp.setCharacterEncoding("UTF-8");
		PrintWriter out = resp.getWriter();
		try {
			Map<String,String> map = MessageUtil.xmlToString(req);
			System.out.println(CommonUtils.mapToString(map));
			  String toUserName   = map .get("ToUserName");
			  String fromUserName   = map .get("FromUserName");
			  String createTime  = map .get("CreateTime");
			  String msgType  = map .get("MsgType");
			  String content  = map .get("Content");
			  String msgId  = map .get("MsgId"); 
			
			  String message ="";
			 
			  if ("text".equals(msgType)) {
				  TextMessage text = new TextMessage();
				  text.setFromUserName(toUserName);
				  text.setToUserName(fromUserName);
				  text.setMsgType("text");
				  text.setCreateTime(new Date().getTime());
				  String recontent ="";
				  try{
				  int aint =  Integer.parseInt(content);
				  recontent=" 您好,我是包包大人.\r\n 您发送的内容是 :"+(aint+1);
				  }catch(Exception e){
					  recontent =" 您好,我是包包大人.\r\n 您发送的内容是 :"+content;
				  }
				  text.setContent(recontent);
				  message =  MessageUtil.textMessageToXml(text);
			  }
			   System.out.println(message);
			  out.print(message);
		} catch (Exception e) { 
			e.printStackTrace();
		}finally{
			out.close();
		}
		
		
	}
}

 

CommonUtils.java

package com.curiousby.cn.util;

import java.util.Map;

/**
 * @author baoyou  E-mail:curiousby@163.com
 * @version 创建时间:2015年9月20日 下午2:24:27 
 * des:
 */
public class CommonUtils {

	public static String arrayToString (String [] arr){
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < arr.length; i++) {
			sb.append(arr[i]);
		}
		return sb.toString();
	}
	
	public static String mapToString(Map<String,String> map){
		StringBuffer sb = new StringBuffer();
		sb.append("{");
		for (String key : map.keySet() ) {
			sb.append(key+":"+map.get(key)+",");
		}
		sb.substring(0, sb.length()-1);
		sb.append("}");
		return sb.toString();
	}
	
	
}

 

 MessageUtil.java

package com.curiousby.cn.util;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.curiousby.cn.entity.TextMessage;
import com.thoughtworks.xstream.XStream;
 

/**
 * @author baoyou  E-mail:curiousby@163.com
 * @version 创建时间:2015年9月20日 下午4:18:35 
 * des:
 */
public class MessageUtil {

	
	public  static Map <String,String> xmlToString(HttpServletRequest request) throws Exception{
		 Map <String,String>  map = new HashMap<String,String>();
		 SAXReader reader = new SAXReader();
		 InputStream is = request.getInputStream();
		 Document doc = reader.read(is);
		 Element root = doc.getRootElement();
		 List<Element> llist = root.elements();
		 for (Element e : llist) {
			map.put(e.getName(), e.getText());
		}
		 is.close();
		return map;
	}
	
	public static String textMessageToXml(TextMessage textMessage){
		
		XStream xStream = new XStream();
		xStream.alias("xml", textMessage.getClass());
		return xStream.toXML(textMessage);
	}
	
}

 

 

ShaUtils.java

package com.curiousby.cn.util;

import java.security.MessageDigest;

/**
 * @author baoyou  E-mail:curiousby@163.com
 * @version 创建时间:2015年9月20日 下午2:36:04 
 * des:
 */
public class ShaUtils {

	private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5',
		'6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
	
	
	public static String getSha1(String str){
		if (str == null || str.length() ==0) {
			return null;
		}
		
		try{
			
			MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
			messageDigest.update(str.getBytes("UTF-8"));
			
			byte[] md = messageDigest.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++] =HEX_DIGITS[byte0 >>> 4 & 0xf ];
				buf[k++] =HEX_DIGITS[byte0  & 0xf ];
			}
			System.out.println(" before sha1 str :"+ str +"\r\n after sha1  string : "+new String(buf));
			return new String(buf);
		}catch(Exception e){
			return null;
		}
	}
}

 

 

WeichatCheckUtils.java

package com.curiousby.cn.util;

import java.util.Arrays;

/**
 * @author baoyou  E-mail:curiousby@163.com
 * @version 创建时间:2015年9月20日 下午2:14:46 
 * des:
 */
public class WeichatCheckUtils {

	
	private static final String TOKEN ="xxxxxx";
	
	public  static boolean checkSignature(String signature, String timestamp,String nonce){
		String[] str = { TOKEN, timestamp, nonce };
		 Arrays.sort(str); // 字典序排序
		String string = CommonUtils.arrayToString(str);
		String temp = ShaUtils.getSha1(string);
		 return temp.equals(signature);
	}
	
}

 

 

web.xml

<servlet>
  	<servlet-name>weichatServlet</servlet-name>
  	<servlet-class>com.curiousby.cn.WeichatServlet</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>weichatServlet</servlet-name> 
  	<url-pattern>/weichat.do</url-pattern>
  </servlet-mapping>

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

捐助开发者

在兴趣的驱动下,写一个免费的东西,有欣喜,也还有汗水,希望你喜欢我的作品,同时也能支持一下。 当然,有钱捧个钱场(右上角的爱心标志,支持支付宝和PayPal捐助),没钱捧个人场,谢谢各位。


weichat 微信开发之接受普通消息
            
    
    博客分类: weichat weichat微信开发接受普通消息 weichat 微信开发之接受普通消息
            
    
    博客分类: weichat weichat微信开发接受普通消息 weichat 微信开发之接受普通消息
            
    
    博客分类: weichat weichat微信开发接受普通消息 
 
 
 谢谢您的赞助,我会做的更好!