How to ensure long-term effectiveness of access_token in WeChat public platform development

Source: Internet
Author: User
This article introduces how to ensure long-term effectiveness of access_token for public platform development. in order to enable third-party developers to provide more and more valuable personalized services to users, the public platform opens many interfaces, this includes custom menu interfaces, customer service interfaces, user information retrieval interfaces, user group interfaces, and group sending interfaces. when calling these interfaces, developers must input the same parameter access_token, it is the globally unique ticket of the public account, and it is the interface access credential.

The validity period of access_token is 7200 seconds (two hours). It can be used all the time during the validity period. you must call the interface again to obtain the access_token only when the access_token expires. In an ideal scenario, a 7x24 system only needs to obtain 12 access_token requests every two hours. If you get the access_token again within the validity period, the last access_token will be invalid.

Currently, the access_token interface can be called for a maximum of 2000 times/day. if you need to call the access_token interface to obtain the interface access credential every time you send a customer service message, obtain user information, or send a group message, this is obviously unreasonable. On the one hand, it will be more time-consuming (more than one interface call operation), and on the other hand, the limit of 2000 calls/day may not be enough. Therefore, in practical applications, we need to store the obtained access_token and call the access_token interface regularly to update it to ensure that the access_token retrieved at any time is valid.

The following describes how to obtain and store access_token on a regular basis. Note: This is not an article about how to call an interface to obtain access_token, please refer to the article "public account development tutorial 14th-custom menu creation and menu Event Response".

First, let's take a simple analysis. we have to solve the following two problems:

1. how to obtain the access_token on a regular basis?

In Java, if you want to regularly execute a task, you need to use java. util. timer class. for friends who like to use the framework, they can use the open-source job scheduling framework quartz, and the Spring Framework also supports quartz. In addition, another method is to start a Thread, write an endless loop in the run () method of the Thread, and then use the Thread. sleep () to ensure that the thread regularly executes a task.

2. Where can I save the access_token?

For the storage of access_token, you can consider storing it in files, databases, or memory. The specific storage method depends on the actual situation of the project. If there is only one server, storing access_token in the memory is the easiest and most effective method.

In this article, I will demonstrate the regular acquisition and storage of access_token process: when the Web server is started, a Servlet is loaded and a thread is enabled in the init () method of the Servlet, in the run () method of the Thread, there is an endless loop + Thread. sleep () method to regularly obtain access_token, and then save the obtained access_token in the variable modified by public static.

Create an InitServlet class in the project. the code for this class is as follows:

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 {// Obtain the web. the TokenThread parameter configured in xml. appid = getInitParameter ("appid"); TokenThread. appsecret = getInitParameter ("appsecret"); log.info ("weixin api appid :{}", TokenThread. appid); log.info ("weixin api appsecret :{}", TokenThread. appsecret); // if ("") is displayed when appid and appsecret are not configured ("". equals (TokenThread. appid) | "". equals (TokenThread. appsecret) {log. error ("appid and appsecret configuration error, please check carefully. ");} else {// The new Thread (new TokenThread () that obtains the access_token at startup time ()). start ();}}}

From the code above, we can see that the InitServlet class only overrides the init () method, and does not overwrite the doGet () and doPost () methods, because we do not intend to let InitServlet process access requests. The implementation of the init () method is also relatively simple. first obtain the appid and appsecret parameters configured in web. xml, and then start the thread TokenThread to regularly obtain access_token.

The configuration of InitServlet in web. xml is as follows:

     
             
              
   
    
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 common Servlet: 1) configuring Input parameters to the Servlet; 2) pass the configuration Make the Servlet load when the Web server starts; 3) no configuration Because InitServlet does not provide external access.

The source code of 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;/*** the thread that regularly obtains access_token ** @ author liuyq * @ date 2013-05-02 */public class TokenThread implements Runnable {private static Logger log = LoggerFactory. getLogger (TokenThread. class); // The unique credential of a third-party user public static String app Id = ""; // The unique credential key of a third-party user. 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 ("access_token retrieved successfully, validity period {} seconds token: {}", accessToken. getExpiresIn (), accessToken. getToken (); // sleep for 7000 seconds Thread. sleep (accessToken. getExpiresIn ()-200) * 1000);} else {// if the access_token is null, obtain the Thread after 60 seconds. sleep (60*1000) ;}} catch (InterruptedException e) {try {Thread. sleep (60*1000);} catch (InterruptedException e1) {log. error ("{}", e1);} log. error ("{}", e );}}}}

Line 1 in the code constructs an infinite loop (permanent execution) through while (true) {}; Line 2 calls the public platform interface to obtain the access_token; Line 3 sleep the thread for 23rd seconds and then runs, that is, the access_token is obtained every 7000 seconds to ensure that the access_token will never expire. For other classes in the project, you can call TokenThread. accessToken. getToken () to obtain the interface access credential access_token. Run the program locally. after Tomcat is started, the following logs are displayed on the console:

[INFO] weixin api appid: wx617a123bb8bc99cd [INFO] weixin api appsecret: token [INFO] get access_token successful, valid duration 7200 seconds token: sFopJ9lMmLl4u-ad61ojKpS0TolhN2s3SnHoI2Mh5GgdiYb35i-7DG2T2CDyQKMe

To intuitively see the effect of regularly obtaining access_token, you can try to change the thread sleep time in TokenThread to 30 s or 60 s.

The above is a detailed description of the methods used by the public platform to ensure long-term effectiveness of access_token. For more information, see other related articles on php Chinese network!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.