第一步 先去申請一個測試號,在微信公眾平台申請一個就可以了
第二步 去弄一個花生殼賬號搞一個域名 進行內網穿透
第三步 在測試號的管理系統
在這個地方填上申請的域名
然后就是代碼了
首先 先給微信測號寫一個菜單
寫菜單的准備工作 需要獲取先獲取access_token(記住這是接口的access_token,和網頁的access_token不一樣)
/**
* 獲取接口acessToken
* @return
*/
public Map<String,Object> getAccessToken()throws Exception{
Map<String,Object> map = new HashMap<String, Object>();
Long nowTime = new Date().getTime();
//判斷accessToken是否緩存 且是否過期
if(ACCESS_TOKEN_TIME < nowTime){
String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
String APPID = ConfigUtil.APPID;
String SECRET = ConfigUtil.SECRET;
url = url.replace("APPID", APPID);
url = url.replace("APPSECRET", SECRET);
String content = HttpUtil.httpUrlConnect(url, null, "GET");
map = getAccessTokenByJsonStr(content);
//獲取新的有效時間 單位秒
Long newExpiresTime = Long.valueOf(map.get("expires_in").toString()) ;
//將access_token的有效時間更新(有效時間默認減少5分鍾,避免意外)
ACCESS_TOKEN_TIME = newExpiresTime*1000+nowTime-30000;
//將access_token更新
tempData.put("access_token", map.get("access_token").toString());
}else{
map.put("access_token", tempData.get("access_token"));
}
return map;
}
這里的appid、secret是在測試號系統里面的
這是訪問網頁的方法
public static String httpUrlConnect(String httpUrl,String params,String method)throws Exception{
URL url = new URL(httpUrl);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setRequestProperty("accept", "*/*");
urlConnection.setRequestProperty("connection", "Keep-Alive");
urlConnection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setRequestMethod(method);
urlConnection.connect();
PrintWriter out = null;
BufferedReader in = null;
if(null != params && !"".equals(params)){
out = new PrintWriter(new OutputStreamWriter(
urlConnection.getOutputStream(), "utf-8"));
out.print(params);
out.flush();
}
in = new BufferedReader(
new InputStreamReader(urlConnection.getInputStream(), "utf-8"));
String line;
String result = "";
while ((line = in.readLine()) != null) {
result += line;
}
return result;
}
/**
* 根據字符串json數據解析access_token
* @param jsonStr
* @return map
*/
private Map<String,Object> getAccessTokenByJsonStr(String jsonStr){
Map<String,Object> map = new HashMap<String, Object>();
JSONObject jsonObj = new JSONObject(jsonStr);
if(jsonObj.has("access_token")){
map.put("access_token", jsonObj.get("access_token"));
}
if(jsonObj.has("expires_in")){
map.put("expires_in", jsonObj.get("expires_in"));
}
return map;
}
然后就獲取到accessctoken了,先寫到這里