WxCookieController.class.php 5.81 KB
<?php
/**
 * 微信扫描支持 获取 Cookie
 */

namespace Api\Controller\Safe;

use Com\Cookie;
use Common\Common\Login;
use Common\Common\Logincp;
use Common\Common\ResAuth;
use Think\Controller\RestController;
use VcySDK\Adminer;
use VcySDK\Service;
use VcySDK\WxQy\WebAuth;

class WxCookieController extends RestController
{
    /**
     * 数值为1时表示获取用户cookie,为2时表示获取管理员cookie
     */
    const USER_COOKIE_TYPE_FRONTEND = 1;
    const USER_COOKIE_TYPE_ADMINER = 2;

    /**
     * 接收的数据
     * @var array
     */
    protected $postData = [];

    /**
     * 企业详情
     * @var array
     */
    private $epDetail = [];

    /**
     * cookie 实例
     * @var null
     */
    private $cookie = null;

    public function index()
    {
        // 接收数据流
        $this->postData = json_decode(file_get_contents("php://input"), true);
        if (empty($this->postData)) {
            $this->returnError('没有数据提交');
        }
        // 获取企业信息
        $this->epDetail = $this->getEpDetail();
        // 初始化 Cookie
        $this->startCookie();
        // 初始化 SDK
        $this->initSdk();

        // 获取用户信息
        try {
            $user = (new WebAuth(Service::instance()))->userLogin($this->postData['code']);
        } catch (\Exception $e) {
            $this->returnError($e->getMessage());
        }
        if (empty($user)) {
            $this->returnError('未找到用户');
        }

        // 写入 Cookie 数据
        if ($this->postData['type'] == self::USER_COOKIE_TYPE_FRONTEND) {
            $this->flushAuth($user);
        } elseif ($this->postData['type'] == self::USER_COOKIE_TYPE_ADMINER) {
            // 根据用户 ID 获取管理员信息
            try {
                $adminer = (new Adminer(Service::instance()))->getAdminerDetailByUid($user['memUserid']);
            } catch (\Exception $e) {
                $this->returnError($e->getMessage());
            }
            if (empty($adminer)) {
                $this->returnError('未找到用户');
            }

            $logincp = new Logincp();
            $logincp->flushAuth(
                $adminer,
                $logincp->getAuthPwd($adminer['eaId'], $this->epDetail['epEnumber']),
                $this->epDetail['epEnumber']
            );;
        }

        // Cookie 里加上企业标识
        $this->cookie->setx('corpid', $this->postData['corpid']);

        $this->returnResult();
    }

    /**
     * corpId 获取企业详情
     * @return array|mixed
     */
    private function getEpDetail()
    {
        try {
            // 不是常规调用 UC 接口
            $sdkService = new Service();
            $response = [];
            $sdkService->request($response, cfg('UC_APIURL') . '/s/enterprise/detail', [
                'corpId' => $this->postData['corpid'],
            ], [
                'Content-Type' => 'application/json',
            ], 'POST');
        } catch (\Exception $e) {
            \Think\Log::record('获取企业详情出错: ' . var_export($e, true));
            $response['data'] = [];
        }

        return $response['data'];
    }

    /**
     * 初始化 Cookie
     */
    private function startCookie()
    {
        $domain = cfg('COOKIE_DOMAIN');
        $expired = cfg('COOKIE_EXPIRE');
        $secret = md5(cfg('COOKIE_SECRET') . $this->epDetail['epEnumber']);

        // 初始化
        $this->cookie = &Cookie::instance($domain, $expired, $secret);
        ob_start([
            $this->cookie,
            'send',
        ]);
    }

    /**
     * 初始化 SDk
     * @return bool
     */
    private function initSdk()
    {
        $config = array(
            'apiUrl' => cfg('UC_APIURL'),
            'enumber' => $this->epDetail['epEnumber'],
            'pluginIdentifier' => APP_IDENTIFIER,
            'thirdIdentifier' => cfg('SDK_THIRD_IDENTIFIER'),
            'logPath' => RUNTIME_PATH . '/Logs/VcySDK/',
            'apiSecret' => cfg('API_SECRET'),
            'apiSigExpire' => cfg('API_SIG_EXPIRE'),
            'fileConvertApiUrl' => cfg('FILE_CONVERT_API_URL'),
        );
        $service = &Service::instance();
        $service->initSdk($config);

        return true;
    }

    /**
     * 刷新校验字符串
     * @param $user
     * @return bool
     */
    private function flushAuth($user)
    {
        $login = &Login::instance();
        $login->setCookie('uid', $user['memUid']);
        $login->setCookie('lastlogin', NOW_TIME);
        $login->setCookie('auth', $this->generateAuth($user['memUid'], NOW_TIME, $this->epDetail['epEnumber']));
        $login->setCookie('qyDomain', $this->epDetail['epEnumber']);

        // 将资源鉴权数据写入 Cookie
        $resauth = &ResAuth::instance();
        $resauth->writeCookie(ResAuth::USER_TYPE_MOBILE, $user, $this->epDetail['epEnumber']);

        return true;
    }

    /**
     * 生成验证字串
     * @param string $uid 用户UID
     * @param int    $lastLogin 最后登录时间
     * @param string $qyDomain 企业标识
     * @return string
     */
    private function generateAuth($uid, $lastLogin, $qyDomain)
    {

        return md5($uid . "\t" . $lastLogin . "\t" . $qyDomain);
    }

    /**
     * 返回数据
     */
    protected function returnResult()
    {
        // 获取 Cookie 数据
        $result = [];
        foreach ($this->cookie->get_cookie_data() as $name => $data) {
            $result['cookie'][] = "$name={$data['value']}";
        }
        $result['cookie'] = implode(';', $result['cookie']);
        // Cookie 时长
        $result['expires_in'] = cfg('COOKIE_EXPIRE');

        // 返回
        $this->_response($result, 'json');
    }

    /**
     * 返回错误
     * @param $errmsg
     */
    protected function returnError($errmsg)
    {
        $this->_response(['errmsg' => $errmsg], 'json');
    }
}