Failed to cache access token

背景

laravel 框架。
由于某些原因,我们调用 EasyWeChat 使用 Factory 直接写入微信的配置信息。在上线一台新机器之后发现 Failed to cache access token 错误,看源文件描述的很清楚。是因为 access token 没有成功写入缓存造成的

源码如下

      $this->getCache()->set($this->getCacheKey(), [
            $this->tokenKey => $token,
            'expires_in' => $lifetime,
        ], $lifetime - $this->safeSeconds);

        if (!$this->getCache()->has($this->getCacheKey())) {
            throw new RuntimeException('Failed to cache access token.');
        }

但是我们其实已经在 .env 中开启了 CACHE_DRIVER=redis 并且 use_laravel_cache=true,所以开始怀疑是 redis 的问题,但是测试 redis 一切正常,没有任何问题。
github 上也有一些 issue,有人提到 $this->getCache() 获取 cache 的方法的问题,按照这个线索跟了一下。发现下面这段代码

 $this->app->singleton("wechat.{$name}.{$account}", function ($laravelApp) use ($name, $account, $config, $class) {
                    $app = new $class(array_merge(config('wechat.defaults', []), $config));
                    if (config('wechat.defaults.use_laravel_cache')) {
                        $app['cache'] = $laravelApp['cache.store'];
                    }
                    $app['request'] = $laravelApp['request'];

                    return $app;
                });

当通过 Factory 传入自定义配置,而 config/wechat.php 中又没有定义时,就不会对 app 赋值 cache 类
这也就导致 getCache() 方法,使用 EasyWeChat 内置的缓存方案。
缓存目标目录为 /tmp/symfony-cache/。而我的这台服务不知什么原因,/tmp/ 对 other 用户是没有写权限的,所以就导致了 Failed to cache access token 的报错

 public function getCache()
    {
        if ($this->cache) {
            return $this->cache;
        }

        if (property_exists($this, 'app') && $this->app instanceof ServiceContainer && isset($this->app['cache'])) {
            $this->setCache($this->app['cache']);

            // Fix PHPStan error
            assert($this->cache instanceof \Psr\SimpleCache\CacheInterface);

            return $this->cache;
        }

        return $this->cache = $this->createDefaultCache();
    }

解决方案

chmod 777 /tmp && chmod o+t /tmp

由于我碰到的问题仅是 /tmp 权限问题,所以此方案即可。不代表适用于全部类型问题
chmod o+t /tmpt 权限是为了防止非 root 用户删除该目录

你可能感兴趣的:(Failed to cache access token)