> ## Documentation Index
> Fetch the complete documentation index at: https://devdocs.xbox.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Configurar a autenticação do PlayFab usando Twitch e HTML5

> Tutorial passo a passo para adicionar o login do Twitch a um título do PlayFab com HTML5 e JavaScript, abordando o registro do aplicativo do Twitch e a autenticação OAuth do jogador.

Este tutorial foi criado para orientar você no processo de autenticação do PlayFab usando Twitch e HTML5/JavaScript.

## Requisitos

Antes de começar, você deve ter:

* Uma [conta do Twitch](https://www.twitch.tv/) para testes.
* Um título do [PlayFab](https://developer.playfab.com/) registrado.
* Familiaridade com os [conceitos básicos e práticas recomendadas de login](/pt-BR/services/playfab/identity/player-identity/login/login-basics-best-practices).
* No mínimo, um servidor com um nome de domínio válido para servir arquivos HTML estáticos.

<Note>
  Consulte o tutorial [Executar um servidor HTTP para testes](/pt-BR/services/playfab/identity/player-identity/platform-specific-authentication/running-an-http-server-for-testing) para obter informações sobre como configurar um servidor com um nome de domínio válido.
</Note>

## Servidor e domínio

Este tutorial exige um servidor Web para seguir as instruções. Se você ainda não tiver um servidor Web remoto registrado, siga nosso tutorial [Executar um servidor HTTP para testes](/pt-BR/services/playfab/identity/player-identity/platform-specific-authentication/running-an-http-server-for-testing) para obter informações sobre como executar um servidor Web local.

<Note>
  Ao longo deste tutorial, presumiremos que seu domínio é `[http://localhost/](http://localhost/)`.
</Note>

## Registrar um aplicativo do Twitch

Comece navegando até o [site do Twitch](https://www.twitch.tv/) e verificando se você está conectado.

1. Navegue até a lista suspensa **Account**.
2. Selecione **Settings** no menu fornecido.

<img src="https://mintcdn.com/microsoft-4404708b/mLCHf0iQv3VidfBe/images/playfab/identity/player-identity/platform-specific-authentication/tutorials/twitch-html5/twitch-account-settings.png?fit=max&auto=format&n=mLCHf0iQv3VidfBe&q=85&s=16b0349a480883b4517f021b9f43b337" alt="Configurações da conta do Twitch" width="1029" height="643" data-path="images/playfab/identity/player-identity/platform-specific-authentication/tutorials/twitch-html5/twitch-account-settings.png" />

Na página **Settings**, selecione **Connections (1)**, conforme mostrado abaixo.

<img src="https://mintcdn.com/microsoft-4404708b/3hg2JQs0m7qmDqay/images/playfab/identity/player-identity/platform-specific-authentication/tutorials/twitch-html5/twitch-settings-connections.png?fit=max&auto=format&n=3hg2JQs0m7qmDqay&q=85&s=4f6e6dc81498ffe1a7007c0ae060eab4" alt="Conexões nas configurações do Twitch" width="1016" height="198" data-path="images/playfab/identity/player-identity/platform-specific-authentication/tutorials/twitch-html5/twitch-settings-connections.png" />

Na parte inferior da página, selecione o botão **Register your application (1)**, conforme mostrado abaixo.

<img src="https://mintcdn.com/microsoft-4404708b/3hg2JQs0m7qmDqay/images/playfab/identity/player-identity/platform-specific-authentication/tutorials/twitch-html5/twitch-open-application-registration.png?fit=max&auto=format&n=3hg2JQs0m7qmDqay&q=85&s=d9b6a12d357e2364a422502ce3e943bd" alt="Abrir a página de registro de aplicativo do Twitch" width="690" height="227" data-path="images/playfab/identity/player-identity/platform-specific-authentication/tutorials/twitch-html5/twitch-open-application-registration.png" />

Será aberta uma página que permite configurar um novo aplicativo.

1. Preencha o **Name** do **Application**.
2. Insira a **Redirect URL**.
3. Insira a **Application Category**.
4. Em seguida, aceite os termos do **Twitch** e selecione o botão **Register**.

<img src="https://mintcdn.com/microsoft-4404708b/3hg2JQs0m7qmDqay/images/playfab/identity/player-identity/platform-specific-authentication/tutorials/twitch-html5/twitch-register-your-application.png?fit=max&auto=format&n=3hg2JQs0m7qmDqay&q=85&s=2f039af883eeeea4f5141f2b5f560cae" alt="Registrar seu aplicativo no Twitch" width="1029" height="643" data-path="images/playfab/identity/player-identity/platform-specific-authentication/tutorials/twitch-html5/twitch-register-your-application.png" />

<Info>
  Ao testar com um servidor Web local, o Twitch permite usar `**<http://localhost>**` como URL de redirecionamento. Inclua a barra **/** à direita. Sem ela, o Twitch não reconhecerá a URL do localhost.
</Info>

Depois que o aplicativo for registrado, a página será atualizada e revelará a Client ID do seu aplicativo.

<Note>
  Mantenha essa Client ID em um local seguro e de fácil acesso, pois você a usará mais tarde para configurar seu título do PlayFab.
</Note>

<img src="https://mintcdn.com/microsoft-4404708b/mLCHf0iQv3VidfBe/images/playfab/identity/player-identity/platform-specific-authentication/tutorials/twitch-html5/twitch-manage-application.png?fit=max&auto=format&n=mLCHf0iQv3VidfBe&q=85&s=a540ab15379f0a9890594bb1f0b8b57a" alt="Gerenciar aplicativo do Twitch" width="1029" height="643" data-path="images/playfab/identity/player-identity/platform-specific-authentication/tutorials/twitch-html5/twitch-manage-application.png" />

## Configurar um título do PlayFab

Depois de obter a Client ID do Twitch, você poderá habilitar e configurar um complemento do Twitch para seu título do PlayFab.

1. Na tela do **PlayFab Title**, acesse o menu e selecione o item **Add-ons**.
2. Em seguida, selecione o link do ícone do **Twitch**.

<img src="https://mintcdn.com/microsoft-4404708b/mLCHf0iQv3VidfBe/images/playfab/identity/player-identity/platform-specific-authentication/tutorials/twitch-html5/game-manager-addons-tab-twitch.png?fit=max&auto=format&n=mLCHf0iQv3VidfBe&q=85&s=50176ba6202f1f26b095ed278ce8c1ed" alt="Guia Add-ons do Game Manager" width="624" height="545" data-path="images/playfab/identity/player-identity/platform-specific-authentication/tutorials/twitch-html5/game-manager-addons-tab-twitch.png" />

Na página do **Twitch**:

* Uma página **Settings** será aberta para o **Twitch Add-on**.
* Insira sua **Twitch Client ID**.
* Selecione o botão **Install Twitch**.

<img src="https://mintcdn.com/microsoft-4404708b/mLCHf0iQv3VidfBe/images/playfab/identity/player-identity/platform-specific-authentication/tutorials/twitch-html5/game-manager-twitch-addon-settings.png?fit=max&auto=format&n=mLCHf0iQv3VidfBe&q=85&s=ade8d576e742ccb6492da588c5f12cbc" alt="Configurações e instalação do complemento do Twitch no Game Manager" width="893" height="599" data-path="images/playfab/identity/player-identity/platform-specific-authentication/tutorials/twitch-html5/game-manager-twitch-addon-settings.png" />

Reserve um momento para verificar se o complemento foi instalado e se nenhum erro ocorreu. Isso conclui a configuração do título do PlayFab.

## Teste

Use o arquivo HTML a seguir para testar a autenticação do PlayFab usando o Twitch.

Substitua `TWITCH_CLIENT_ID_GOES_HERE` e `PLAYFAB_TITLE_ID_GOES_HERE` pelos seus próprios valores.

```html theme={null}
<!DOCTYPE html>
<html>
<head>
    <!-- Include JQuery - dependency of Twitch JS SDK -->
    <script src="//code.jquery.com/jquery.min.js"></script>
    <!-- Include Twitch SDK -->
    <script src="https://ttv-api.s3.amazonaws.com/twitch.min.js"></script>
    <!-- Include PlayFab SDK -->
    <script src="https://download.playfab.com/PlayFabClientApi.js"></script>
</head>
<body>
    <p>Twitch Auth Example</p>
    <button onclick="login()">Login With Twitch</button>
    <script>
        // Establish Twitch Auth Callback (invoked when logged in with Twitch)
        Twitch.events.addListener('auth.login', function() {
            logLine("Logged in with Twitch!");
            // Invoke login with PlayFab code and pass the token
            loginWithPlayFab(Twitch.getToken());
        });

        // Run Twitch SDK initialization
        Twitch.init({clientId: 'TWITCH_CLIENT_ID_GOES_HERE'}, function(error, status) {
            logLine("Twitch SDK Initialized");
        });

        // This method is invoked when you press the button

        function login() {
            logLine("Logging in via Twitch...");
            Twitch.login({
                scope: ['user_read', 'channel_read']
            });
        }

        function loginWithPlayFab(accessToken){
            logLine("Logging in via PlayFab...");

            // When given accessToken, make call to LoginWithTwitch API Call
            // Make sure to use your own PlayFab Title ID
            PlayFabClientSDK.LoginWithTwitch({
                AccessToken: accessToken,
                TitleId: "PLAYFAB_TITLE_ID_GOES_HERE",
                CreateAccount: true
            }, onPlayFabResponse);
        }

        // Handles response from playfab.
        function onPlayFabResponse(response, error) {
            if (response)
                logLine("Response: " + JSON.stringify(response));
            if (error)
                logLine("Error: " + JSON.stringify(error));
        }

        function logLine(message) {
        console.log(message);
            var textnode = document.createTextNode(message);
            document.body.appendChild(textnode);
            var br = document.createElement("br");
            document.body.appendChild(br);
        }
    </script>
</body>
</html>
```

1. Solicite o arquivo a seguir do seu servidor usando o domínio que você configurou durante a configuração do aplicativo do Twitch, `<http://localhost>` no nosso caso.

2. Quando a página abrir, aguarde a mensagem indicando que o **Twitch SDK** foi inicializado.

3. Em seguida, selecione o botão **Login with Twitch**.

4. Siga as instruções do **Twitch** na janela pop-up e observe a saída.

<Info>
  Se você *já tiver* uma sessão de autenticação do Twitch em andamento ao acessar a página, é possível que os retornos de chamada sejam disparados em uma ordem diferente e inesperada. Esse caso é mostrado na captura de tela abaixo. No entanto, verifique se apenas **Logging in via PlayFab** vem depois de **Logged in with Twitch**. Isso indica que o token foi recebido ou restaurado do armazenamento local e que não precisamos esperar o Twitch SDK para começar a entrar no PlayFab.
</Info>

<img src="https://mintcdn.com/microsoft-4404708b/mLCHf0iQv3VidfBe/images/playfab/identity/player-identity/platform-specific-authentication/tutorials/twitch-html5/twitch-auth-example.png?fit=max&auto=format&n=mLCHf0iQv3VidfBe&q=85&s=8e4934020a31d60a0c4eb5ee8c017558" alt="Exemplo de autenticação do Twitch" width="489" height="416" data-path="images/playfab/identity/player-identity/platform-specific-authentication/tutorials/twitch-html5/twitch-auth-example.png" />

Se o PlayFab conseguir obter um `SessionTicket`, você integrou com êxito a autenticação do Twitch ao seu aplicativo do PlayFab.


## Related topics

- [Autenticação específica da plataforma](/pt-BR/services/playfab/identity/player-identity/platform-specific-authentication/index.md)
- [Configurar a autenticação do PlayFab usando Google e HTML5](/pt-BR/services/playfab/identity/player-identity/platform-specific-authentication/google-html5.md)
- [Configurar a autenticação do PlayFab usando Kongregate e HTML5](/pt-BR/services/playfab/identity/player-identity/platform-specific-authentication/kongregate-html5.md)
- [Configurar a autenticação do PlayFab usando Facebook e HTML5](/pt-BR/services/playfab/identity/player-identity/platform-specific-authentication/facebook-html5.md)
- [Configurar a entrada com Battle.net para o PlayFab](/pt-BR/services/playfab/identity/player-identity/platform-specific-authentication/battlenet-login.md)
