zmb3 / spotify

A Go wrapper for the Spotify Web API
Apache License 2.0
1.33k stars 283 forks source link

{"error":"invalid_client"} #218

Closed TAMILVIP007 closed 1 year ago

TAMILVIP007 commented 1 year ago

import (
    "context"
    "fmt"
    "github.com/zmb3/spotify/v2/auth"
    "log"
    "net/http"

    "github.com/zmb3/spotify/v2"
)

// redirectURI is the OAuth redirect URI for the application.
// You must register an application at Spotify's developer portal
// and enter this value.
const redirectURI = "http://localhost:8080/callback"

var (
    auth  = spotifyauth.New(spotifyauth.WithRedirectURL(redirectURI), spotifyauth.WithScopes(spotifyauth.ScopeUserReadPrivate))
    ch    = make(chan *spotify.Client)
    state = "abc123"
)

func main() {
    // first start an HTTP server
    http.HandleFunc("/callback", completeAuth)
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        log.Println("Got request for:", r.URL.String())
    })
    go func() {
        err := http.ListenAndServe(":8080", nil)
        if err != nil {
            log.Fatal(err)
        }
    }()

    url := auth.AuthURL(state)
    fmt.Println("Please log in to Spotify by visiting the following page in your browser:", url)

    // wait for auth to complete
    client := <-ch

    // use the client to make calls that require authorization
    user, err := client.CurrentUser(context.Background())
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println("You are logged in as:", user.ID)
}

func completeAuth(w http.ResponseWriter, r *http.Request) {
    tok, err := auth.Token(r.Context(), state, r)
    if err != nil {
        http.Error(w, "Couldn't get token", http.StatusForbidden)
        log.Fatal(err)
    }
    if st := r.FormValue("state"); st != state {
        http.NotFound(w, r)
        log.Fatalf("State mismatch: %s != %s\n", st, state)
    }

    // use the token to get an authenticated client
    client := spotify.New(auth.Client(r.Context(), tok))
    fmt.Fprintf(w, "Login Completed!")
    ch <- client
}
Please log in to Spotify by visiting the following page in your browser: https://accounts.spotify.com/authorize?client_id=&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Fcallback&response_type=code&scope=user-read-private&state=abc123
2023/04/02 01:23:22 oauth2: cannot fetch token: 400 Bad Request
Response: {"error":"invalid_client"}
exit status 1
TAMILVIP007 commented 1 year ago

done

percit commented 12 months ago

How did You fix it?

Oladipupo commented 1 month ago

Frustrating when people just say done and they do not explain how they fixed it.