I have an error while trying to connect to the api with my unity app

Actually this is where i take the Auth Token, this works on my web browser.

void GetAuthToken()
    {
        // Reemplaza [CLIENT-ID] y [CLIENT-SECRET] con tus propias credenciales de Twitch
        string clientId = "pop";
        string clientSecret = "yt";

        // Crea una solicitud POST a la API de Twitch para obtener el token de autenticación
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://id.twitch.tv/oauth2/token?Client-ID=" + clientId + "&client_secret=" + clientSecret + "&grant_type=client_credentials");
        //HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://id.twitch.tv/oauth2/authorize?client_id=" + clientId + "&redirect_uri=http://localhost&response_type=token&scope=user_read");
        request.Method = "POST";

        // Lee la respuesta y obtiene el token de autenticación
        using (WebResponse response = request.GetResponse())
        {
            using (Stream stream = response.GetResponseStream())
            {
                using (StreamReader reader = new StreamReader(stream))
                {
                    string jsonResponse = reader.ReadToEnd();
                    AuthToken token = JsonUtility.FromJson<AuthToken>(jsonResponse);
                    authToken = token.access_token;
                }
            }
        }
        PlayerPrefs.SetString("authToken", authToken);
    }

At this step I’m trying to get the url of the stream and i can’t:

IEnumerator GetStreamUrl()
    {
        string authToken = PlayerPrefs.GetString("authToken");
        // Crea una solicitud GET a la API de Twitch para obtener la información del stream
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.twitch.tv/helix/streams?user_login=" + twitchUsername);
        request.Method = "GET";
        request.Headers.Add("Authorization", "Bearer " + authToken); // Agrega el token de autenticación en el encabezado
        request.ContentType = "application/json";

        // Realiza la solicitud GET y lee la respuesta
        using (WebResponse response = request.GetResponse())
        {
            using (Stream stream = response.GetResponseStream())
            {
                using (StreamReader reader = new StreamReader(stream))
                {
                    string jsonResponse = reader.ReadToEnd();
                    StreamInfo streamInfo = JsonUtility.FromJson<StreamInfo>(jsonResponse);
                    streamUrl = streamInfo.data[0].thumbnail_url.Replace("{width}", "1920").Replace("{height}", "1080").Replace("-preview.jpg", ".m3u8");
                }
            }
        }

        // Carga la URL del stream en el objeto RawImage
        //rawImage.texture = new WWW(streamUrl).texture;
        material.mainTexture = new WWW(streamUrl).texture;
        yield break;
    }

And this is my error:

WebException: The remote server returned an error: (401) Unauthorized.
System.Net.HttpWebRequest.GetResponseFromData (System.Net.WebResponseStream stream, System.Threading.CancellationToken cancellationToken) (at <111da4cba18442e7addb95bcddc21c3b>:0)
System.Net.HttpWebRequest.RunWithTimeoutWorker[T] (System.Threading.Tasks.Task1[TResult] workerTask, System.Int32 timeout, System.Action abort, System.Func1[TResult] aborted, System.Threading.CancellationTokenSource cts) (at <111da4cba18442e7addb95bcddc21c3b>:0)
System.Net.HttpWebRequest.GetResponse () (at <111da4cba18442e7addb95bcddc21c3b>:0)
TwitchLiveStream+d__6.MoveNext () (at Assets/Scripts/VideoLoader/TwitchLiveStream.cs:65)
UnityEngine.SetupCoroutine.InvokeMoveNext (System.Collections.IEnumerator enumerator, System.IntPtr returnValueAddress) (at :0)
UnityEngine.MonoBehaviour:StartCoroutine(IEnumerator)
TwitchLiveStream:Start() (at Assets/Scripts/VideoLoader/TwitchLiveStream.cs:23)

This should be

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://id.twitch.tv/oauth2/token?client_id=" + clientId + "&client_secret=" + clientSecret + "&grant_type=client_credentials");

The client_id parameter is all lower case and a _ instead of a -

Sorry but I have changed to try it on another way, It’s not that the problem i have tried right now again without caps and I have the same error.

I forgot to add this lines:

// Clase para el token de autenticación de Twitch
    [System.Serializable]
    private class AuthToken
    {
        public string access_token;
        public string token_type;
    }

    // Clase para la información del stream de Twitch
    [System.Serializable]
    private class StreamInfo
    {
        public StreamData[] data;
    }

    [System.Serializable]
    private class StreamData
    {
        public string thumbnail_url;
    }

Then revise your code to return the body of the response

Your error log only outputs the HTTP Code and a error blob from the library
There should be a JSON Blob/body which will describe the error.

I’m trying but the program doesnt enter inside the next lines:

using (WebResponse response = request.GetResponse()){
            using (Stream stream = response.GetResponseStream())
            {
                using (StreamReader reader = new StreamReader(stream))
                {
                    string jsonResponse = reader.ReadToEnd();
                    if (response is HttpWebResponse httpWebResponse)
                    {
                        Debug.LogError($"Error ({httpWebResponse.StatusCode}): {httpWebResponse.StatusDescription}\n{jsonResponse}");
                    }
                    StreamInfo streamInfo = JsonUtility.FromJson<StreamInfo>(jsonResponse);
                    streamUrl = streamInfo.data[0].thumbnail_url.Replace("{width}", "1920").Replace("{height}", "1080").Replace("-preview.jpg", ".m3u8");
                }
            }
        }

You may want to check out the game plug-in closed beta if you are making a unity app. Twitch Game Engine Plugins Closed Beta Application

I have applied i hope i get it as soon as possible to test it!

Hello, I have find a solution to the problem, i forgot this line at GetStreamUrl():

request.Headers.Add("Client-Id", clientId);

But now my material is not rendering every frame the stream. How anyone knows how can i do it?

Thanks!

This topic was automatically closed after 30 days. New replies are no longer allowed.