In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly shows you "how to ensure the long-term effectiveness of access_token in the development of Wechat public platform". The content is simple and clear. I hope it can help you solve your doubts. Now let me lead you to study and learn this article "how to ensure the long-term effectiveness of access_token in the development of Wechat public platform".
In order to enable third-party developers to provide users with more and more valuable personalized services, Wechat public platform opens many interfaces, including custom menu API, customer service API, user information acquisition API, user grouping interface, group sending interface, etc. When calling these interfaces, developers need to pass in the same parameter access_token, which is the unique global ticket for public account and the access certificate of the interface.
The validity period of access_token is 7200 seconds (two hours). It can be used all the time during the validity period. Only when the access_token expires, you need to call the API again to obtain the access_token. Ideally, a system running 7x24 hours only needs to get access_token 12 times a day, that is, every 2 hours. If the access_token is obtained again within the validity period, the last acquired access_token will be invalidated.
Currently, the frequency of calling the access_token API is limited to 2000 / day. It is obviously unreasonable to call the access_token API to obtain the API access credential before sending customer service messages, obtaining user information, or sending messages in groups. On the one hand, it will be more time-consuming (one more API call operation), and on the other hand, the limit of 2000 calls per day may not be enough. Therefore, in practical application, we need to store the acquired access_token, and then call the access_token API to update it periodically to ensure that the access_token fetched at any time is valid.
Before we start, let's make a brief analysis. What we have to solve is nothing more than the following two problems:
1. How to obtain access_token regularly?
In Java, if you want to perform a task regularly, you need to use the java.util.Timer class. For friends who like to use the framework, you can use the open source task scheduling framework, quartz,Spring framework, which also supports quartz. In addition to this, another way is to start a thread, write an endless loop in the thread's run () method, and then use Thread.sleep () to ensure that the thread executes a task on a regular basis.
two。 Where do I save the access_token?
For access_token storage, consider storing it in a file, database, or memory. The specific storage method needs to be based on the actual situation of the project. If you have only one server, storing access_token directly in memory is the easiest and most efficient way.
In this article, the author demonstrates the process of periodically fetching and storing access_token as follows: loading a Servlet when the Web server starts, starting a thread in the init () method of Servlet, obtaining access_token periodically in the thread's run () method through an endless loop + Thread.sleep (), and then saving the acquired access_token in public static-decorated variables.
Create an InitServlet class in the project with the following code:
Package org.liufeng.weixin.servlet; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import org.liufeng.weixin.thread.TokenThread; import org.liufeng.weixin.util.WeixinUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; / * initialize servlet * * @ author liuyq * @ date 2013-05-02 * / public class InitServlet extends HttpServlet {private static final long serialVersionUID = 1L Private static Logger log = LoggerFactory.getLogger (WeixinUtil.class); public void init () throws ServletException {/ / get the parameter TokenThread.appid = getInitParameter ("appid") configured in web.xml; TokenThread.appsecret = getInitParameter ("appsecret"); log.info ("weixin api appid: {}", TokenThread.appid) Log.info ("weixin api appsecret: {}", TokenThread.appsecret); / / prompt if (".equals (TokenThread.appid) | |" .equals (TokenThread.appsecret)) {log.error ("appid and appsecret configuration error, please check carefully.") when appid and appsecret are not configured. } else {/ / thread new Thread (new TokenThread ()) .start ();} that starts the timed acquisition of access_token
As you can see from the above code, the InitServlet class only overrides the init () method, not the doGet () and doPost () methods, because we don't intend to let InitServlet handle the access request. The implementation of the init () method is also relatively simple, first getting the parameters appid and appsecret configured in web.xml, and then starting the thread TokenThread to get access_token on time.
The configuration of InitServlet in web.xml is as follows:
Http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> initServlet org.liufeng.weixin.servlet.InitServlet appid wx617a123bb8bc99cd appsecret 4d82cbbbb08714c12345b62d7hn3dcb8 0 index.jsp
The configuration of InitServlet in web.xml is different from that of ordinary Servlet: 1) pass parameters to Servlet through configuration; 2) configure so that the Servlet;3 is loaded when the Web server starts) there is no configuration, because InitServlet does not provide external access.
The source code for TokenThread is as follows:
Package org.liufeng.weixin.thread; import org.liufeng.weixin.pojo.AccessToken; import org.liufeng.weixin.util.WeixinUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; / * Thread that regularly obtains Wechat access_token * * @ author liuyq * @ date 2013-05-02 * / public class TokenThread implements Runnable {private static Logger log = LoggerFactory.getLogger (TokenThread.class) / / third-party user unique credentials public static String appid = ""; / / third-party user unique credential keys public static String appsecret = ""; public static AccessToken accessToken = null; public void run () {while (true) {try {accessToken = WeixinUtil.getAccessToken (appid, appsecret) If (null! = accessToken) {log.info ("obtain access_token successfully, valid duration {} seconds token: {}", accessToken.getExpiresIn (), accessToken.getToken ()); / / dormant 7000 seconds Thread.sleep ((accessToken.getExpiresIn ()-200) * 1000) } else {/ / if access_token is null,60, then get Thread.sleep (60 * 1000);}} catch (InterruptedException e) {try {Thread.sleep (60 * 1000) } catch (InterruptedException E1) {log.error ("{}", E1);} log.error ("{}", e);}}
Line 23 of the code constructs an endless loop (permanent execution) through while (true) {}; line 25 calls the public platform interface to get line 29 of access_token; and leaves the thread dormant for 7000 seconds, that is, to get the access_token every 7000 seconds to ensure that the access_token never fails. For other classes in the project, you can get the interface access credential access_token by calling TokenThread.accessToken.getToken (). Run the program locally, and after Tomcat starts, the following log will be displayed on the console:
[INFO] weixin api appid:wx617a123bb8bc99cd [INFO] weixin api appsecret:4d82cbbbb08714c12345b62d7hn3dcb8 [INFO] obtained access_token successfully. The valid duration is 7200 seconds token:sFopJ9lMmLl4u-ad61ojKpS0TolhN2s3SnHoI2Mh6GgdiYb35i-7DG2T2CDyQKMe.
To see the effect of getting access_token on a regular basis, try changing the thread sleep time in TokenThread to 30 or 60 seconds.
These are all the contents of this article entitled "how to ensure the long-term effectiveness of access_token in the Development of Wechat Public platform". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.