To obtain access_token, please refer to Obtaining access_token on WeChat public platform
Because the validity period of the access_token is currently 2 hours, it needs to be refreshed regularly. Repeated acquisition will invalidate the access_token obtained last time. And the number of times to get it per day is limited, so you can do a cache. The caching method depends on your needs.
My specific code implementation is as follows:
AccessToken.java
public class AccessToken { private String id; private String accessToken; private int expiresIn; public String getAccessToken() { return accessToken; } public void setAccessToken(String accessToken) { this.accessToken = accessToken; } public int getExpiresIn() { return expiresIn; } public void setExpiresIn(int expiresIn) { this.expiresIn = expiresIn; } public String getId() { return id; } public void setId(String id) { this.id = id; } }
AccessTokenCache.java
/** * Singleton design mode cache accessToken expires_in */ public class AccessTokenCache { //Cache the Map of accessToken, the map contains accessToken, expiresIn and the cached timestamp time private Map<String, String> map = new HashMap<String,String>(); private static AccessTokenCache accessTokenCache = null; private AccessTokenCache() { } // static factory method public static AccessTokenCache getInstance() { if (accessTokenCache == null) { accessTokenCache = new AccessTokenCache(); } return accessTokenCache; } public Map<String, String> getMap() { return map; } public void setMap(Map<String, String> map) { this.map = map; } /** * Get accessToken expires_in * @param appid third-party user unique credentials * @param appsecret third-party user unique credential key * @return */ public Map<String,Object> getAcessTokenAndExpiresIn(String appid, String appsecret) { Map<String,Object> result = new HashMap<String,Object>(); AccessTokenCache accessTokenCache = AccessTokenCache.getInstance(); Map<String, String> map = accessTokenCache.getMap(); String time = map.get("time"); String accessToken = map.get("access_token"); String expiresIn = map.get("expires_in"); Long nowDate = new Date().getTime(); if (accessToken != null && time != null && expiresIn!=null) { //Set the expiration time here to the expiration time specified by WeChat minus 5 minutes int outTime = (Integer.parseInt(expiresIn)-300) * 1000; if (nowDate - Long.parseLong(time) < outTime) { System.out.println("-----Read access_token from cache: " + accessToken); // Get the data from the cache and assign the returned result result.put("access_token", accessToken); result.put("expires_in", expiresIn); } } else { AccessToken info = WeiXinUtil.getAccessToken(appid, appsecret);//In fact, you need to call the WeChat interface yourself to get accessToken and expires_in System.out.println("-----Get access_token by calling WeChat interface: " + info.getAccessToken()); // put the information in the cache map.put("time", nowDate + ""); map.put("access_token", info.getAccessToken()); map.put("expires_in", info.getExpiresIn()+""); //assign the return result result.put("access_token", info.getAccessToken()); result.put("expires_in", info.getExpiresIn()); } return result; } }
The method of calling the WeChat API to obtain the accessToken. WeiXinUtil.java
// Get the interface address of access_token (GET), limited to 2000 (times/day) public final static String access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
public class WeiXinUtil { private static Logger log = LoggerFactory.getLogger(WeiXinUtil.class); /** * Get access_token * @param appid credentials * @param appsecret key * @return */ public static AccessToken getAccessToken(String appid, String appsecret) { AccessToken accessToken = null; String requestUrl = WXConstants.access_token_url.replace("APPID", appid).replace("APPSECRET", appsecret); JSONObject jsonObject = httpRequest(requestUrl, "GET", null); // if the request was successful if (null != jsonObject) { try { accessToken = new AccessToken(); accessToken.setAccessToken(jsonObject.getString("access_token")); accessToken.setExpiresIn(jsonObject.getInt("expires_in")); } catch (JSONException e) { accessToken = null; // Failed to get token log.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg")); } } return accessToken; } /** * Description: initiate an https request and get the result * @param requestUrl request address * @param requestMethod request method (GET, POST) * @param outputStr Submitted data * @return JSONObject (get the attribute value of the json object by JSONObject.get(key)) */ public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) { JSONObject jsonObject = null; StringBuffer buffer = new StringBuffer(); try { // Create an SSLContext object and initialize it with our specified trust manager TrustManager[] tm = { new MyX509TrustManager() }; SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); sslContext.init(null, tm, new java.security.SecureRandom()); // Get the SSLSocketFactory object from the above SSLContext object SSLSocketFactory ssf = sslContext.getSocketFactory(); URL url = new URL(requestUrl); HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection(); httpUrlConn.setSSLSocketFactory(ssf); httpUrlConn.setDoOutput(true); httpUrlConn.setDoInput(true); httpUrlConn.setUseCaches(false); // Set the request method (GET/POST) httpUrlConn.setRequestMethod(requestMethod); if ("GET".equalsIgnoreCase(requestMethod)) httpUrlConn.connect(); // when there is data to submit if (null != outputStr) { OutputStream outputStream = httpUrlConn.getOutputStream(); // Pay attention to the encoding format to prevent Chinese garbled characters outputStream.write(outputStr.getBytes("UTF-8")); outputStream.close(); } // Convert the returned input stream to a string InputStream inputStream = httpUrlConn.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(); // release resources inputStream.close(); inputStream = null; httpUrlConn.disconnect(); jsonObject = JSONObject.fromObject(buffer.toString()); } catch (ConnectException ce) { log.error("Weixin server connection timed out."); } catch (Exception e) { log.error("https request error:{}", e); } return jsonObject; } }
MyX509TrustManager.java
import javax.net.ssl.X509TrustManager; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; /** * Write a program to simulate an https connection and obtain a token. For https requests, we need a certificate trust manager. This manager class needs to be defined by itself, but it needs to implement the X509TrustManager interface * description: certificate trust manager (for https requests) */ public class MyX509TrustManager implements X509TrustManager { // Check client certificate public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } // Check server side certificate public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } // Returns an array of trusted X509 certificates public X509Certificate[] getAcceptedIssuers() { return null; } }
// You can call AccessTokenCache in the main method to get access_token Map<String,Object> map = AccessTokenCache.getInstance().getAcessTokenAndExpiresIn(WXConstants.APPID, WXConstants.APPSECRET); String accessToken = (String)map.get("access_token");
The console prints the result: