- How to store and update access_token regularly

Source: https://blog.csdn.net/sct_t/article/details/53002611

We know that requesting access_Token will return such a json, including access_token (credentials) and expires_in (time limit of credentials)

When we need access_token, there is no need to request the server every time, because this certificate is valid within 2 hours, then it must be stored. There are several methods to choose from: 1. Redis; 2. Database; 3 File storage .

I am using the way the database is stored:

--  
-- The structure of the table `accesstoken`  
--  
CREATE TABLE IF NOT EXISTS `accesstoken` (  
  `A_ID` int(11) NOT NULL,  
  `A_Token` varchar(600) COLLATE utf8_bin NOT NULL,  
  `A_Date` int(11) NOT NULL,  
  `A_Update` int(11) DEFAULT NULL  
) ENGINE=InnoDB AUTO_INCREMENT=29 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;  

  Then here is the php code:

       //Get access_token Of course, please connect to your own database before this  
function Curl($appid,$appsecret) {  
    $url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret;  
       $ch = curl_init();  
       curl_setopt($ch, CURLOPT_TIMEOUT, 5);  
       curl_setopt($ch, CURLOPT_URL, $url);  
       curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  
       curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);  
       $dataBlock = curl_exec($ch);//This is json data  
       curl_close($ch);  
    $res = json_decode($dataBlock, true); //Accept a string in json format and convert it to PHP variable  
      
       return $res['access_token'];  
   }  
//insert token into database  
function serilizable(){  
    $appid="your own";  
    $appsecret="your own";  
    $sql="select A_ID,A_Token,A_Date from accesstoken order by A_ID desc";  
    $rs=mysql_query($sql);  
    $times=time();//Current time  
    $row=mysql_fetch_array($rs);  
    $rownum=mysql_num_rows($rs);  
    //Data time - the current time is less than 800s  
    if($rownum == 0 ){//If there is no data, get the token and store it in the database  
       $timestamp=time()+6000;//After 100 minutes  
        $token= Curl($appid,$appsecret);  
        $sqlin="insert into accesstoken(A_Token,A_Date) values('$token','$timestamp')";  
        mysql_query($sqlin);  
        return $token;  
        ///return $rownum;  
    }else{  
      
            //Exceed the data time, then re-acquire the token  
        if($row['A_Date'] < $times){  
            $token= Curl($appid,$appsecret);  
            $timestamp=time()+6000;//After 100 minutes  
            $sqlu="UPDATE `accesstoken` SET `A_Token`='$token',`A_Date`='$timestamp' WHERE A_ID = '$row[A_ID]' ";  
            mysql_query($sqlu);  
            return $token;  
        }else//If it does not exceed, then fetch from the database  
         return $row[A_Token];  
          
    }  
       
}  

  

Guess you like

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