1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
|
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"net/url"
"golang.org/x/oauth2/clientcredentials"
"golang.org/x/oauth2/twitch"
)
type UserTokenResponse struct {
AccessToken string `json:"access_token"`
ExpiresIn int `json:"expires_in"`
RefreshToken string `json:"refresh_token"`
Scope []string `json:"scope"`
TokenType string `json:"token_type"`
}
func GetUserToken(authCode string) UserTokenResponse{
apiURL := "https://id.twitch.tv/oauth2/token"
data := url.Values{}
data.Set("client_id", clientSecrets.ClientID)
data.Set("client_secret", clientSecrets.ClientSecret)
data.Set("code", authCode)
data.Set("grant_type", "authorization_code")
data.Set("redirect_uri", "http://localhost:3000")
req, err := http.NewRequest("POST", apiURL, bytes.NewBufferString(data.Encode()))
if err != nil {
fmt.Println("Error creating request:", err)
panic(err)
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println("Error sending request:", err)
panic(err)
}
defer resp.Body.Close()
if DEBUG {
fmt.Println("Response Status:", resp.Status)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Println("Error reading response body:", err)
panic(err)
}
var userTokenResponse UserTokenResponse
err = json.Unmarshal([]byte(body), &userTokenResponse)
if err != nil {
fmt.Println("Error unmarshaling JSON:", err)
panic(err)
}
return userTokenResponse
}
func GetAppToken() string{
oauth2Config = &clientcredentials.Config{
ClientID: clientSecrets.ClientID,
ClientSecret: clientSecrets.ClientSecret,
TokenURL: twitch.Endpoint.TokenURL,
}
token, err := oauth2Config.Token(context.Background())
if err != nil {
log.Fatal(err)
}
return token.AccessToken
}
|