Java微信公众平台开发模式+自定义按钮源码

原文:http://blog.csdn.net/sunbreezemoon/article/details/9832287

首先,想用开放模式需要先成为开发者。成为开发者有两种写法。

一是:通过jsp页面,用out.print("echostr")//SHA1加密的字符串;

二是:通过Servlet。doGet返回exhostr,给微信平台。

这里我只写第二种方式的请求(这里的请求是以get方式请求),代码如下:

  1. import java.io.IOException;  
  2. import java.io.InputStream;  
  3. import java.io.PrintWriter;  
  4. import java.util.Arrays;  
  5.   
  6. import javax.servlet.ServletException;  
  7. import javax.servlet.http.HttpServlet;  
  8. import javax.servlet.http.HttpServletRequest;  
  9. import javax.servlet.http.HttpServletResponse;  
  10.   
  11. import org.jdom.JDOMException;  
  12.   
  13. /** 
  14.  * 微信统一入口 
  15.  * @author slz  
  16.  * 2013-7-26 上午10:17:08 
  17.  */  
  18. public class WeixinServlet extends HttpServlet {  
  19.   
  20.     public WeixinServlet() {  
  21.         super();  
  22.     }  
  23.   
  24.     public void destroy() {  
  25.         super.destroy();  
  26.     }  
  27.   
  28.     /** 
  29.      * 微信公众平台  成为开发者验证入口 
  30.      */  
  31.     public void doGet(HttpServletRequest request, HttpServletResponse response)  
  32.             throws ServletException, IOException {  
  33.         doPost(request, response);  
  34.     }  
  35.   
  36.     /** 
  37.      * 微信公众平台  所有接口入口 
  38.      */  
  39.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  40.             throws ServletException, IOException {  
  41.           
  42.         response.setCharacterEncoding("UTF-8");  
  43.         request.setCharacterEncoding("UTF-8");  
  44.         PrintWriter out = response.getWriter();  
  45.         String TOKEN = "sun";//Token   
  46.         String signature = request.getParameter("signature");//SHA1加密字符串   
  47.         String timestamp = request.getParameter("timestamp");//时间   
  48.         String nonce = request.getParameter("nonce");//随机数   
  49.         String echoStr = request.getParameter("echostr");//随机字符串   
  50.         if(StrUtil.isNotNull(echoStr)){  
  51.                 String[] a = {TOKEN,timestamp,nonce};  
  52.                 Arrays.sort(a);//数组排序   
  53.                 String str = "";  
  54.                 for(int i=0;i<a.length;i++){  
  55.                         str += a[i];  
  56.                 }  
  57.   
  58.                 String echo = new SHA1().getDigestOfString(str.getBytes());//SHA1加密   
  59.   
  60.                 if(echo.equals(signature)){  
  61.                         out.print(echoStr);  
  62.                 }else{  
  63.                         out.print("123");  
  64.                 }  
  65.         }else{  
  66.                 try {  
  67.                         InputStream is = request.getInputStream();  
  68.                         PushManage push = new PushManage();  
  69.                         String getXml = push.PushManageXml(is);  
  70.                         System.out.println("getXml:"+getXml);  
  71.                         out.print(getXml);  
  72.                 } catch (JDOMException e) {  
  73.                         out.print("");  
  74.                 }  
  75.         }  
  76.         out.flush();  
  77.         out.close();  
  78.     }  
  79.   
  80. }  
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jdom.JDOMException;

/**
 * 微信统一入口
 * @author slz 
 * 2013-7-26 上午10:17:08
 */
public class WeixinServlet extends HttpServlet {

	public WeixinServlet() {
		super();
	}

	public void destroy() {
		super.destroy();
	}

