SoFunction
Updated on 2025-03-08

Detailed explanation and examples of the getAccessToken method of WeChat

Memcache cache stores user information for 7000 seconds

<?php
function getAccessToken($appid,$appsecret) 
{
  $mem = new CacheMemcache();
  $acc = $mem->get('access_token_'.$appid);
  if (!$acc) 
  {
    $url = "/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret";
    $result = https_request($url);
    $jsoninfo = json_decode($result, true);
    $access_token = $jsoninfo['access_token'];
    if ($access_token) 
    {
      $expire = time() + 7000;
      $mem = new CacheMemcache();
      $mem->set('access_token_'.$appid,$access_token,$expire);
    }
  }
  else 
  {
    $access_token = $acc;
  }
  return $access_token;
}
?>

File storage access_token

 function getAccessToken() {
  // access_token should be stored and updated globally. The following code is written to the file for example  $data = json_decode(file_get_contents("access_token.json"));
  if ($data-&gt;expire_time &lt; time()) {
   $url = "/cgi-bin/token?grant_type=client_credential&amp;appid=$this-&gt;appId&amp;secret=$this-&gt;appSecret";
   $res = json_decode($this-&gt;httpGet($url));
   $access_token = $res-&gt;access_token;
   if ($access_token) {
    $data-&gt;expire_time = time() + 7000;
    $data-&gt;access_token = $access_token;
    $fp = fopen("access_token.json", "w");
    fwrite($fp, json_encode($data));
    fclose($fp);
   }
  } else {
   $access_token = $data-&gt;access_token;
  }
  return $access_token;
 }


Thank you for reading, I hope it can help you. Thank you for your support for this site!