<?php

namespace App\Com;

use App\Models\AccountWechat;
use App\Models\OperatorsUser;
use App\Com\Redis;
use EasySwoole\EasySwoole\Logger;

class WechatAccessToken
{

    protected $redis = null;    //redis客户端
    protected $url = "https://api.weixin.qq.com/cgi-bin/token";    //接口请求URL
    protected $appid = null;    //appid
    protected $secret = null;    //秘钥
    protected $redis_save_key = 'wechat_access_token';    //redis中的缓存键值
    protected $operators_id = 0;    //运营商ID

    //构造函数
    function __construct($operators_id = 0)
    {
        $set = AccountWechat::create()->get()->toArray();
        if ($operators_id) {
            //获取运营商数据
            $this->operators_id = $operators_id;
            $operators_res = OperatorsUser::create()->where('id', $operators_id)->get()->toArray();
            $set = isset($operators_res['wechat_appid']) && $operators_res['wechat_appid'] && isset($operators_res['wechat_secret']) && $operators_res['wechat_secret'] ? $operators_res : $set;
            $this->redis_save_key = isset($operators_res['wechat_appid']) && $operators_res['wechat_appid'] && isset($operators_res['wechat_secret']) && $operators_res['wechat_secret'] ? $this->redis_save_key . '_' . $operators_id : $this->redis_save_key;
        }
        $this->appid = $set['wechat_appid'];
        $this->secret = $set['wechat_secret'];
    }


    /**
     * @param $operators_id 运营商ID，无运营商则为0
     * 获取Access_token
     * @return String 返回小程序授权码，获取失败可能会返回空
     */
    public function getAccess_token()
    {
        //加载redis
        $this->redis = Redis::getInstance()->getConnect();
        //获取redis存储
        $result = json_decode($this->redis->get($this->redis_save_key), true);
        //判断access_token不为空，且过期时间大于当前时间（去掉最后60秒防止时间误差）
        if ($result['access_token'] && $result['expires_time'] > (time() - 60)) {
            return $result['access_token'];
        } else {    //否者获取最新的access_token
            $response = file_get_contents($this->url . "?grant_type=client_credential&appid=" . $this->appid . "&secret=" . $this->secret);
            $result = json_decode($response, true);
            //记录微信服务器返回值
            Logger::getInstance()->info('小程序Access_token接口返回值:' . $response);
            //缓存到Redis中
            $this->redis->set($this->redis_save_key, json_encode(array('access_token' => $result['access_token'], 'expires_time' => time() + $result['expires_in'])));
            return $result['access_token'];
        }
    }
}