위챗 공식번호 개발, 코드 사용자 정의 메뉴

package com.wzqj.wsp.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.wzqj.wsp.http.HttpUtil;
import com.wzqj.wsp.prop.PropertiesUtil;
import org.apache.commons.lang3.StringUtils;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class MenuUtils {

	/**
	 *   accessToken
	 */
	public static String getAccessToken(String appid, String appsecret) {
		String uri = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
				+ appid + "&secret=" + appsecret;
		String jsonStr = getJSONStr(uri);
		JSONObject object = JSONObject.parseObject(jsonStr);
		String access_token = object.getString("access_token");
		// ACCESS_TOKEN_CACHE.put(ACCESS_TOKEN_KEY, access_token);
		return access_token;
	}

	/**
	 *     
	 */
	public static String getMenuInfo(String accessToken) throws Exception {
		String uri = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token="
				+ accessToken;
		return getJSONStr(uri);
	}

	/**
	 *        
	 */
	public static void createMenu(String meunStr, String accessToken) {
		System.out.println("wirte menu--->" + meunStr);
		if (StringUtils.isBlank(meunStr)) {
			return;
		}
		StringBuffer bufferRes = new StringBuffer();
		try {
			URL realUrl = new URL(
					"https://api.weixin.qq.com/cgi-bin/menu/create?access_token="
							+ accessToken);
			HttpURLConnection conn = (HttpURLConnection) realUrl
					.openConnection();
			//     
			conn.setConnectTimeout(25000);
			//      --        ,    
			conn.setReadTimeout(25000);
			HttpURLConnection.setFollowRedirects(true);
			//     
			conn.setRequestMethod("POST");
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setRequestProperty("User-Agent",
					"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0");
			conn.setRequestProperty("Referer", "https://api.weixin.qq.com/");
			conn.connect();
			//   URLConnection        
			OutputStreamWriter out = new OutputStreamWriter(
					conn.getOutputStream());
			//       
			// out.write(URLEncoder.encode(params,"UTF-8"));
			out.write(meunStr);
			out.flush();
			out.close();
			InputStream in = conn.getInputStream();
			BufferedReader read = new BufferedReader(new InputStreamReader(in,
					"UTF-8"));
			String valueString = null;
			while ((valueString = read.readLine()) != null) {
				bufferRes.append(valueString);
			}
			System.out.println(bufferRes.toString());
			in.close();
			if (conn != null) {
				conn.disconnect();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 *        
	 */
	/*
	 * public static String getDelMenuInfo(String accessToken) throws Exception
	 * { String uri =
	 * "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=" +
	 * accessToken; String jsonStr = getJSONStr(uri); JSONObject object =
	 * JSONObject.parseObject(jsonStr); return object.getString("errmsg"); }
	 */

	/**
	 *   get    json  
	 *
	 * @param url
	 * @return
	 */
	private static String getJSONStr(String url) {
		try {
			return HttpUtil.getResult(url);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;

	}

	/**
	 *              
	 * 
	 * @param token
	 * @param sceneid
	 * @return
	 */
	/*
	 * public static String createTicket(String token,long sceneid){ String url
	 * = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=%s"; url
	 * = String.format(url, token); String jsonStr = ""; Map<String, Object>
	 * params = new HashMap<String,Object>(); Map<String, Object> scenes = new
	 * HashMap<String,Object>(); Map<String, Object> scene = new
	 * HashMap<String,Object>(); scene.put("scene_id",sceneid);
	 * scenes.put("scene",scene); params.put("expire_seconds",604800);
	 * params.put("action_name","QR_SCENE"); params.put("action_info",scenes);
	 * try {jiamin gg lasses jsonStr = HttpUtil.requestPostJSON(url, params); }
	 * catch (Exception e) { e.printStackTrace(); } JSONObject object =
	 * JSONObject.parseObject(jsonStr); return object.toJSONString(); }
	 */

	public static void main(String[] args) {
		try {
			String token = getAccessToken("xxx", "xxx");// appid,secret
			long sceneid = 3333333;
			System.out.println("token===>" + token);
			JSONObject subBtn1 = new JSONObject();
			subBtn1.put("type", "view");
			subBtn1.put("name", "  ");
			subBtn1.put("url", "http://xxx");
			JSONObject subBtn2 = new JSONObject();
			subBtn2.put("type", "view");
			subBtn2.put("name", "    ");
			subBtn2.put("url", "http://xxx");
			JSONObject subBtn3 = new JSONObject();
			subBtn3.put("type", "view");
			subBtn3.put("name", "    ");
			subBtn3.put("url", "http://xxx");
			JSONObject subBtn4 = new JSONObject();
			subBtn4.put("type", "view");
			subBtn4.put("name", "    ");
			subBtn4.put("url", "http://xxx");
			JSONObject subBtn = new JSONObject();
			JSONArray array = new JSONArray();
			array.add(subBtn1);
			array.add(subBtn2);
			array.add(subBtn3);
			array.add(subBtn4);
			subBtn.put("name", "xx  ");
			subBtn.put("sub_button", array);
			JSONObject btn = new JSONObject();

			JSONObject subB003 = new JSONObject();
			subB003.put("type", "click");
			subB003.put("name", "    ");
			subB003.put("key", "wxcustomer");
			JSONArray array003 = new JSONArray();
			array003.add(subB003);

			JSONArray arrayBtn = new JSONArray();
			// arrayBtn.add(subB001);
			arrayBtn.add(subBtn);
			arrayBtn.add(subB003);
			btn.put("button", arrayBtn);
			String newMenu = btn.toString();
			System.out.println(newMenu);
			/**
			 *            { "button": [ {"type":"click", "name":"   ",
			 * "key":"   " }, { "name": "    ", "sub_button": [ { "type":
			 * "view", "name": "  ", "url": "http: //xxxx" }, { "type": "view",
			 * "name": "    ", "url": "http: //xxxx" }, { "type": "view",
			 * "name": "    ", "url": "http: //xxxx" }, { "type": "view",
			 * "name": "    ", "url": "http: //xxxx" } ] }, {"type":"click",
			 * "name":"   ", "key":"   " } ] }
			 */
			createMenu(newMenu, token);
			String menu = getMenuInfo(token);
			System.out.println("menu===>" + menu);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

좋은 웹페이지 즐겨찾기