public JSONObject index1(Model model,HttpServletRequest request) {
String code=request.getParameter("code");
net.sf.json.JSONObject jsonObject=WeChatUtils.getOpenId(code);//获取微信用户access_token
String openid=jsonObject.getString("openid");
String access_token=jsonObject.getString("access_token");
HttpSession session=request.getSession();
session.setAttribute("access_token",access_token);
session.setAttribute("openid",openid);
System.out.println("index1-- access_token:"+access_token);
// String refresh_token =jsonObject.getString("refresh_token");
net.sf.json.JSONObject ticket =WeChatUtils.getJsapi_ticket(access_token);
String jsapi_ticket=jsonObject.getString("ticket");//通过access_token获取jsapi_ticket
System.out.println("jsapi_ticket:"+jsapi_ticket);
-------WechatUtil.java
public static JSONObject getOpenId(String code) {
String path=OAUTHUSERINFO.replace("APPID", appid).replace("SECRET", appsecret).replace("CODE", code);
System.out.println("调用微信api url:"+path);
JSONObject wxjsonObject=HttpRequest(path);
return wxjsonObject;
}
private static JSONObject HttpRequest(String requestUrl) {
JSONObject jsonObject=null;
StringBuffer buffer=new StringBuffer();
InputStream inputStream=null;
try {
URL url=new URL(requestUrl);
HttpsURLConnection httpsURLConnection=(HttpsURLConnection) url.openConnection();
httpsURLConnection.setDoOutput(true);
httpsURLConnection.setDoInput(true);
httpsURLConnection.setUseCaches(false);
//设置请求方式
httpsURLConnection.setRequestMethod("GET");
httpsURLConnection.connect();
inputStream=httpsURLConnection.getInputStream();
InputStreamReader inputStreamReader=new InputStreamReader(inputStream,"utf-8");
BufferedReader bufferedReader=new BufferedReader(inputStreamReader);
String str=null;
while((str=bufferedReader.readLine())!=null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
//释放资源
inputStream.close();
inputStream=null;
httpsURLConnection.disconnect();
jsonObject=JSONObject.fromObject(buffer.toString());
System.out.println(buffer.toString());
}catch(ConnectException ce) {
ce.printStackTrace();
System.out.println("WeChat server connection timed out");
}catch(Exception e) {
e.printStackTrace();
System.out.println("http request error:{}");
}finally {
try {
if(inputStream!=null) {
inputStream.close();
}
}catch(IOException e) {
e.printStackTrace();
}
}
return jsonObject;
}
初接触微信公众号开发, 前端传个code过来,根据code获取的access_token,获取jsapi_ticket时提示invalid credential, access_token is invalid or not latest hint
access_token是可以获取到的,可是为什么jsapi_ticket获取失败?问题出在什么地方,做的的麻烦给看看