我是靠谱客的博主 还单身哈密瓜,最近开发中收集的这篇文章主要介绍微信公众号菜单接口,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

文章目录

        • 1、实现效果
        • 2、注意事项
        • 3、实现步骤
        • 4、代码实现(主菜)
          • 前端页面
          • 工具类
          • accesstoken获取
          • 获取公众号菜单
          • 保存公众号菜单

1、实现效果

目前仅支持自定义菜单名称、增减菜单、外链设置,暂无图文信息
在这里插入图片描述

2、注意事项

  1. 自定义菜单最多包括3个一级菜单,每个一级菜单最多包含5个二级菜单。
  2. 一级菜单最多4个汉字,二级菜单最多7个汉字,多出来的部分将会以“…”代替。
  3. 创建自定义菜单后,菜单的刷新策略是,在用户进入公众号会话页或公众号profile页时,如果发现上一次拉取菜单的请求在5分钟以前,就会拉取一下菜单,如果菜单有更新,就会刷新客户端的菜单。测试时可以尝试取消关注公众账号后再次关注,则可以看到创建后的效果。

3、实现步骤

0)、参考官方文档:https://developers.weixin.qq.com/doc/offiaccount/Custom_Menus/Creating_Custom-Defined_Menu.html

1)、搞一套前端代码

2)、获取公众号菜单

接口调用请求说明

http请求方式: GET(请使用https协议)

https://api.weixin.qq.com/cgi-bin/get_current_selfmenu_info?access_token=ACCESS_TOKEN

3)、保存公众号菜单

接口调用请求说明

http请求方式:POST(请使用https协议)

https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN

4、代码实现(主菜)

前端页面

获取地址:https://download.csdn.net/download/zhanghuaiyu_35/12410999 没有金币的可以留言给我
在这里插入图片描述

工具类
package com.wf.commons.utils;

import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;

/**
 * Created by wanter on 2019/10/9.
 * 后端模拟请求
 */
public class AuthUtil {

    private static final Logger LOGGER = LogManager.getLogger(AuthUtil.class);

    public static JSONObject doGetJson(String url) throws IOException {
        JSONObject jsonObject = null;
        DefaultHttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        HttpResponse response = client.execute(httpGet);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            String result = EntityUtils.toString(entity, "UTF-8");
            jsonObject = JSONObject.fromObject(result);
        }
        httpGet.releaseConnection();
        return jsonObject;
    }

    //post请求方法
    public static String sendPost(String url, String menu) {
        String response = null;
        LOGGER.info("url: " + url);
        LOGGER.info("request: " + menu);
        try {
            CloseableHttpClient httpclient = null;
            CloseableHttpResponse httpresponse = null;
            try {
                httpclient = HttpClients.createDefault();
                HttpPost httppost = new HttpPost(url);
                StringEntity stringentity = new StringEntity(menu,
                        ContentType.create("text/json", "UTF-8"));
                httppost.setEntity(stringentity);
                httpresponse = httpclient.execute(httppost);
                response = EntityUtils
                        .toString(httpresponse.getEntity());
                LOGGER.info("response: " + response);
            } finally {
                if (httpclient != null) {
                    httpclient.close();
                }
                if (httpresponse != null) {
                    httpresponse.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }
}
accesstoken获取

如果accesstoken获取失败很可能是因为没有设置服务器白名单,公众号绑定了域名,获取accesstoken需要在服务器上调试,本地不知道怎么测试,哪位大神知道可以给我留言,谢谢。

package com.wf.commons.utils.wechat;

import com.wf.commons.utils.AuthUtil;
import com.wf.commons.utils.WeixinUtil;
import com.wf.mobile.model.AccessToken;
import net.sf.json.JSONObject;

import java.io.IOException;

/**
 * Created by wanter on 2019/10/16.
 */
public class AccessTokenTool {

    //自己的appid 和 appsecret
    private static final String APPID = WeixinUtil.APPID;
    private static final String APPSECRET = WeixinUtil.APPSECRET;
    //用于存储token
    private static AccessToken at;

    /**
     * @return
     * @throws Exception
     */
    private static AccessToken getAccessToken() throws IOException {
        String accessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
        accessTokenUrl = accessTokenUrl.replace("APPID", APPID).replace("APPSECRET", APPSECRET);
        System.out.println(" 微信全局token的url " + accessTokenUrl);

        JSONObject jsonObject = AuthUtil.doGetJson(accessTokenUrl);
        System.out.println(" jsonObject " + jsonObject);
        /**
         *  获取access_token
         *  成功返回的json : {"access_token":"ACCESS_TOKEN","expires_in":7200}
         *  失败放的json  : {"errcode":40013,"errmsg":"invalid appid"}
         *
         */
        String accessToken = jsonObject.getString("access_token");
        String expires_in = jsonObject.getString("expires_in");

        System.out.println("accessToken = " + accessToken);
        System.out.println("expires_in = " + expires_in);

        if (!jsonObject.containsKey("errcode")) {
            //创建token,并且存起来
            at = new AccessToken(expires_in, accessToken);
            return at;
        }
        return null;
    }


    /**
     * 对外提供获取 AccessTokenTool
     *
     * @return
     */
    public static String getToken() {
        if (at == null || at.isExpired() == true) {
            //logger.info("过期");
            try {
                getAccessToken();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return at.getAccess_token();
    }
}
获取公众号菜单

当前action的请求路径需要与前端请求路径一致

	@PostMapping("/getButton")
    @ResponseBody
    public Object getButton() throws IOException {
		Subject subject = SecurityUtils.getSubject();
		if (subject != null) {
			ShiroUser user = (ShiroUser) subject.getPrincipal();
			if (user != null) {
		    	String basetoken = AccessTokenTool.getToken();
		    	System.out.println("#########tooken"+basetoken+"#########");
		    	//根据token获取数据
		    	String getUrl = "https://api.weixin.qq.com/cgi-bin/get_current_selfmenu_info?access_token="+basetoken;
		    	JSONObject doGetJson = AuthUtil.doGetJson(getUrl);
		    	System.out.println("#########doGetJson"+doGetJson+"#########");
		    	return doGetJson;
			} else {
				return renderError("请先登录后再获取");
			}
		}else {
			return renderError("请先登录后再获取");
		}
    }
保存公众号菜单
	@PostMapping("saveButton")
    @ResponseBody
    public Object saveButton(String menujson) {
        Subject subject = SecurityUtils.getSubject();
        if (subject != null) {
            ShiroUser user = (ShiroUser) subject.getPrincipal();
            if (user != null) {
                String basetoken = AccessTokenTool.getToken();
                String postUrl = " https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + basetoken;
                URL url = null;//把string类型先转化为URL类型
                try {
                    url = new URL(postUrl);
                    URI uri = url.toURI();
                    String rs = AuthUtil.sendPost(uri.toString(), menujson);
                    System.out.println(rs);
                    return rs;
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (URISyntaxException e) {
                    e.printStackTrace();
                }
            } else {
                return renderError("请先登录后再设置");
            }
        } else {
            return renderError("请先登录后再设置");
        }
        return renderError("请先登录后再设置");
    }

最后

以上就是还单身哈密瓜为你收集整理的微信公众号菜单接口的全部内容,希望文章能够帮你解决微信公众号菜单接口所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(43)

评论列表共有 0 条评论

立即
投稿
返回
顶部