Session.php 1.8 KB
<?php

namespace Lackoxygen\TiktokOpen\Wap;

use Lackoxygen\TiktokOpen\Base\Cache;
use Lackoxygen\TiktokOpen\Base\Exception\AnswerException;
use Lackoxygen\TiktokOpen\Base\Exception\Exception;
use Lackoxygen\TiktokOpen\Base\ServiceManager;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;

/**
 * @property string $accessToken
 * @property int $issueTime
 * @property int $expiresIn
 */
class Session extends ServiceManager
{
    /**
     * @var string $name
     */
    protected string $name = 'wap.session';

    /**
     * @throws Exception
     */
    private function generateToken()
    {
        $response = $this->app['wap.oauth']->clientToken();

        try {
            $this->storeResponse($response);
        } catch (AnswerException $e) {
            throw new Exception(
                sprintf('Token creation exception, %s', $e->getMessage())
            );
        }
    }


    /**
     * @throws AnswerException
     */
    private function storeResponse(array $response): void
    {
        $data = Arr::get($response, 'data', []);

        if (0 !== Arr::get($data, 'error_code')) {
            throw new AnswerException(Arr::get($response, 'message'));
        }
        $expiresIn = (int)Arr::get($data, 'expires_in');

        $payload = [
            'access_token' => $data['access_token'],
            'issue_time' => time(),
            'expires_in' => $expiresIn,
        ];

        Cache::put(
            $this->name,
            $payload,
            $expiresIn - 30
        );
    }

    protected function get(string $key)
    {
        if (!Cache::has($this->name)) {

            $this->generateToken();
        }

        $payload = Cache::get($this->name);

        return Arr::get($payload, $key, '');
    }

    public function __get($name)
    {
        $key = Str::snake($name);

        return $this->get($key);
    }
}