In order to enable third-party developers to provide users with more valuable personalized services , Wechat public platform has opened many interfaces , Include custom menu interface 、 Customer service interface 、 Get user information interface 、 User grouping interface 、 Group interface, etc , When developers call these interfaces , All need to pass in the same parameter access_token, It is the global only bill of public account , It is an interface access credential .

access_token Is valid for 7200 second ( Two hours ), Within the validity period , Can be used all the time , Only when access_token expires , You need to call the interface again to get access_token. In an ideal situation , One 7x24 Hourly system , Every day, you just need to get 12 Time access_token, That is, every 2 Once per hour . If within the validity period , Once again access_token, So the last one access_token Will fail .

at present , obtain access_token The call frequency of the interface is limited to 2000 Time / God , If customer service message is sent every time 、 Get user information 、 Call get before mass sending messages access_token Interface gets interface access credentials , This is clearly unreasonable , On the one hand, it will be more time-consuming ( One more interface call operation ), On the other hand 2000 Time / I'm afraid it's not enough . therefore , in application , We need to get access_token Store it , Then call it regularly access_token Interface update it , To ensure that it can be taken out at any time access_token It's all valid .

Next, we will introduce how to acquire and store access_token. Please note that : This is not an article on how to call an interface to get access_token The article , About access_token Acquisition , Please refer to the article 《 Wechat public account development tutorial No 14 piece - The creation of custom menu and menu event response 》.

Let's make a brief analysis before we start , We have to solve the following two problems :

1、 How to get it regularly access_token?

stay Java in , If you want to perform a task regularly , Need to use java.util.Timer class , For those who like to use frames , Open source task scheduling framework can be adopted quartz,Spring The framework also supports quartz. Besides this , Another way is to start a thread , Threading run() Write a dead loop in the method , And then use Thread.sleep() To ensure that the thread regularly performs a task .

2、 take access_token Where to keep it ?

about access_token The storage , Consider storing in a file 、 Database or memory . What kind of storage method is used , It depends on the actual situation of the project . If there is only one server , Direct will access_token Storage in memory is the easiest and most efficient way .

In this paper , I will demonstrate how to get and store access_token The process of is :Web Load one when the server starts Servlet, stay Servlet Of init() Method to start a thread , Threading run() Method through the dead loop +Thread.sleep() Regular access to access_token, Then we will get access_token Save in public static In the modified variables .

Create a... In the project InitServlet class , The code for this class is as follows :

01. package  org.liufeng.weixin.servlet;
03. import  javax.servlet.ServletException;
04. import  javax.servlet.http.HttpServlet;
05. import  org.liufeng.weixin.thread.TokenThread;
06. import  org.liufeng.weixin.util.WeixinUtil;
07. import  org.slf4j.Logger;
08. import  org.slf4j.LoggerFactory;
10. /**
11. * initialization servlet
12. *
13. * @author liuyq
14. * @date 2013-05-02
15. */
16. public  class  InitServlet  extends  HttpServlet {
17. private  static  final  long  serialVersionUID = 1L;
18. private  static  Logger log = LoggerFactory.getLogger(WeixinUtil. class );
20. public  void  init()  throws  ServletException {
21. // obtain web.xml Parameters configured in
22. TokenThread.appid = getInitParameter( "appid" );
23. TokenThread.appsecret = getInitParameter( "appsecret" );
25. "weixin api appid:{}" , TokenThread.appid);
26. "weixin api appsecret:{}" , TokenThread.appsecret);
28. // Not configured appid、appsecret Give a hint when
29. if  ( "" .equals(TokenThread.appid) ||  "" .equals(TokenThread.appsecret)) {
30. log.error( "appid and appsecret configuration error, please check carefully." );
31. else  {
32. // Start timing acquisition access_token The thread of
33. new  Thread( new  TokenThread()).start();
34. }
35. }
36. }

As you can see from the code above ,InitServlet Class only overrides init() Method , I didn't rewrite it doGet() and doPost() Two methods , Because we're not going to let InitServlet To handle access requests .init() The implementation of the method is also relatively simple , First get in web.xml Parameters configured in appid and appsecret, Restart thread TokenThread Time acquisition access_token.

InitServlet stay web.xml The configuration in :

