How to obtain and save interface call credentials on WeChat, I will introduce it to you below
1. Explanation
* Please refer to the first two articles for detailed instructions.
*This article is divided into three parts:
The role of interface call credential access_token and explain how to obtain interface call credential access_token
How to implement the implementation of the "central control server" mentioned in the WeChat document to save access_token
* At the end of this article, all demonstration source codes including the first three articles in this article will be given.
Why do you need to obtain and save interface call credentials access_token
• Begin development - get interface call credentials
◦Document address: http://mp.weixin.qq.com/wiki/14/9f9c82c1af308e3b14ba9b973f99a8ba.html
•The official website document gives the following explanation:
◦Access_token is the globally unique ticket of the official account. Access_token is required when calling each interface of the official account. Developers need to save it properly. The storage of access_token must retain at least 512 character space. The validity period of access_token is currently 2 hours and needs to be refreshed regularly. Repeated acquisition will cause the access_token you obtained last time to be invalid.
•understand:
◦We can simply read the document and find that many advanced functions, such as: custom menu, material management, user management, account management and other advanced functions, have the parameter "?access_token=TOKEN" in the links for requests. This is a global call parameter. The WeChat backend needs to determine the identity based on this parameter to ensure the security of our WeChat official account.
◦In order to prevent the WeChat server load exception from being caused by program errors in the official account, by default, the call interface of each official account cannot exceed a certain limit. Here, WeChat is limited to 2,000 times a day. So, if we want to call this parameter frequently, we need to save it manually by the developer, and each access_token is valid for 2 hours.
Get interface call credential access_token
•The official website document gives the following explanation:
◦Interface call request description
http request method: GET
https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
■Return to the description
Under normal circumstances, WeChat will return the following JSON packet to the official account:
{"access_token":"ACCESS_TOKEN","expires_in":7200}
When error occurs, WeChat will return error codes and other information. The example of JSON packet is as follows (this example is an invalid AppID error):
{"errcode":40013,"errmsg":"invalid appid"}
•understand:
◦GET request, this method can be implemented directly locally. Because it's just a normal GET request, similar to accessing a URL. Therefore, you don’t need to upload this part of the code to the server to operate directly.
◦The http request protocol is a GET request, which means that we need to obtain the return stream through the GET request, and the return stream is in the form of json. When calling, we need to carry three parameters: grant_type, appid, and secret. Among them, appid and secret are the key parameters of our WeChat official account, which have been explained in the previous article. The return result is divided into two types: correct and wrong results. 【Baidu: json】
◦In fact, we can directly enter the example given by the document in the address bar: https://api.weixin.qq.com/cgi-bin/token? grant_type=client_credential&appid=APPID&secret=APPSECRET, we will see the message like this: "{"errcode":40013,"errmsg":"invalid appid hint: [pQKl0120ic11]"}", because this is an invalid request, the result is returned with an error.
◦When we replace the above two parameters with our test numbers APPID and APPSECRET, we will see the following message: "{"access_token":"XrllR3fNf...bADAMIO", "expires_in":7200}", which means successful acquisition.
◦Now we get the return stream through the java code and get the access_token.
•accomplish
private static final long MAX_TIME = 7200 * 1000;// WeChat allows maximum Access_token validity time (ms) private static final String TAG = "WeixinApiTest";// TAGprivate static final String APPID = "wx889b****b3666b0b8";// APPIDprivate static final String SECERT = "6da7676***f0a9f15fbf06027856bb";// Secret key/* * This test case demonstrates how to obtain access_token. * access_token is the globally unique ticket of the official account. Access_token is required when calling each interface of the official account. */@Testpublic void getAccess_token() throws IOException { // Stitch the httpsurl link required by the API String urlString = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + APPID + "&secret=" + SECERT; // Create a url URL reqURL = new URL(urlString); // Get the link HttpsURLConnection httpsConn = (HttpsURLConnection) reqURL .openConnection(); // Get the input stream of the connection to read the response content InputStreamReader isr = new InputStreamReader( httpsConn.getInputStream()); // Read the server's response content and display char[] chars = new char[1024]; String reslut = ""; int len; while ((len = isr.read(chars)) != -1) { reslut += new String(chars, 0, len); } isr.close(); /* * Convert json to javabean. A third-party jar was introduced:GSON */ Gson gson = new Gson();// Convert the obtained json into a bean in java // Note: Access_token access_token is a javabean created by itself. Access_token access_token = gson.fromJson(reslut, new Access_token().getClass()); if (access_token.getAccess_token() != null) { System.out.println("The obtained access_token is: " + access_token.getAccess_token()); System.out.println("The valid time of the access_token is: " + access_token.getExpires_in() + "s"); } else { System.out.println(TAG + "Failed to obtain access_token, please check"); }} Save interface call credential access_token
•Thoughts
Store the obtained Access_token and the current time in the file. When extracting, determine the time difference between the current time and the time recorded in the storage. If it is greater than MAX_TIME, re-acquire it, and replace the obtained accessed content in the file. If it is less than MAX_TIME, directly obtain it.
•accomplish
/* * This method implements the acquisition of Access_token, save and save only 2 hours of Access_token. If it exceeds two hours, re-acquire it; if it does not exceed two hours, obtain it directly. This method depends on *: public static String getAccessToken(); * * Idea: Store the obtained Access_token and the current time in the file, * When extracting, determine the time difference between the current time and the time recorded in the storage. If it is greater than MAX_TIME, re-acquire it, and store the obtained access to the file to replace the original content*, and if it is less than MAX_TIME, obtain it directly. */ @Test public void getSavedAccess_token() throws IOException { Gson gson = new Gson(); String mAccess_token = null;// Access_token to be obtained; File file = new File("temp_access_token.temp");// The location where Access_token is saved// If the file does not exist, create if (!file.exists()) file.createNewFile(); // If the file size is equal to 0, it means that it is used for the first time, and save Access_token if (file.length() == 0) { mAccess_token = getAccessToken(); FileOutputStream fos = new FileOutputStream(file, false);// Append Access_token at = new Access_token(); at.setAccess_token(mAccess_token); at.setExpires_in(System.currentTimeMillis() + ""); String json = gson.toJson(at); fos.write((json).getBytes()); fos.close(); } else { // Read file content FileInputStream fis = new FileInputStream(file); byte[] b = new byte[2048]; int len = fis.read(b); String mJsonAccess_token = new String(b, 0, len);// Read the file content Access_token access_token = gson.fromJson(mJsonAccess_token, new Access_token().getClass()); if (access_token.getExpires_in() != null) { long saveTime = Long.parseLong(access_token.getExpires_in()); long nowTime = System.currentTimeMillis(); long remianTime = nowTime - saveTime; // System.out.println(TAG + "Time Difference:" + remianTime); if (remianTime < MAX_TIME) { Access_token at = gson.fromJson(mJsonAccess_token, new Access_token().getClass()); mAccess_token = at.getAccess_token(); } else { mAccess_token = getAccessToken(); FileOutputStream fos = new FileOutputStream(file, false);// Append Access_token at = new Access_token(); at.setAccess_token(mAccess_token); at.setExpires_in(System.currentTimeMillis() + ""); String json = gson.toJson(at); fos.write((json).getBytes()); fos.close(); } } } System.out.println("The access_token obtained is: " + mAccess_token); } /* * Get the WeChat server AccessToken. This part is consistent with getAccess_token(), no comments are added*/ public static String getAccessToken() { String urlString = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + APPID + "&secret=" + SECERT; String reslut = null; try { URL reqURL = new URL(urlString); HttpsURLConnection httpsConn = (HttpsURLConnection) reqURL .openConnection(); InputStreamReader isr = new InputStreamReader( httpsConn.getInputStream()); char[] chars = new char[1024]; reslut = ""; int len; while ((len = isr.read(chars)) != -1) { reslut += new String(chars, 0, len); } isr.close(); } catch (IOException e) { e.printStackTrace(); } Gson gson = new Gson(); Access_token access_token = gson.fromJson(reslut, new Access_token().getClass()); if (access_token.getAccess_token() != null) { return access_token.getAccess_token(); } else { return null; } } The first three articles demonstrate the source code: http://xiazai.VeVB.COM/201606/yuanma/WeixinApiDemo(VeVB.COM).rar
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.