微信公衆平臺自定義菜單建立 -JAVA

微信公衆平臺開發之自定義菜單建立JAVA源碼php

建立項目添加httpclient.jar、fastjson.jar支持html

專一微信公衆平臺app開發羣:209389987java

 

 

自定義菜單的問題總結:apache

1.自定義菜單隻有服務號能夠申請,訂閱號暫時沒法申請(繼續觀望微信的開放政策)json

2.菜單響應回覆方式能夠是【圖文】、【音樂】、【文本】三種方式api

3.自定義菜單建立以後沒法當即生效,能夠採用先取消關注,再關注的方式查看效果瀏覽器

 

 

微信自定義菜單建立官網文檔微信

 

package com.using.weixin.common.https;  
      
    import org.apache.http.client.HttpClient;  
    import org.apache.http.client.methods.HttpGet;  
    import org.apache.http.client.methods.HttpPost;  
    import org.apache.http.conn.ClientConnectionManager;  
    import org.apache.http.conn.scheme.Scheme;  
    import org.apache.http.conn.scheme.SchemeRegistry;  
    import org.apache.http.impl.client.DefaultHttpClient;  
      
    public class HttpClientConnectionManager {  
          
          
        /** 
         * 獲取SSL驗證的HttpClient 
         * @param httpClient 
         * @return 
         */  
        public static HttpClient getSSLInstance(HttpClient httpClient){  
            ClientConnectionManager ccm = httpClient.getConnectionManager();  
            SchemeRegistry sr = ccm.getSchemeRegistry();  
            sr.register(new Scheme("https", MySSLSocketFactory.getInstance(), 443));  
            httpClient =  new DefaultHttpClient(ccm, httpClient.getParams());  
            return httpClient;  
        }  
          
        /** 
         * 模擬瀏覽器post提交 
         *  
         * @param url 
         * @return 
         */  
        public static HttpPost getPostMethod(String url) {  
            HttpPost pmethod = new HttpPost(url); // 設置響應頭信息  
            pmethod.addHeader("Connection", "keep-alive");  
            pmethod.addHeader("Accept", "*/*");  
            pmethod.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");  
            pmethod.addHeader("Host", "mp.weixin.qq.com");  
            pmethod.addHeader("X-Requested-With", "XMLHttpRequest");  
            pmethod.addHeader("Cache-Control", "max-age=0");  
            pmethod.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");  
            return pmethod;  
        }  
      
        /**  
         * 模擬瀏覽器GET提交  
         * @param url  
         * @return  
         */  
        public static HttpGet getGetMethod(String url) {  
            HttpGet pmethod = new HttpGet(url);  
            // 設置響應頭信息  
            pmethod.addHeader("Connection", "keep-alive");  
            pmethod.addHeader("Cache-Control", "max-age=0");  
            pmethod.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");  
            pmethod.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/;q=0.8");  
            return pmethod;  
        }  
    }
package com.using.weixin.common.https;  
      
    import java.security.KeyManagementException;  
    import java.security.NoSuchAlgorithmException;  
      
    import javax.net.ssl.SSLContext;  
    import javax.net.ssl.TrustManager;  
      
    import org.apache.http.conn.ssl.SSLSocketFactory;  
      
    public class MySSLSocketFactory extends SSLSocketFactory{  
          
        static{  
            mySSLSocketFactory = new MySSLSocketFactory(createSContext());  
        }  
          
        private static MySSLSocketFactory mySSLSocketFactory = null;  
          
          
          
        private static SSLContext createSContext(){  
            SSLContext sslcontext = null;  
            try {  
                sslcontext = SSLContext.getInstance("SSL");  
            } catch (NoSuchAlgorithmException e) {  
                e.printStackTrace();  
            }  
            try {  
                sslcontext.init(null, new TrustManager[]{new TrustAnyTrustManager()}, null);  
            } catch (KeyManagementException e) {  
                e.printStackTrace();  
                return null;  
            }  
            return sslcontext;  
        }  
          
        private MySSLSocketFactory(SSLContext sslContext) {  
            super(sslContext);  
            this.setHostnameVerifier(ALLOW_ALL_HOSTNAME_VERIFIER);  
        }  
          
        public static MySSLSocketFactory getInstance(){  
            if(mySSLSocketFactory != null){  
                return mySSLSocketFactory;  
            }else{  
                return mySSLSocketFactory = new MySSLSocketFactory(createSContext());  
            }  
        }  
          
    }
package com.using.weixin.common.https;  
      
    import java.security.cert.CertificateException;  
    import java.security.cert.X509Certificate;  
      
    import javax.net.ssl.X509TrustManager;  
      
    /** 
     *  
     * @author Administrator 
     * 
     */  
    public class TrustAnyTrustManager implements X509TrustManager{  
      
        @Override  
        public void checkClientTrusted(X509Certificate[] chain, String authType)  
                throws CertificateException {  
              
        }  
      
        @Override  
        public void checkServerTrusted(X509Certificate[] chain, String authType)  
                throws CertificateException {  
              
        }  
      
        @Override  
        public X509Certificate[] getAcceptedIssuers() {  
            return null;  
        }  
      
    }
