wechat_tokenの有効期限が切れているかどうかを自動的に判断し、スクリプトを自動的に取得します

/ ***
サービス番号トークンを取得します
* @ throws \ Exception
*トークンが無効かどうかを自動的に検出します
* /

private function get_token(){
    $data=WechatToken::findOne(['appid'=>self::appid]);
    if ($data){
        if (strtotime($data['end_time'])<time()){
            $query=WechatToken::deleteAll(['appid'=>self::appid]);
            there:
            $appid=self::appid;
            $appsecret=self::appsecret;
            $url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$appsecret}";
            $wxmsg=json_decode(file_get_contents($url),true);
            if (isset($wxmsg['errcode'])){
                throw new \Exception('请求失败');
            }
            $model=new WechatToken();
            $model->wechat_token=$wxmsg['access_token'];
            $model->end_time=date("Y-m-d H:i:s",time()+$wxmsg['expires_in']);
            $model->appid=self::appid;
            $model->secret=self::appsecret;
            if ($model->save()){
                return $wxmsg['access_token'];
            }
            throw new \Exception('保存失败');
        }
        return $data['wechat_token'];
    }
    goto there;
}

その中で、データベースまたはキャッシュを保存することを選択し、yiiフレームワークを選択しました。

データベースの形式は次のとおりです。
ここに画像の説明を挿入

おすすめ

転載: blog.csdn.net/weixin_43272542/article/details/113567809