微信公衆號自定義菜單

微信公衆平臺自定義菜單接口文檔:https://mp.weixin.qq.com/wiki/10/0234e39a2025342c17a7d23595c6b40a.htmlhtml

最近作了下公衆號的自定義菜單,下面貼上每一步的操做步驟,一共三步:java

1.調用公衆號建立自定義菜單接口建立本身想要的菜單(建立自定義菜單表,存儲自定義菜單內容,方便後續更新):web


舉例以下:spring

levelNum列:菜單級別(1:父菜單,2子菜單)json

father列:父級菜單是誰api

type列: main:一級菜單,click:點擊事件,view:跳轉路徑,微信

name:展現的名稱session

contentText:若是是一級菜單,配置main或者不配(null)都行,配置view也能夠,可是切記一級菜單不能直接配click這類的點擊事件,不然建立菜單時會失敗app

contentText與contentType配置對應關係:
微信公衆平臺

main ------>main

cilck  ------>key

view  ------>url

sequence:展現的順序

siteId:刷新哪一個站點的菜單

後臺添加菜單功能如圖:

而後作一個刷新自定義菜單的按鈕,後期若是菜單有更新,點擊按鈕判斷刷新的是哪一個站點的菜單就好了

刷新自定義菜單就是調用微信的建立自定義菜單接口:

package com.odao.weixin.site.web.controller.createMenu;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.alibaba.fastjson.JSON;
import com.odao.weixin.api.oauth.MenuManager;
import com.odao.weixin.api.support.AccessTokenKit;
import com.odao.weixin.site.core.GlobalThreadLocal;
import com.odao.weixin.site.subsys.customButton.CustomButtonSys;