package com.using.weixin.common;  
      
    import org.apache.http.HttpResponse;  
    import org.apache.http.client.methods.HttpGet;  
    import org.apache.http.client.methods.HttpPost;  
    import org.apache.http.entity.StringEntity;  
    import org.apache.http.impl.client.DefaultHttpClient;  
    import org.apache.http.util.EntityUtils;  
      
    import com.alibaba.fastjson.JSON;  
    import com.alibaba.fastjson.JSONObject;  
    import com.using.weixin.common.https.HttpClientConnectionManager;  
      
    /** 
     * 微信自定義菜單建立 
     */  
    public class WxMenuUtils {  
        // http客戶端  
        public static DefaultHttpClient httpclient;  
          
        static {  
            httpclient = new DefaultHttpClient();  
            httpclient = (DefaultHttpClient) HttpClientConnectionManager.getSSLInstance(httpclient); // 接受任何證書的瀏覽器客戶端  
        }  
      
        public static void main(String[] args) {  
            try {  
                // 獲取accessToken -參數appid,secret  
                String accessToken = getAccessToken("appid", "secret");  
                System.out.println(accessToken);  
                // 建立菜單  
                //String s = "{\"button\":[{\"name\":\"休閒娛樂\",\"sub_button\":[{\"type\":\"click\",\"name\":\"笑話大全\",\"key\":\"m_joke\"},{\"type\":\"click\",\"name\":\"內涵段子\",\"key\":\"m_duanzi\"},{\"type\":\"click\",\"name\":\"爆笑圖片\",\"key\":\"m_laughImg\"}]},{\"name\":\"實用工具\",\"sub_button\":[{\"type\":\"click\",\"name\":\"天氣查詢\",\"key\":\"m_weather\"},{\"type\":\"click\",\"name\":\"公交查詢\",\"key\":\"m_bus\"}]},{\"type\":\"click\",\"name\":\"關於企特\",\"key\":\"m_about\"}]}";  
                String s = "{\"button\":[{\"name\":\"休閒娛樂\",\"sub_button\":[{\"type\":\"click\",\"name\":\"笑話大全\",\"key\":\"m_joke\"},{\"type\":\"click\",\"name\":\"內涵段子\",\"key\":\"m_duanzi\"},{\"type\":\"click\",\"name\":\"爆笑圖片\",\"key\":\"m_laughImg\"}]},{\"name\":\"實用工具\",\"sub_button\":[{\"type\":\"click\",\"name\":\"天氣查詢\",\"key\":\"m_weather\"},{\"type\":\"click\",\"name\":\"公交查詢\",\"key\":\"m_bus\"},{\"type\":\"click\",\"name\":\"功能菜單\",\"key\":\"m_sysmenu\"}]},{\"name\":\"消息示例\",\"sub_button\":[{\"type\":\"click\",\"name\":\"關於企特\",\"key\":\"m_about\"},{\"type\":\"click\",\"name\":\"圖文消息\",\"key\":\"m_imgmsg\"},{\"type\":\"click\",\"name\":\"音樂消息\",\"key\":\"m_musicmsg\"}]}]}";  
                String res = createMenu(s, accessToken);  
                System.out.println(res);  
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
        }  
          
          
        /** 
         * 建立菜單 
         */  
        public static String createMenu(String params, String accessToken) throws Exception {  
            HttpPost httpost = HttpClientConnectionManager.getPostMethod("https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + accessToken);  
            httpost.setEntity(new StringEntity(params, "UTF-8"));  
            HttpResponse response = httpclient.execute(httpost);  
            String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");  
            System.out.println(jsonStr);  
            JSONObject object = JSON.parseObject(jsonStr);  
            return object.getString("errmsg");  
        }  
      
        /** 
         * 獲取accessToken 
         */  
        public static String getAccessToken(String appid, String secret) throws Exception {  
            HttpGet get = HttpClientConnectionManager.getGetMethod("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret);  
            HttpResponse response = httpclient.execute(get);  
            String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");  
            JSONObject object = JSON.parseObject(jsonStr);  
            return object.getString("access_token");  
        }  
          
        /** 
         * 查詢菜單 
         */  
        public static String getMenuInfo(String accessToken) throws Exception {  
            HttpGet get = HttpClientConnectionManager.getGetMethod("https://api.weixin.qq.com/cgi-bin/menu/get?access_token=" + accessToken);  
            HttpResponse response = httpclient.execute(get);  
            String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");  
            return jsonStr;  
        }  
          
        /** 
         * 刪除自定義菜單 
         */  
        public static String deleteMenu(String accessToken) throws Exception {  
            HttpGet get = HttpClientConnectionManager.getGetMethod("https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=" + accessToken);  
            HttpResponse response = httpclient.execute(get);  
            String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");  
            JSONObject object = JSON.parseObject(jsonStr);  
            return object.getString("errmsg");  
        }  
    }
相關文章
相關標籤/搜索