第一步 先去申请一个测试号,在微信公众平台申请一个就可以了
第二步 去弄一个花生壳账号搞一个域名 进行内网穿透
第三步 在测试号的管理系统
在这个地方填上申请的域名
然后就是代码了
首先 先给微信测号写一个菜单
写菜单的准备工作 需要获取先获取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了,先写到这里