YandexDirect.php 1.53 KB
<?php
namespace App\Service\API;

use Illuminate\Http\Client\Response;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

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 =  [
            'grant_type'    =>  'authorization_code',
            'code'  =>  $code,
            'client_id'  =>  config('api.yandex.id'),
            'client_secret'  =>  config('api.yandex.password'),
        ];
        $data = Http::asForm()->post($this->getTokenUrl(), $data);
        return $this->extractToken($data);
    }

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

    function extractToken($data){
        $token = $data->json()['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 = Http::get($url)->json();

        return isset($data['login']) ? $data['login'] : false;
    }

    public function execute(): Response
    {
        $result =  Http::withBody($this->request->getBody(), 'none')
            ->withHeaders($this->request->getHeaders())
            ->withToken($this->request->getToken()->token)
            ->post($this->request->getUrl());
        return $result;
    }
}