YandexDirect.php 1.2 KB
<?php
namespace App\Service;


class YandexDirect extends API{
    private $url = 'https://oauth.yandex.ru/token';

    function getAuthLink()
    {
        return 'https://oauth.yandex.ru/authorize?response_type=code&client_id=' . config('api.yandex.id');
    }

    function getToken($code) {
        $data = $this->client->post($this->getTokenUrl(), [
            'form_params'   =>  [
                'grant_type'    =>  'authorization_code',
                'code'  =>  $code,
                'client_id'  =>  config('api.yandex.id'),
                'client_secret'  =>  config('api.yandex.password'),
            ]
        ]);
        return $this->extractToken($data);
    }

    protected function getTokenUrl() {
        return $this->url;
    }

    function extractToken($data){
        $token = json_decode($data->getBody())->access_token;
        $login = $this->getLoginByToken($token);
        return ['token' => $token, 'login' => $login];
    }

    public function getLoginByToken($token) {
        $url = "https://login.yandex.ru/info?format=json&oauth_token={$token}";
        $data = json_decode($this->client->get($url)->getBody());

        return isset($data->login) ? $data->login : false;
    }
}