]> git.localhorst.tv Git - alttp.git/blob - app/Models/TwitchToken.php
a4c561eaffa40ce75cc49f5272cf13c8a1fb5b87
[alttp.git] / app / Models / TwitchToken.php
1 <?php
2
3 namespace App\Models;
4
5 use Illuminate\Database\Eloquent\Factories\HasFactory;
6 use Illuminate\Database\Eloquent\Model;
7 use Illuminate\Support\Facades\Http;
8
9 class TwitchToken extends Model
10 {
11         use HasFactory;
12
13         public function getAuthUrl() {
14                 return 'https://id.twitch.tv/oauth2/authorize'
15                         .'?response_type=code'
16                         .'&client_id='.rawurlencode(config('twitch.client_id'))
17                         .'&redirect_uri='.rawurlencode(config('twitch.redirect_uri'))
18                         .'&scope='.implode('+', array_map('rawurlencode', $this->scope));
19         }
20
21         public function refresh() {
22                 $rsp = Http::post('https://id.twitch.tv/oauth2/token', [
23                         'client_id' => config('twitch.client_id'),
24                         'client_secret' => config('twitch.client_secret'),
25                         'grant_type' => 'refresh_token',
26                         'refresh_token' => $this->refresh,
27                 ]);
28                 if (!$rsp->successful()) {
29                         throw new \Exception($rsp['message']);
30                 }
31                 $this->type = $rsp['token_type'];
32                 $this->scope = $rsp['scope'];
33                 $this->access = $rsp['access_token'];
34                 $this->refresh = $rsp['refresh_token'];
35                 $this->save();
36         }
37
38         public function request() {
39                 return Http::baseUrl('https://api.twitch.tv/helix')
40                         ->withToken($this->access)
41                         ->withHeaders([
42                                 'Client-Id' => config('twitch.client_id'),
43                         ]);
44         }
45
46         protected $casts = [
47                 'scope' => 'array',
48         ];
49
50         protected $hidden = [
51                 'access',
52                 'refresh',
53         ];
54
55 }