Accesstoken in the development of micro-credit to avoid access_token failure

Source: Internet
Author: User
Tags mongoclient mongodb sleep tojson xmlns ticket

Micro-letter embedded H5 station has been very hot, many companies also want to use the micro-letter user groups and social groups to do something, so for everyone code gentleman is also a research direction.

Access_token is the public number's globally unique ticket, the public number calls each interface to use the Access_token. Developers need to be properly saved. Access_token storage should be reserved for at least 512 character spaces. The validity period of the Access_token is currently 2 hours and needs to be refreshed periodically, and repeated acquisition will cause the last acquired access_token to fail.

The public number can use AppID and Appsecret to invoke this interface to obtain the Access_token. AppID and Appsecret are available on the website of the micro-credit public platform-Developer Center page (need to be a developer and the account is not in an abnormal state). Note The HTTPS protocol is required to invoke all micro-interfaces.

Request Address: Https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET

Parameter description:

Parameters whether you must Description
Grant_type Is Get Access_token Fill client_credential
AppID Is Unique credentials for third party users
Secret Is Third-party user unique voucher key, i.e. Appsecret

Return Description: {"Access_token": "Access_token", "expires_in": 7200}

Parameters Description
Access_token The voucher that was obtained
Expires_in Voucher valid time, in units: seconds

Recently done a demo, the function is a timer to obtain the request Micro-trust server to get Accesstoken saved to the MongoDB database, in the business needs need to use the Accesstoken when the MongoDB directly to take the latest Accesstoken record.

Code-> Business Operation Method:

        /// <summary>       
  ///  Get accesstoken        /// </summary>         /// <returns></returns>          public static mwechattoken gettoken ()          {            var  Token = new mwechattoken ();             var url = string. Format ("Https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}",  appid, appsecret);            var  Msg = httpreq (url,  "POST",  encoding.utf8, 1000);     &nbSp;       try              {                
Var tojson = new javascriptserializer ();                 token =
 toJson.Deserialize<MWeChatToken> (msg);             }             catch  (Exception ex)              {             
   log.error (ex);             }      
      return token;         } 

 Code-> Save to database:

        public static void settoken ()          {            const  string dbString =  "WeChat";             const string colString =  "Wechattoken";             var model = gettoken ();             if  (model == null)  return;             var mongoclient = new mongoclient (Conn);             var mdb =  Mongoclient.getserver (). Getdatabase (dbstring);            var  mcollection = mdb.

GetCollection (colstring);
            mcollection.insert (model);             mongoclient.getserver ().
Disconnect ();         }


Micro-trust public platform development--how to ensure access_token long-term effective?

In order to enable third party developers to provide users with more valuable personalized services, micro-trust public platform to open a number of interfaces, including custom menu interface, customer interface, access to user information interface, user group interface, mass interface, etc., developers call these interfaces, they need to pass in a same parameter access _token, it is the public account's globally unique ticket, which is the interface access credentials.

The validity period of the Access_token is 7,200 seconds (two hours) and can be used in the validity period, only when the access_token expires, you need to call the interface to get Access_token again. Ideally, a 7x24-hour system requires only 12 access_token per day, that is, every 2 hours. If the Access_token is acquired again within the validity period, the last Access_token obtained will be invalidated.

At present, get the Access_token interface of the call frequency limit of 2000 times/day, if every time to send customer service messages, get user information, mass message before the call to obtain Access_token interface access credentials, which is obviously unreasonable, On the one hand will be more time-consuming (multiple interface invoke operation), on the other hand, 2000 times/day call restrictions may not be enough. Therefore, in the practical application, we need to store the acquired Access_token, and then periodically call the Access_token interface to update it to ensure that the access_token can be removed at any time is valid.

Here's how to get and store access_token at timed intervals. Please note: This is not an article on how to invoke the interface to get Access_token, for Access_token, please refer to the article "micro-credit Public account development tutorial 14th-Customize menu creation and Menu event response."

Before you start, let's briefly analyze what we're going to solve is the following two questions:

1. How to get 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 also support quartz. In addition, there is a way to start a thread, write a dead loop in the thread's Run () method, and then use Thread.Sleep () to ensure that the thread performs a task on a regular basis.

2. Where will the Access_token be kept?

For Access_token storage, you can consider storing it in a file, database, or memory. Which storage mode to use, depending 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 to do it.

In this article, the author will demonstrate the regular acquisition and storage of Access_token process: The Web server started loading a servlet, in the servlet init () method to start a thread, the thread in the run () method through the dead Loop + Thread.Sleep () to get Access_token periodically, and then save the acquired Access_token in a variable that is decorated by the public static.

