diff options
Diffstat (limited to 'token.go')
-rw-r--r-- | token.go | 90 |
1 files changed, 90 insertions, 0 deletions
diff --git a/token.go b/token.go new file mode 100644 index 0000000..8ccbdb2 --- /dev/null +++ b/token.go @@ -0,0 +1,90 @@ +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{ + + // Define the URL and form data + apiURL := "https://id.twitch.tv/oauth2/token" // Replace with the actual URL to send the POST request to + + data := url.Values{} + data.Set("client_id", clientID) + data.Set("client_secret", clientSecret) + data.Set("code", authCode) + data.Set("grant_type", "authorization_code") + data.Set("redirect_uri", "http://localhost:3000") + + // Create the POST request + req, err := http.NewRequest("POST", apiURL, bytes.NewBufferString(data.Encode())) + if err != nil { + fmt.Println("Error creating request:", err) + panic(err) + } + + // Set the appropriate header for x-www-form-urlencoded + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + + // Send the request + client := &http.Client{} + resp, err := client.Do(req) + if err != nil { + fmt.Println("Error sending request:", err) + panic(err) + } + defer resp.Body.Close() + + // Print the response status + // fmt.Println("Response Status:", resp.Status) + + // You can read and print the body here if needed + 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: clientID, + ClientSecret: clientSecret, + TokenURL: twitch.Endpoint.TokenURL, + } + + token, err := oauth2Config.Token(context.Background()) + if err != nil { + log.Fatal(err) + } + + return token.AccessToken +} |