Search code examples
c#apispotify

Collect token on spotify


I liked collect token on spotify api, but program return "Id = 356, Status = WaitingForActivation, Method = "{null}", Result = "{Not yet computed}"". I dont know, if i do someting bad, I’m helping by this question.

Code:

private void code()
{
    var ds = $"https://accounts.spotify.com/authorize?client_id={Properties.Resources.clientidSp}&response_type=code&redirect_uri={url}&show_dialog=true&scope=user-read-private%20user-read-email%20user-modify-playback-state%20user-read-playback-position%20user-library-read%20streaming%20user-read-playback-state%20user-read-recently-played%20playlist-read-private";

    Process.Start(ds);
}

static HttpListener _httpListener = new HttpListener();
private async void Form1_Load(object sender, EventArgs e)
{
    _httpListener.Prefixes.Add("http://localhost:5000/"); 
    _httpListener.Start(); // start server (Run application as Administrator!)
    Console.WriteLine("Server started.");
    Thread _responseThread = new Thread(ResponseThread);
    _responseThread.Start(); // start the response thread
    code();
}


static void ResponseThread()
{
    HttpListenerContext context = _httpListener.GetContext()
    var client = new RestClient("https://accounts.spotify.com/api/token");
    var request = new RestRequest("POST");
    request.AddParameter("grant_type", "authorization_code");
    request.AddParameter("client_secret", Properties.Resources.clientSecredtSp);
    request.AddParameter("client_id", Properties.Resources.clientidSp);
    request.AddParameter("code", context.Request.RawUrl.Replace("/?code=", ""));
    request.AddParameter("redirect_uri", "http://localhost:5000/");

    var responses = client.ExecuteAsync(request);
}

What i need add on my code to collect token?? Thanks for supporting me!!


Solution

  • You're calling an Async method without the await, try changing your code to this (at a minimum) ...

    static async Task ResponseThread()
    {
        HttpListenerContext context = _httpListener.GetContext()
        var client = new RestClient("https://accounts.spotify.com/api/token");
        var request = new RestRequest("POST");
        request.AddParameter("grant_type", "authorization_code");
        request.AddParameter("client_secret", Properties.Resources.clientSecredtSp);
        request.AddParameter("client_id", Properties.Resources.clientidSp);
        request.AddParameter("code", context.Request.RawUrl.Replace("/?code=", ""));
        request.AddParameter("redirect_uri", "http://localhost:5000/");
    
        var responses = await client.ExecuteAsync(request);
    }
    

    ... noting the first and second last lines that I have modified.