WeChat Access Token caching method

The default cache of WeChat Access Token is 2 hours, but it needs to be emphasized that the cache of WeChat service account and WeChat enterprise account are different.

(1) WeChat Official Account: Each time Http requests Access Token, the system will return a different Token with a timeout period, the default is 2 hours.

(2) WeChat Enterprise Account: Each time you request an Access Token, the default validity period is 2 hours, and the Access Token obtained within these 2 hours is the same.

For the WeChat official account, we store the Access Token obtained each time through txt. In other words, when you get Access again after caching, you get it directly from txt. code show as below:

  private static string wxml = HttpContext.Current.Server.MapPath("~/app_data/access_token.txt");

      
    public static string GetAccessToken()
    {
        string json = "";
        DateTime dt = DateTime.Now;
        if (!System.IO.File.Exists(wxml))
        { 
//txt does not exist, create json = GetTokenFromURL(); } else { json = System.IO.File.ReadAllText(wxml); } //Get the time of the last txt write dt = System.IO.File.GetLastWriteTime(wxml); DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(AccessToken)); var mStream = new MemoryStream(Encoding.Default.GetBytes(json)); AccessToken token = (AccessToken)serializer.ReadObject(mStream); //_expires_in defaults to 7200 seconds, which is 2 hours, that is, access_token expires after 2 hours. To ensure reliability, the system invalidates access_tokey for 1.5 hours. int minRefreshTimeSpan = 1800 - int.Parse(token.expires_in); // -5400秒 if (minRefreshTimeSpan > 0) { minRefreshTimeSpan = -1800; } if (dt < DateTime.Now.AddSeconds(minRefreshTimeSpan)) { GetTokenFromURL(); json = System.IO.File.ReadAllText(wxml); serializer = new DataContractJsonSerializer(typeof(AccessToken)); mStream = new MemoryStream(Encoding.Default.GetBytes(json)); token = (AccessToken)serializer.ReadObject(mStream); } return token.access_token; } private static string GetTokenFromURL() { string appid = AppID; string secret = AppSecret; string strUrl = Access_Token_URL; string json = HttpUtility.SendGetHttpRequest(strUrl); System.IO.File.WriteAllText(wxml, json); return json; }



 (2) For enterprise WeChat AccessToken, single-column mode storage can be used

public class TokenSingleton {
    //Cache the Map of accessToken, the map contains an accessToken and the cached timestamp
        // Of course, it can also be separated into two properties.
    
        public final static String weixin_jssdk_ticket_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";

        private Map<String, String> map = new HashMap<>();

        private TokenSingleton() {
        }

        private static TokenSingleton single = null;

        // static factory method
        public static TokenSingleton getInstance() {
            if (single == null) {
                single = new TokenSingleton();
            }
            return single;
        }

        public Map<String, String> getMap(WeixinAccountServiceI weixinAccountService) {
            String time = map.get("time");
            String accessToken = map.get("access_token");
            Long nowDate = new Date().getTime();
            
            if (accessToken != null && time != null && nowDate - Long.parseLong(time) < 3000 * 1000) {
//                result = accessToken;
                System.out.println("accessToken exists without timeout, return singleton");
            } else {
                System.out.println("accessToken timed out, or does not exist, re-acquire");
                System.out.println("weixinAccountService : " + weixinAccountService);
                String access_token=weixinAccountService.getNewAccessToken("gh_ab6e37102f85");
                        //"Here is to directly call WeChat's API to get accessToken and Jsapi_ticket directly";
                String jsapi_token = getJsapiToken(access_token);
                        //"Get jsapi_token";
                map.put("time", nowDate + "");
                map.put("access_token", access_token);
                map.put("jsapi_token", jsapi_token);
//                result = access_token;
            }
            
            return map;
        }

        public void setMap(Map<String, String> map) {
            this.map = map;
        }

        public static TokenSingleton getSingle() {
            return single;
        }

        public static void setSingle(TokenSingleton single) {
            TokenSingleton.single = single;
        }
        
        
        public String getJsapiToken(String accessToken){
            //Get jsapi_ticket
            System.out.println("获取jsapi_ticket");
            String jsapi_Url = weixin_jssdk_ticket_url.replace("ACCESS_TOKEN", accessToken);
            String jsapi_ticket = null;
            net.sf.json.JSONObject jsonObject = WeixinUtil.httpRequest(jsapi_Url, "GET", null);  
            
            System.out.println("Request returned data: " + jsonObject);
            
            // if the request was successful   
            if (null != jsonObject) {  
                System.out.println("jsapi_ticket  :  "+jsonObject);
                jsapi_ticket=jsonObject.getString("ticket");  
            }
            
            return jsapi_ticket;
        }
        
        
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324647817&siteId=291194637