How to Cache WeChat Token via PHP?


WeChat APIs require the input of the token, which is accessed via the following API:

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

On success, it returns the token string and the expiry in seconds. There is a rate limit on calling this API so we have to cache the token string locally to avoid calling the API too frequently. If the token has not expired yet, calling the API will simply return the same token.

Calling API has network latency and we should re-use the token whenever we can. The best way is to cache it locally via Database or file. The following PHP script will check for the cached tokens stored and its validity.

define('APPID', 'APPID');
define('APPSECRET', 'APPSECRET');
define('TOKENFILE', 'token.txt'); 
define('EXPIRY', 'expiry.txt');

date_default_timezone_set('UTC');

function getToken() {
  $tokenfile = TOKENFILE;
  $expiryfile = EXPIRY;
  if (is_file($tokenfile)) {
    $token = trim(file_get_contents($tokenfile));
  }
  if ($token && is_file($expiryfile)) {
    $x = (integer)trim(file_get_contents($expiryfile));
    if ($x > 0) {
      if (time() < $x) { // token still valid
        return $token;
      } 
    }  
  } 
  // invoke wechat API if token is not found or has expired
  $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".APPID."&secret=" . APPSECRET;
  $data = trim(file_get_contents($url)); 
  if ($data) {
    $data = json_decode($data, true);
    if ($data) {
      $token = $data['access_token'];
      $expiry = time() + (integer)$data['expires_in'];
      // save for cache until expiry
      file_put_contents($tokenfile, $token, LOCK_EX);
      file_put_contents($expiryfile, $expiry, LOCK_EX);
      return $token;
    }
  }
  // can't get valid token
  return ""; 
}

getToken.php on Github

–EOF (The Ultimate Computing & Technology Blog) —

337 words
Last Post: Microsoft Interview Question - Compute the Area of the Triangle
Next Post: How to Remove all elements of val From a Linked List?

The Permanent URL is: How to Cache WeChat Token via PHP? (AMP Version)

Leave a Reply