@Controller
@RequestMapping("/")
public class CreateMenuController {
	final static Logger logger = LoggerFactory.getLogger(CreateMenuController.class); 
	@Autowired
	private CustomButtonSys customButtonSys;

	
	@RequestMapping("creatMenu.do")
	protected void 	handleRequestInternal(HttpServletRequest request,
			HttpServletResponse response,Writer writer) throws Exception {
		boolean b=false;
		String accesstoken=null;
		String text=null;
		logger.debug("建立自定義菜單請求");	
	
		//獲取基礎token		
		try {			
			String token = AccessTokenKit.getTokenNew(微信公衆號appid, 微信公衆號Secret);
			accesstoken = (String) JSON.parseObject(token, Map.class).get("access_token");//經過AppId 和 AppSecret 獲取access_token
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		
		//建立菜單語句
		text = customButtonSys.getCreatText();
		logger.debug("建立自定義菜單請求的text["+text+"]");
		
		if(accesstoken!=null&&accesstoken.length()>0&&text!=null&&text.length()>0){
			try {
			    b=MenuManager.createMenu(accesstoken, text);//經過access_token和頁面提交的按鈕建立字符串建立自定義菜單,成功返回true,失敗返回false
			} catch (KeyManagementException e) {
				e.printStackTrace();
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
			} catch (NoSuchProviderException e) {
				e.printStackTrace();
			}
		}
		
		int result = 0;
		if(b){
			result = 1;
		} else {
			result = 0;
		}
		logger.debug("建立自定義菜單結果:"+result);
		
		response.setContentType("text/plain");
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		PrintWriter out;
		try {			
			out = response.getWriter();
			JSONObject resultJSON = new JSONObject();
			String jsonpCallback = request.getParameter("jsonpCallback");// 客戶端請求參數
			resultJSON.put("retCode", result);
			out.println(jsonpCallback + "(" + resultJSON.toString(1, 1)+")");// 返回jsonp格式數據
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return;
	}

}

 寫得比較簡陋,你能夠本身優化下,功能反正沒問題。

 

2.配置微信公衆號事件轉發地址:

進入微信公衆號,左側菜單找到基本配置,配置以下:

 

3.編寫菜單點擊觸發事件:

配置好後,你的自定義菜單點擊事件都會轉發到你的後臺Java方法中:

package com.odao.weixin.site.web.controller.weixinListener;

import java.io.InputStream;
import java.io.OutputStream;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.odao.weixin.api.msg.*;
import com.odao.weixin.site.subsys.listener.ListenerEventService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.odao.common.util.HttpUtil;
import com.odao.weixin.api.DefaultSession;
import com.odao.weixin.api.HandleMessageAdapter;
import com.odao.weixin.api.support.MySecurity;
import com.odao.weixin.site.util.QpMobileGameWebUtil;


@Controller
@RequestMapping("/")
public class WeiXinListenerController {
	final static Logger logger = LoggerFactory.getLogger(WeiXinListenerController.class);
	// TOKEN 是你在微信平臺開發模式中設置的哦
	public static final String TOKEN = "上圖中的Token(令牌)";
	@Autowired
	private ListenerEventService listenerEventService;

	@RequestMapping("weiXinListener.do")
	protected void handleRequestInternal(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String method = request.getMethod();
		logger.debug("請求類型:" + method);
		if ("GET".equals(method)) {
			doGet(request, response);

		}
		if ("POST".equals(method)) {
			doPost(request, response);

		}

	}

	/**
	 * 微信驗證
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		logger.debug("==================================================");
		logger.debug("微信驗證交互請求!!");
		Writer writer = response.getWriter();
		String signature = request.getParameter("signature");// 微信加密簽名
		String timestamp = request.getParameter("timestamp");// 時間戳
		String nonce = request.getParameter("nonce");// 隨機數
		String echostr = request.getParameter("echostr");// 隨機字符串

		// 重寫totring方法,獲得三個參數的拼接字符串
		List<String> list = new ArrayList<String>(3) {
			private static final long serialVersionUID = 2621444383666420433L;

			public String toString() {
				return this.get(0) + this.get(1) + this.get(2);
			}
		};
		list.add(TOKEN);
		list.add(timestamp);
		list.add(nonce);
		try {
			Collections.sort(list);// 排序
			String tmpStr = new MySecurity().encode(list.toString(),
					MySecurity.SHA_1);// SHA-1加密

			if (signature.equals(tmpStr)) {
				QpMobileGameWebUtil.writeString(writer, echostr);
			} else {
				QpMobileGameWebUtil.writeString(writer, "");
			}
		} catch (Exception e) {
			QpMobileGameWebUtil.writeString(writer, "");
		}

	}

	/**
	 * 微信監聽
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		logger.debug("==================================================");
		logger.debug("微信監聽請求!");

		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=utf-8");
		InputStream is = request.getInputStream();
		OutputStream os = response.getOutputStream();

		final DefaultSession session = DefaultSession.newInstance();
		final String uploadPath = request.getSession().getServletContext()
				.getRealPath("/");// 獲取項目路徑
		// 請求IP
		final String requestIP = HttpUtil.getIpAddr(request);

		// 處理事件(事件都會到此處)
		session.addOnHandleMessageListener(new HandleMessageAdapter() {
			// 獲取基礎token
			public void onEventMsg(Msg4Event msg) {
				listenerEventService.onEventMsg(session, msg, requestIP,uploadPath);
			}
		}

		);

		session.process(is, os);// 處理微信消息
		session.close();// 關閉Session

	}

}

咱們來看看listenerEventService.onEventMsg(session, msg, requestIP,uploadPath)方法:

package com.odao.weixin.site.subsys.listener;

import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;
import com.odao.weixin.api.DefaultSession;
import com.odao.weixin.api.msg.Msg4Event;
import com.odao.weixin.api.msg.Msg4Text;
import com.odao.weixin.api.msg.UserInfo;
import com.odao.weixin.api.support.AccessTokenKit;
import com.odao.weixin.site.cases2017.wxpay.service.SyncXMLUtils;
import com.odao.weixin.site.core.GlobalThreadLocal;
import com.odao.weixin.site.subsys.MenuEvent.MenuEventSys;
import com.odao.weixin.site.subsys.config.WeiXinProcessConfigSys;
import com.odao.weixin.site.subsys.publicsys.UserManager;
import com.odao.weixin.site.subsys.user.GameUserSys;

/**
 * 微信監聽處理事件
 * 
 * @author Administrator
 *
 */
@Service
public class ListenerEventService {

	final static Logger logger = LoggerFactory.getLogger(ListenerEventService.class);
	
	private String respContent;
	
	/**
	 * 處理事件
	 * 
	 * @param session
	 * @param msg
	 */
	public void onEventMsg(DefaultSession session, Msg4Event msg,String requestIP, String uploadPath) {
		String eventType = msg.getEvent();
		// ============================訂閱關注=============================================
		if (Msg4Event.SUBSCRIBE.equals(eventType)) {
			Msg4Text reMsg = new Msg4Text();
			reMsg.setFromUserName(msg.getToUserName());
			reMsg.setToUserName(msg.getFromUserName());
			reMsg.setCreateTime(msg.getCreateTime());
			reMsg.setContent(respContext);
			session.callback(reMsg);// 回傳消息
		}
		// ============================已經關注了的==========================================
		else if (Msg4Event.SCAN.equals(eventType)) {}
		// ============================取消訂閱=============================================
		else if (Msg4Event.UNSUBSCRIBE.equals(eventType)) {}
		// ============================點擊事件=============================================
		else if (Msg4Event.CLICK.equals(eventType)) {
            //kfrx就是你以前配置菜單時定義的contentText列內容
            if("kfrx".equals(msg.getEventKey())){
                 //do something you want....
            }
         } } }

 上述列舉了菜單中點擊觸發的4中類型,訂閱關注、已經關注了的、取消關注、點擊事件(你以前配置的click)

按照上述操做一步步來,你的自定義菜單就完成啦

不過你開了本身的自定義菜單,公衆號中的自定義菜單就被禁用啦,看你本身的需求,究竟是本身去公衆號配置自定義菜單,仍是本身開發自定義回覆的才慘吧。

相關文章
相關標籤/搜索