PHP全局管理微信公众平台token

由于微信平台对获取token有限制,而且每次获取的token不一样,需要对获取到的token,ticket之类的数据进行服务器全局保存,而且有7200秒的限制,如果token不同步或超时,会导致相关接口不可用.
对于java这类语言而言,维护全局变量是很简单的事,但是PHP做全局一直是个麻烦事,需要借助第三方的功能才能实现,如数据库,缓存,文件系统等,我这里提供一种文件系统全局保存ticket的方式,对单台服务器有效,如果要用在多台服务器上,可以实现成一个http接口给其他服务器获取token

下面是PHP代码

<?php
//weixin.php
//全局保存ticket和token,系统中的所有获取token的地方通过引用该文件
//注意:需要保证该php文件可以读写同目录下的lock,_weixin_tickets.php两个文件.
$cdir=dirname(__FILE__);
$file=$cdir.'/lock';
if(!file_exists($file)) touch($file);
$lock=fopen($file,'w');
flock($lock,LOCK_EX);

$tokenFile=$cdir.'/_weixin_tickets.php';
$ticketData=include($tokenFile);
//如果token超时,更新token
if(time()-$ticketData['time']>=7100){
    $url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=myappid&secret=mysecret";
    $datas=json_decode(file_get_contents($url));

    $ticketData=array(
        'access_token'=>$datas->access_token,
        'time'=>time()
    );
    $token=$ticketData['access_token'];
    $rdata=file_get_contents("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={$token}&type=jsapi");
    $datas=json_decode($rdata);
    $ticketData['ticket']=$datas->ticket;

    unlink($tokenFile);
    file_put_contents($tokenFile,"<?php\nreturn ".var_export($ticketData,true).";");
}

flock($lock,LOCK_UN);
fclose($lock);

return $ticketData;

如果需要多个服务器共享token,可以某一台服务器实现一个内部http接口,引用该文件,输出token等信息,如下示例

//内部api
<?php
$ticketData=include("/path/to/weixin.php");
echo json_encode($ticketData);

Leave a comment

Your email address will not be published. Required fields are marked *