01. <?xml version= "1.0"  encoding= "UTF-8" ?>
02. <web-app version= "2.5"  xmlns= ""
04. xsi:schemaLocation="http: //
05. http: //">
07. <servlet>
08. <servlet-name>initServlet</servlet-name>
09. <servlet- class >
10. org.liufeng.weixin.servlet.InitServlet
11. </servlet- class >
12. <!-- Configuration get access_token Required parameters appid and appsecret -->
13. <init-param>
14. <param-name>appid</param-name>
15. <param-value>wx617a123bb8bc99cd</param-value>
16. </init-param>
17. <init-param>
18. <param-name>appsecret</param-name>
19. <param-value>4d82cbbbb08714c12345b62d7hn3dcb8</param-value>
20. </init-param>
21. <load-on-startup> 0 </load-on-startup>
22. </servlet>
24. <welcome-file-list>
25. <welcome-file>index.<a href= ""  target= "_blank"  class = "keylink" >jsp</a></welcome-file>
26. </welcome-file-list>
27. </web-app>

InitServlet stay web.xml The configuration in is the same as that in normal Servlet There are several differences in the configuration of :1) By configuring <init-param> towards Servlet Parameter passed in ;2) By configuring <load-on-startup> bring Web The server loads the Servlet;3) No configuration <servlet-mapping>, because InitServlet No external access .

TokenThread The source code is as follows :

