]> git.localhorst.tv Git - alttp.git/blob - app/Models/TwitchToken.php
further refine chat gen
[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 hasExpired() {
22                 return now()->isAfter($this->expires_at);
23         }
24
25         public function refresh() {
26                 $rsp = Http::post('https://id.twitch.tv/oauth2/token', [
27                         'client_id' => config('twitch.client_id'),
28                         'client_secret' => config('twitch.client_secret'),
29                         'grant_type' => 'refresh_token',
30                         'refresh_token' => $this->refresh,
31                 ]);
32                 if (!$rsp->successful()) {
33                         throw new \Exception($rsp['message']);
34                 }
35                 $this->type = $rsp['token_type'];
36                 $this->scope = $rsp['scope'];
37                 $this->access = $rsp['access_token'];
38                 $this->refresh = $rsp['refresh_token'];
39                 $this->expires_at = now()->add($rsp['expires_in'], 'second');
40                 $this->save();
41         }
42
43         public function request() {
44                 return Http::baseUrl('https://api.twitch.tv/helix')
45                         ->withToken($this->access)
46                         ->withHeaders([
47                                 'Client-Id' => config('twitch.client_id'),
48                         ]);
49         }
50
51         protected $casts = [
52                 'scope' => 'array',
53         ];
54
55         protected $hidden = [
56                 'access',
57                 'refresh',
58         ];
59
60 }