	/**
	 * 微信公众平台  成为开发者验证入口
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * 微信公众平台  所有接口入口
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		String TOKEN = "sun";//Token
		String signature = request.getParameter("signature");//SHA1加密字符串
		String timestamp = request.getParameter("timestamp");//时间
		String nonce = request.getParameter("nonce");//随机数
		String echoStr = request.getParameter("echostr");//随机字符串
		if(StrUtil.isNotNull(echoStr)){
		        String[] a = {TOKEN,timestamp,nonce};
		        Arrays.sort(a);//数组排序
		        String str = "";
		        for(int i=0;i<a.length;i++){
		                str += a[i];
		        }

		        String echo = new SHA1().getDigestOfString(str.getBytes());//SHA1加密

		        if(echo.equals(signature)){
		                out.print(echoStr);
		        }else{
		                out.print("123");
		        }
		}else{
		        try {
		                InputStream is = request.getInputStream();
		                PushManage push = new PushManage();
		                String getXml = push.PushManageXml(is);
		                System.out.println("getXml:"+getXml);
		                out.print(getXml);
		        } catch (JDOMException e) {
		                out.print("");
		        }
		}
		out.flush();
		out.close();
	}

}


当我们完成第一步成为开发者后,我们就可以用微信提供给我们的接口。

大家应该也看见上面有doPost方法(微信公共平台  所有接口入口)。当我们成为开发者后,微信用户向我们的公众账号发信息都是post请求。

  1. //这里写法多种,怎么写就要看你这么获取微信请求时发给我们的XML   
  2. InputStream is = request.getInputStream();  
  3. PushManage push = new PushManage();  
  4. String getXml = push.PushManageXml(is);  
//这里写法多种,怎么写就要看你这么获取微信请求时发给我们的XML
InputStream is = request.getInputStream();
PushManage push = new PushManage();
String getXml = push.PushManageXml(is);
此方法代码如下:

  1. import java.io.IOException;  
  2. import java.io.InputStream;  
  3. import java.text.SimpleDateFormat;  
  4. import java.util.Date;  
  5. import java.util.List;  
  6.   
  7. import org.jdom.Document;  
  8. import org.jdom.Element;  
  9. import org.jdom.JDOMException;  
  10. import org.jdom.input.SAXBuilder;  
  11. import org.jdom.output.XMLOutputter;  
  12.   
  13. /** 
  14.  * 微信所有接口入口 
  15.  * @author slz  
  16.  * 2013-7-26 上午11:01:08 
  17.  */  
  18. public class PushManage {  
  19.       
  20.     public String PushManageXml(InputStream is) throws JDOMException{  
  21.         String returnStr = "";  
  22.         String toName = "";  
  23.         String FromName = "";  
  24.         String type = "";  
  25.         String content = "";  
  26.         String con = "";  
  27.         String event = "";//自定义按钮事件请求   
  28.         String eKey = "";//事件请求key值   
  29.               
  30.         try {  
  31.               
  32.             SAXBuilder sax = new SAXBuilder();   
  33.             Document doc = sax.build(is);  
  34.             //获得文件的根元素   
  35.             Element root = doc.getRootElement();  
  36.                       
  37.             //获得根元素的第一级子节点   
  38.             List list = root.getChildren();  
  39.             for(int j=0;j<list.size();j++){  
  40.                 //获得结点   
  41.                 Element first = (Element) list.get(j);  
  42.       
  43.                 if(first.getName().equals("ToUserName")){  
  44.                     toName = first.getValue().trim();  
  45.                 }else if(first.getName().equals("FromUserName")){  
  46.                     FromName = first.getValue().trim();  
  47.                 }else if(first.getName().equals("MsgType")){  
  48.                     type = first.getValue().trim();  
  49.                 }else if(first.getName().equals("Content")){  
  50.                     con = first.getValue().trim();  
  51.                 }else if(first.getName().equals("Event")){  
  52.                     event = first.getValue().trim();  
  53.                 }else if(first.getName().equals("EventKey")){  
  54.                     eKey = first.getValue().trim();  
  55.                 }  
  56.             }  
  57.         } catch (IOException e) {  
  58.             e.printStackTrace();  
  59.         }  
  60.           
  61.         if(type.equals("event")){  
  62.             if(event.equals("subscribe")){//此为关注事件   
  63.                 content = "您好,欢迎关注我!";  
  64.             }  
  65.         }else if(type.equals("text")){  
  66.             if(con.equals("help")||con.equals("帮助")||con.equals("?")||con.equals("?")){  
  67.                 content = "帮助中心\n\n";  
  68.             }else if(con.equals("bind")||con.equals("绑定")){  
  69.                 content = "点击 <A href="\'\'" target=_blank>绑定账户</A>";  
  70.             }else if(con.startsWith("ck")||con.startsWith("CK")){  
  71.                 String order_id = "0";  
  72.                 con.toLowerCase();  
  73.                 if(con.startsWith("ck")){  
  74.                     order_id = con.substring(con.indexOf("ck")+2);  
  75.                 }else if(con.startsWith("CK")){  
  76.                     order_id = con.substring(con.indexOf("CK")+2);  
  77.                 }  
  78.                 if(!"".equals(order_id)){  
  79.                     StringBuffer sb = new StringBuffer();  
  80.                       
  81.                     sb.append("订单详情...\n");  
  82.                     content = sb.toString();  
  83.                 }else{  
  84.                     content = "未查询到相应信息,请重新输入!";  
  85.                 }  
  86.                   
  87.             }  
  88.         }  
  89.         //以下为自定义按钮事件   
  90.         if(eKey.equals("music")){//音乐请求   
  91.             returnStr = getBackXMLTypeMusic(toName, FromName, "http://view.online.zcom.com/full/16107/風之誓言.mp3");  
  92.         }else if(eKey.equals("img")){//图片请求   
  93.             content = "http://a.hiphotos.baidu.com/album/w%3D2048/sign=61aa038f622762d0803ea3bf94d409fa/d62a6059252dd42ae072bd07023b5bb5c9eab827.jpg";  
  94.             returnStr = getBackXMLTypeImg(toName, FromName, content);  
  95.         }else{//无自定义按钮返回上面的文本信息   
  96.             returnStr = getBackXMLTypeText(toName, FromName, content);  
  97.         }  
  98.         return returnStr;  
  99.     }  
  100.       
  101.     public String getBackXMLTypeText(String toName, String FromName, String content){  
  102.           
  103.         String returnStr = "";  
  104.           
  105.         SimpleDateFormat format=new SimpleDateFormat("yyyyMMddHHmmss");  
  106.         String times = format.format(new Date());  
  107.           
  108.         Element rootXML = new Element("xml");  
  109.           
  110.         rootXML.addContent(new Element("ToUserName").setText(FromName));  
  111.         rootXML.addContent(new Element("FromUserName").setText(toName));  
  112.         rootXML.addContent(new Element("CreateTime").setText(times));  
  113.         rootXML.addContent(new Element("MsgType").setText("text"));  
  114.         rootXML.addContent(new Element("Content").setText(content));  
  115.   
  116.         Document doc = new Document(rootXML);   
  117.           
  118.         XMLOutputter XMLOut = new XMLOutputter();    
  119.         returnStr = XMLOut.outputString(doc);  
  120.   
  121.         return returnStr;  
  122.     }  
  123.       
  124.     public String getBackXMLTypeImg(String toName, String FromName, String content){  
  125.           
  126.         String returnStr = "";  
  127.   
  128.         SimpleDateFormat format=new SimpleDateFormat("yyyyMMddHHmmss");  
  129.         String times = format.format(new Date());  
  130.           
  131.         Element rootXML = new Element("xml");  
  132.           
  133.         rootXML.addContent(new Element("ToUserName").setText(FromName));  
  134.         rootXML.addContent(new Element("FromUserName").setText(toName));  
  135.         rootXML.addContent(new Element("CreateTime").setText(times));  
  136.         rootXML.addContent(new Element("MsgType").setText("news"));  
  137.         rootXML.addContent(new Element("ArticleCount").setText("3"));  
  138.           
  139.         Element fXML = new Element("Articles");  
  140.         Element mXML = null;  
  141.   
  142.         String url = "http://www.baidu.com";  
  143.         String ss = "";  
  144.         for(int i = 1 ;i<=3;i++){  
  145.             mXML = new Element("item");  
  146.             mXML.addContent(new Element("Title").setText("图片"+i));  
  147.             mXML.addContent(new Element("Description").setText("美女"+i));  
  148.             mXML.addContent(new Element("PicUrl").setText(ss));  
  149.             mXML.addContent(new Element("Url").setText(url));  
  150.             fXML.addContent(mXML);  
  151.         }  
  152.         rootXML.addContent(fXML);  
  153.           
  154.         Document doc = new Document(rootXML);   
  155.           
  156.         XMLOutputter XMLOut = new XMLOutputter();    
  157.         returnStr = XMLOut.outputString(doc);  
  158.   
  159.         return returnStr;  
  160.     }  
  161.       
  162.     public String getBackXMLTypeMusic(String toName, String FromName, String content){  
  163.           
  164.         String returnStr = "";  
  165.   
  166.         SimpleDateFormat format=new SimpleDateFormat("yyyyMMddHHmmss");  
  167.         String times = format.format(new Date());  
  168.           
  169.         Element rootXML = new Element("xml");  
  170.           
  171.         rootXML.addContent(new Element("ToUserName").setText(FromName));  
  172.         rootXML.addContent(new Element("FromUserName").setText(toName));  
  173.         rootXML.addContent(new Element("CreateTime").setText(times));  
  174.         rootXML.addContent(new Element("MsgType").setText("music"));  
  175.   
  176.         Element mXML = new Element("Music");  
  177.           
  178.         mXML.addContent(new Element("Title").setText("音乐"));  
  179.         mXML.addContent(new Element("Description").setText("音乐让人心情舒畅!"));  
  180.         mXML.addContent(new Element("MusicUrl").setText(content));  
  181.         mXML.addContent(new Element("HQMusicUrl").setText(content));  
  182.           
  183.         rootXML.addContent(mXML);  
  184.   
  185.         Document doc = new Document(rootXML);   
  186.           
  187.         XMLOutputter XMLOut = new XMLOutputter();    
  188.         returnStr = XMLOut.outputString(doc);  
  189.   
  190.         return returnStr;  
  191.     }  
  192. }  
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;

/**
 * 微信所有接口入口
 * @author slz 
 * 2013-7-26 上午11:01:08
 */
public class PushManage {
	