Create a Initservlet class in the project, the code for the 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 {
Get the parameters configured in Web.xml
Tokenthread.appid = Getinitparameter ("AppID");
Tokenthread.appsecret = Getinitparameter ("Appsecret");

Log.info ("Weixin API appid:{}", Tokenthread.appid);
Log.info ("Weixin API appsecret:{}", Tokenthread.appsecret);

Prompt when AppID, Appsecret are not configured
if ("". Equals (tokenthread.appid) | | "". Equals (Tokenthread.appsecret)) {
Log.error ("AppID and Appsecret configuration error, please check carefully.");
} else {
Start a timed fetch access_token thread
New Thread (New Tokenthread ()). Start ();
}
}
}

As you can see from the above code, the Initservlet class only rewrites the Init () method and does not rewrite doget () and Dopost () two methods, because we do not intend to have initservlet handle the access request. The implementation of the Init () method is also relatively simple, first get the parameters AppID and Appsecret configured in the Web.xml, and then start the thread tokenthread to get access_token periodically.

The configuration of Initservlet in Web.xml is as follows:

<?xml version= "1.0" encoding= "UTF-8"?>
<web-app version= "2.5" xmlns= "Http://java.sun.com/xml/ns/javaee"
Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"
Xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee
<a href= "http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" "=" ">http://java.sun.com/xml/ns/javaee/web-app _2_5.xsd "</a>>

<servlet>
<servlet-name>initServlet</servlet-name>
<servlet-class>
Org.liufeng.weixin.servlet.InitServlet
</servlet-class>
<!--configuration to obtain Access_token required parameters AppID and Appsecret-->
<init-param>
<param-name>appid</param-name>
<param-value>wx617a123bb8bc99cd</param-value>
</init-param>
<init-param>
<param-name>appsecret</param-name>
<param-value>4d82cbbbb08714c12345b62d7hn3dcb8</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>

<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

The configuration of Initservlet in Web.xml differs from that of the normal servlet: 1 by configuring <init-param> passing parameters to the servlet, 2 by configuring <load-on-startup> Servlet;3 is not configured to load the Web server when it is started <servlet-mapping&gt because Initservlet does not provide access externally.

Tokenthread's source code 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;

/**
* Timed access to micro-letter Access_token Thread
*
* @author Liuyq
* @date 2013-05-02
*/
public class Tokenthread implements Runnable {
private static Logger log = Loggerfactory.getlogger (Tokenthread.class);
Unique credentials for third party users
public static String AppID = "";
Third-party user unique voucher key
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 ("Get access_token successful, effective time {} seconds token:{}", Accesstoken.getexpiresin (), Accesstoken.gettoken ());
Hibernate 7,000 seconds
Thread.Sleep ((Accesstoken.getexpiresin ()-200) * 1000);
} else {
If Access_token is null,60 seconds before getting
Thread.Sleep (60 * 1000);
}
catch (Interruptedexception e) {
try {
Thread.Sleep (60 * 1000);
catch (Interruptedexception E1) {
Log.error ("{}", E1);
}
Log.error ("{}", E);
}
}
}
}

Line 23rd in the code constructs a dead loop (permanent execution) by while (true) {}, and line 25th invokes the public platform interface to get Access_token; the 29th line lets the thread hibernate for 7,000 seconds before running, that is, getting access_token every 7,000 seconds, Ensure Access_token never fail. In other classes in the project, you can get the interface access voucher Access_token by calling TokenThread.accessToken.getToken (). Run the program on a local deployment, and the following log will appear on the console after Tomcat startup completes:

[INFO] Weixin API APPID:WX617A123BB8BC99CD
[INFO] Weixin API Appsecret:4d82cbbbb08714c12345b62d7hn3dcb8
[INFO] Get Access_token success, effective time 7,200 seconds Token:sfopj9lmmll4u-ad61ojkps0tolhn2s3snhoi2mh5ggdiyb35i-7dg2t2cdyqkme

To be able to visually see the effect of getting access_token regularly, try modifying the thread hibernation time in Tokenthread to 30 seconds or 60 seconds. Finally, attach the project source code involved in this article, download the address: http://download.csdn.net/detail/lyq8479/7300501

ps:2014 April 25, the micro-letter team released a notice to modify the length of the Access_token, many developers asked how the changes will affect our program, here by the way: if the developer will get the Access_token into the database, You must ensure that the corresponding field length is large enough to store at least 512 characters; if the developer is storing the access_token in memory, nothing needs to be changed.

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.