01. package  org.liufeng.weixin.thread;
03. import  org.liufeng.weixin.pojo.AccessToken;
04. import  org.liufeng.weixin.util.WeixinUtil;
05. import  org.slf4j.Logger;
06. import  org.slf4j.LoggerFactory;
08. /**
09. * Get wechat regularly access_token The thread of
10. *
11. * @author liuyq
12. * @date 2013-05-02
13. */
14. public  class  TokenThread  implements  Runnable {
15. private  static  Logger log = LoggerFactory.getLogger(TokenThread. class );
16. // Third party user unique credentials
17. public  static  String appid =  "" ;
18. // Third party user unique credential key
19. public  static  String appsecret =  "" ;
20. public  static  AccessToken accessToken =  null ;
22. public  void  run() {
23. while  ( true ) {
24. try  {
25. accessToken = WeixinUtil.getAccessToken(appid, appsecret);
26. if  ( null  != accessToken) {
27. " obtain access_token success , Effective time {} second token:{}" , accessToken.getExpiresIn(), accessToken.getToken());
28. // Sleep 7000 second
29. Thread.sleep((accessToken.getExpiresIn() -  200 ) *  1000 );
30. else  {
31. // If access_token by null,60 Get it in seconds
32. Thread.sleep( 60  1000 );
33. }
34. catch  (InterruptedException e) {
35. try  {
36. Thread.sleep( 60  1000 );
37. catch  (InterruptedException e1) {
38. log.error( "{}" , e1);
39. }
40. log.error( "{}" , e);
41. }
42. }
43. }
44. }

In the code 23 Yes while(true){} A dead cycle is constructed ( Permanent execution ); The first 25 Line calls the public platform interface to get access_token; The first 29 OK, let the thread sleep 7000 Seconds to run , That is, every 7000 Seconds to get once access_token, Guarantee access_token Never fail . Other classes in the project , You can call TokenThread.accessToken.getToken() To get the interface access credentials access_token. Run the program locally ,Tomcat After startup, the following log will be displayed on the console :

1. [INFO ] weixin api appid:wx617a123bb8bc99cd
2. [INFO ] weixin api appsecret:4d82cbbbb08714c12345b62d7hn3dcb8
3. [INFO ] obtain access_token success , Effective time 7200 second token:sFopJ9lMmLl4u-ad61ojKpS0TolhN2s3SnHoI2Mh5GgdiYb35i-7DG2T2CDyQKMe

In order to be able to intuitively see regular access access_token The effect of , Try to put TokenThread The thread sleep time in is changed to 30 Seconds or 60 second . Last , Attach the source code of this project , Download address :

PS:2014 year 4 month 25 The wechat team in Japan released the modification access_token The length of the notice , Many developers ask what impact this change will have on our program , By the way : If the developer will get access_token Store in database , We must ensure that the corresponding field length is large enough , At least it can store 512 Characters ; If the developer is going to access_token Stored in memory , Then nothing needs to be changed .

If you think the article will help you , Please leave a message or follow wechat public account xiaoqrobot To support Liu Feng !

Wechat timing access token More articles about

  1. nodejs Wechat development gets token,ticket-1

    /* jshint -W079 */ /* jshint -W020 */ "use strict"; var _ = require("lodash"); v ...

  2. WeChat php obtain token The solution to the second failure

    For the first time , The second time always fails , It's simple ,session problem clearstatcache(); $_SESSION = ''; $_COOKIE = ''; // Get parameters signature nonce ...

  3. Java WeChat official account development ---- Time acquisition access_token And save to redis in

    I originally wanted to do the operation of creating, modifying and deleting WeChat official account menu , But finding out needs to be access_token, By reading the document , The following requirements are found in the document : 1.access_token Valid for 2 Hours 2.access_ ...

  4. 【 WeChat 】 Wechat access to TOKEN, And storage TOKEN Method ,Spring quartz Give Way Token Forever is just a time

    Website shows access_token Is the official account of the public number. , Official account calls for interfaces. access_token. Developers need to keep it properly . access_token At least keep the storage of 512 Character space .ac ...

  5. weblogic Next Wechat public platform token Report errors

    Problem description : Develop wechat public platform , Local tomcat You can get token And send a template message , Deployed in weblogic Report a mistake later , The exception information is as follows : ...

  6. Wechat hardware platform ( 8、 ... and ) 1 esp8266 Get it from your own server token

    from txt obtain token #include <ESP8266WiFi.h> #define host_token "" #define ...

  7. WeChat development -ACCESS TOKEN Expired solutions

    WeChat development -ACCESS TOKEN Expired solutions cause : because access_token Importance , Anyone who has developed wechat knows , But he has his own life cycle , The official explanation is :" Valid for 7200 second ", One ...

  8. obtain token, Binding micro signals , Custom menu , Event response demo

    Abstract : This demo It includes getting token, Binding micro signals , Set up custom menus , Response text and events I've finished the basic and advanced parts of this tutorial , I always feel a little itchy , I understand everything , Didn't absorb much new knowledge . It's not like I'm here yet ...

  9. [ turn ] Android Advanced —— Android access to wechat , obtain OpenID

    PS: sendAuthRequest Get code, adopt code Get access_token and openId,access_token You can get user information ...

Random recommendation

  1. webservice Communication call weather forecast interface example

    Reprint : One : Environment building 1: Create a new one java project engineering weatherInf 2: Introduce the corresponding ja ...

  2. ansible Not root User batch modification root password

    Preface : Because the password of the online server has not been updated for a long time , Now the leader asked to change the password in batch . Online has been deployed before salt, But due to various factors, it is not used normally . The plan to use automated tools to batch modify has run aground , Later, the leader gave a python Multi thread password modification script ...

  3. Uncle also said Xamarin~Android piece ~ListView Inside Click Event and get the other elements of the line

    Back to directory I'm original , I contribute , I'm uncle warehouse This article is original , Study it with a passion for Technology , Share the results with the Chinese people ! Uncle always believes in one thing : You have to choose a job you're interested in , You can make the most of your potential , And it's all based on your constant research , ...

  4. Searching for a valid kernel header path... The path &quot;&quot; is not a valid path to the ***** kernel headers. Would you like to change it? [yes]

    stay centos 6.5 install vmtools When , Unzip the package ,mount After mounting , install pl Report in the process This problem , It hasn't been solved for a long time ,google And then I found out that's it I installed the kernel-deve ...

  5. [js Open source component development ]network Asynchronous requests ajax An extension of

    network Asynchronous requests ajax An extension of In everyday applications , You might call $.ajax There will be some problems , For example, repeated clicks by users , For example, I only hope that it can be submitted once and can't be submitted again , For example, I would like to have one that is being submitted loadin ...

  6. PLSQL see oracle Chinese characters display garbled code

    First, execute the statement select * from V$NLS_PARAMETERS   Look at... In the first line PARAMETER The middle of the item is NLS_LANGUAGE Corresponding VALUE Whether the item is SIMPLIFIED CHINES ...

  7. only for equality comparisons Hash Index Characteristics Hash Index Characteristics Hash indexes ...

  8. Python Script controlled WebDriver Common operations &lt; 8、 ... and &gt; Simple object positioning

    Contents of this part , Will be in WebDriver in , Demonstration of positioning element method , Yes, it will Selenium in Selenese Element positioning command WebDriver A combination of the methods used in Selenium In the element localization method review may refer to : & ...

  9. Preliminary discussion JavaScript Pattern (8) : function 【 summary 】

    What is a function function , It's a piece of code in a large program , Consists of one or more statement blocks . It's responsible for a particular task , And compared to other code , With relative independence .( Wikipedia ) Features of functions The first kind of object stay JavaScript In the world ...

  10. win7 Dual system installation openSUSE13.2 solve 【 Error during bootloader installation 】 problem

    Original date :2015-08-17 14:16 I didn't know which one was wrong last night , Suddenly want to install a liunx System , And win7 Form a double system , Finally selected openSUSE13.2, Think about installing it before Ubuntu, It should be almost , So direct ...