	public String PushManageXml(InputStream is) throws JDOMException{
		String returnStr = "";
		String toName = "";
		String FromName = "";
		String type = "";
		String content = "";
		String con = "";
		String event = "";//自定义按钮事件请求
		String eKey = "";//事件请求key值
			
		try {
			
			SAXBuilder sax = new SAXBuilder(); 
			Document doc = sax.build(is);
			//获得文件的根元素
			Element root = doc.getRootElement();
					
			//获得根元素的第一级子节点
			List list = root.getChildren();
			for(int j=0;j<list.size();j++){
				//获得结点
				Element first = (Element) list.get(j);
	
				if(first.getName().equals("ToUserName")){
					toName = first.getValue().trim();
				}else if(first.getName().equals("FromUserName")){
					FromName = first.getValue().trim();
				}else if(first.getName().equals("MsgType")){
					type = first.getValue().trim();
				}else if(first.getName().equals("Content")){
					con = first.getValue().trim();
				}else if(first.getName().equals("Event")){
					event = first.getValue().trim();
				}else if(first.getName().equals("EventKey")){
					eKey = first.getValue().trim();
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		if(type.equals("event")){
			if(event.equals("subscribe")){//此为关注事件
				content = "您好,欢迎关注我!";
			}
		}else if(type.equals("text")){
			if(con.equals("help")||con.equals("帮助")||con.equals("?")||con.equals("?")){
				content = "帮助中心\n\n";
			}else if(con.equals("bind")||con.equals("绑定")){
				content = "点击 绑定账户";
			}else if(con.startsWith("ck")||con.startsWith("CK")){
				String order_id = "0";
				con.toLowerCase();
				if(con.startsWith("ck")){
					order_id = con.substring(con.indexOf("ck")+2);
				}else if(con.startsWith("CK")){
					order_id = con.substring(con.indexOf("CK")+2);
				}
				if(!"".equals(order_id)){
					StringBuffer sb = new StringBuffer();
					
					sb.append("订单详情...\n");
					content = sb.toString();
				}else{
					content = "未查询到相应信息,请重新输入!";
				}
				
			}
		}
		//以下为自定义按钮事件
		if(eKey.equals("music")){//音乐请求
			returnStr = getBackXMLTypeMusic(toName, FromName, "http://view.online.zcom.com/full/16107/風之誓言.mp3");
		}else if(eKey.equals("img")){//图片请求
			content = "http://a.hiphotos.baidu.com/album/w%3D2048/sign=61aa038f622762d0803ea3bf94d409fa/d62a6059252dd42ae072bd07023b5bb5c9eab827.jpg";
			returnStr = getBackXMLTypeImg(toName, FromName, content);
		}else{//无自定义按钮返回上面的文本信息
			returnStr = getBackXMLTypeText(toName, FromName, content);
		}
		return returnStr;
	}
	
	public String getBackXMLTypeText(String toName, String FromName, String content){
		
		String returnStr = "";
		
		SimpleDateFormat format=new SimpleDateFormat("yyyyMMddHHmmss");
		String times = format.format(new Date());
		
		Element rootXML = new Element("xml");
		
		rootXML.addContent(new Element("ToUserName").setText(FromName));
		rootXML.addContent(new Element("FromUserName").setText(toName));
		rootXML.addContent(new Element("CreateTime").setText(times));
		rootXML.addContent(new Element("MsgType").setText("text"));
		rootXML.addContent(new Element("Content").setText(content));

		Document doc = new Document(rootXML); 
		
		XMLOutputter XMLOut = new XMLOutputter();  
		returnStr = XMLOut.outputString(doc);

		return returnStr;
	}
	
	public String getBackXMLTypeImg(String toName, String FromName, String content){
		
		String returnStr = "";

		SimpleDateFormat format=new SimpleDateFormat("yyyyMMddHHmmss");
		String times = format.format(new Date());
		
		Element rootXML = new Element("xml");
		
		rootXML.addContent(new Element("ToUserName").setText(FromName));
		rootXML.addContent(new Element("FromUserName").setText(toName));
		rootXML.addContent(new Element("CreateTime").setText(times));
		rootXML.addContent(new Element("MsgType").setText("news"));
		rootXML.addContent(new Element("ArticleCount").setText("3"));
		
		Element fXML = new Element("Articles");
		Element mXML = null;

		String url = "http://www.baidu.com";
		String ss = "";
		for(int i = 1 ;i<=3;i++){
			mXML = new Element("item");
			mXML.addContent(new Element("Title").setText("图片"+i));
			mXML.addContent(new Element("Description").setText("美女"+i));
			mXML.addContent(new Element("PicUrl").setText(ss));
			mXML.addContent(new Element("Url").setText(url));
			fXML.addContent(mXML);
		}
		rootXML.addContent(fXML);
		
		Document doc = new Document(rootXML); 
		
		XMLOutputter XMLOut = new XMLOutputter();  
		returnStr = XMLOut.outputString(doc);

		return returnStr;
	}
	
	public String getBackXMLTypeMusic(String toName, String FromName, String content){
		
		String returnStr = "";

		SimpleDateFormat format=new SimpleDateFormat("yyyyMMddHHmmss");
		String times = format.format(new Date());
		
		Element rootXML = new Element("xml");
		
		rootXML.addContent(new Element("ToUserName").setText(FromName));
		rootXML.addContent(new Element("FromUserName").setText(toName));
		rootXML.addContent(new Element("CreateTime").setText(times));
		rootXML.addContent(new Element("MsgType").setText("music"));

		Element mXML = new Element("Music");
		
		mXML.addContent(new Element("Title").setText("音乐"));
		mXML.addContent(new Element("Description").setText("音乐让人心情舒畅!"));
		mXML.addContent(new Element("MusicUrl").setText(content));
		mXML.addContent(new Element("HQMusicUrl").setText(content));
		
		rootXML.addContent(mXML);

		Document doc = new Document(rootXML); 
		
		XMLOutputter XMLOut = new XMLOutputter();  
		returnStr = XMLOut.outputString(doc);

		return returnStr;
	}
}
以上方法用到的jar包: jdom.jar


微信公众平台自定义按钮设置,在此下载   微信公众平台自定义按钮Java
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值