<?php
/**
 * 每分钟执行一次,拉取已授权账号信息,将要过期的信息,刷新
 * authorizer_access_token 有效期为 2 小时
 * 1.获取已授权账号信息
 * 2.若授权即将过期,调用刷新令牌接口,重新获取令牌
 * Created by PhpStorm.
 * User: XiaoMing
 * Date: 2020/4/20
 * Time: 14:11
 */

namespace JinDouYun\Controller\Cron;

use Mall\Framework\Core\ResultWrapper;
use Mall\Framework\Factory;

use JinDouYun\Dao\Oem\DOem;

use Util\WeiXin\Oplatform;

class PullWxInfo
{
    private $oplatformConfigData;

    public function __construct()
    {
        echo date('Y-m-d H:i:s') . ':拉取已授权账号信息' . PHP_EOL;
        /*$oplatformConfigData = Factory::config()->getAppoint('weixin', 'oplatform');
        if (empty($oplatformConfigData)) {
            exit('配置错误');
        }
        $this->oplatformConfigData = $oplatformConfigData;*/
    }

    /**
     * 对所有代理的微信开发平台授权自行自动更新操作
     */
    public function autoAuthorizerToken()
    {
        $objDOem = new DOem();
        $dbResult = $objDOem->select(' weixinOpenAppid != ""', 'weixinOpen', 'id asc');
        if( $dbResult === false ){
            echo $dbResult->error();exit();
        }

        if( empty($dbResult) ){
            echo '没有微信开放平台需要刷新';exit();
        }

        foreach ($dbResult as $key => $value){
            $this->oplatformConfigData = json_decode($value['weixinOpen'], true);
            self::pullWx();
        }
    }

    /**
     * 拉取已授权用户信息,效验过期时间
     * @throws \Exception
     */
    public function pullWx()
    {
        $objOplatform = new Oplatform($this->oplatformConfigData['appid'], $this->oplatformConfigData['token'], $this->oplatformConfigData['encodingAesKey'], $this->oplatformConfigData['appSecret']);
        $pullResult = $objOplatform->apiGetAuthorizerList();
        if (!$pullResult->isSuccess()) {
            echo $pullResult->getData();
        }
        $userData = $pullResult->getData();
        if (empty($userData)) {
            echo '拉取已经授权用户信息为空';
        }
        if (!isset($userData['list']) || empty($userData['list'])) {
            echo '拉取已经授权用户信息为空';
        }
        $time = time();
        foreach ($userData['list'] as $val) {
            //获取上次刷新的时间
            $expire = Factory::cache('default')->hget('appid_expire', $val['authorizer_appid']);//上次刷新的时间
            if ((($expire + 6480) < $time) || empty($expire)) {
                //已过期,刷新token
                $result = self::refAuth($val);
                if ($result->isSuccess()) {
                    Factory::cache('default')->hset('appid_expire', $val['authorizer_appid'], $time);//本次刷新的时间
                    echo $val['authorizer_appid'] . '刷新令牌成功'.PHP_EOL;
                } else {
                    echo $val['authorizer_appid'] . '刷新令牌失败' . $result->getData().PHP_EOL;
                }
            }
        }
    }

    /**
     * 刷新令牌
     * @param $params
     * @return ResultWrapper
     */
    private function refAuth($params)
    {
        $objOplatform = new Oplatform($this->oplatformConfigData['appid'], $this->oplatformConfigData['token'], $this->oplatformConfigData['encodingAesKey'], $this->oplatformConfigData['appSecret']);
        $result = $objOplatform->apiAuthorizerToken($params['authorizer_appid'], $params['refresh_token']);
        if (!$result->isSuccess()) {
            return ResultWrapper::fail($result->getData(), $result->getErrorCode());
        }
        return ResultWrapper::success($result->getData());
    }
}