本地缓存token php

这篇博客介绍了如何在PHP中实现微信API的token本地缓存,通过发送请求获取token并将其写入文件,同时添加时间戳以检查是否过期,确保缓存的有效性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//获取token

    public function getToken()
    {
        $appid = $this->config->item('appid');
        $secret = $this->config->item('secret');
        $url = "https://api.weixin.qq.com/cgi-bin/token";
        $data = "grant_type=client_credential"."&appid=".$appid."&secret=".$secret;
        $result = $this->curl_post($url,$data);
        return $result;

    }

//把token写入文件  加个时间戳

    public function cacheToken()

    {

//判断文件是否存在  存在取读取token  在判断是否到期

        if (file_exists('token.json')){
            $ken = file_get_contents('token.json');
            $arr_token = json_decode($ken,true);
            if (is_array($arr_token) && $arr_token['expire_time'] > time()){
                $token['access_token'] = $arr_token['access_token'];
            }else{
                $token = $this->getToken();
                $token['expire_time'] = time() + 7000;
                file_put_contents('token.json',json_encode($token));
            }
        }else{
            $token = $this->getToken();
            $token['expire_time'] = time() + 7000;
            file_put_contents('token.json',json_encode($token));
        }
        return $token['access_token'];
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值