> ## 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 entrada com Battle.net para o PlayFab

> Configure a autenticação do PlayFab com Battle.net usando HTML5 e JavaScript, incluindo a configuração do aplicativo da Blizzard, o fluxo OAuth e a integração da entrada do jogador.

# Configurar a autenticação do PlayFab com Battle.net

Este tutorial orienta você no processo de configuração da autenticação do PlayFab usando Battle.net e HTML5/JavaScript.

## Requisitos

Você precisa de:

* Uma [conta Battle.net](https://developer.battle.net) para testes.
* Um título registrado no [PlayFab](https://developer.playfab.com/).
* Familiaridade com [Noções básicas e práticas recomendadas de login](/pt-BR/services/playfab/identity/player-identity/login/login-basics-best-practices).
* Um servidor com um nome de domínio válido para servir um arquivo HTML estático. Consulte o tutorial [Executando 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 e domínio

Para seguir este guia, é necessário um servidor com um domínio válido. Se você ainda não tiver um domínio registrado e um servidor Web remoto, siga nosso tutorial [Executando 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 Web local com um nome de domínio válido.

Ao longo deste guia, presumimos que seu domínio seja [http://playfab.example](http://playfab.example).

## Recuperar a Client ID do título do Battle.net

Comece navegando até o [Battle.net](https://developer.battle.net) e crie uma conta de desenvolvedor do Battle.net. Depois que sua conta for criada, você precisará criar um título e receber Client IDs.

## Instalar o complemento do Battle.net

Acesse a página do **Game Manager** do PlayFab para o seu título.

1. Navegue até **Add-ons** no menu.
2. Localize e abra o ícone/link do **complemento do Battle.net**.

<img src="https://mintcdn.com/microsoft-4404708b/mLCHf0iQv3VidfBe/images/playfab/identity/player-identity/platform-specific-authentication/tutorials/battlenet/battlenet-partner-add-on-page.png?fit=max&auto=format&n=mLCHf0iQv3VidfBe&q=85&s=de4613079755faeb998407ac4158da89" alt="Complemento do PlayFab Game Manager" width="1248" height="555" data-path="images/playfab/identity/player-identity/platform-specific-authentication/tutorials/battlenet/battlenet-partner-add-on-page.png" />

3. Selecione **Install Battle.net**.

<img src="https://mintcdn.com/microsoft-4404708b/mLCHf0iQv3VidfBe/images/playfab/identity/player-identity/platform-specific-authentication/tutorials/battlenet/battlenet-add-on.png?fit=max&auto=format&n=mLCHf0iQv3VidfBe&q=85&s=f9828e789c2285bbde0d456d7f307102" alt="Complemento do Battle.net no PlayFab Game Manager" width="1248" height="545" data-path="images/playfab/identity/player-identity/platform-specific-authentication/tutorials/battlenet/battlenet-add-on.png" />

4. Preencha a **Client ID for Game Client**.
5. Opcionalmente, preencha uma **Client ID for Game Server**.
6. Em seguida, selecione o botão **Save settings**.

<img src="https://mintcdn.com/microsoft-4404708b/mLCHf0iQv3VidfBe/images/playfab/identity/player-identity/platform-specific-authentication/tutorials/battlenet/battlenet-validated.png?fit=max&auto=format&n=mLCHf0iQv3VidfBe&q=85&s=1fe7a49156f04e31ae204c6f7ce6a9ef" alt="Client IDs do complemento do Battle.net no PlayFab Game Manager" width="1248" height="650" data-path="images/playfab/identity/player-identity/platform-specific-authentication/tutorials/battlenet/battlenet-validated.png" />

O Battle.net é exibido como ativo na página de complementos.

<img src="https://mintcdn.com/microsoft-4404708b/mLCHf0iQv3VidfBe/images/playfab/identity/player-identity/platform-specific-authentication/tutorials/battlenet/battlenet-partner-add-on-page-active.png?fit=max&auto=format&n=mLCHf0iQv3VidfBe&q=85&s=42e07d365b7f93b5e3014039e91ac91b" alt="Complemento do Battle.net ativo no PlayFab Game Manager" width="1248" height="561" data-path="images/playfab/identity/player-identity/platform-specific-authentication/tutorials/battlenet/battlenet-partner-add-on-page-active.png" />

## Testando com um token de acesso

Neste exemplo, mostramos como testar a API LoginWithBattleNet usando a abordagem clássica de token de acesso. Use o código HTML fornecido para seus testes.

<Note>
  *Certifique-se* de substituir `YOUR_CLIENT_ID`, `YOUR_PLAYFAB_TITLE_ID`, `YOUR_BNET_TITLE_NAME` e `YOUR_CLIENT_SECRET` pelos seus próprios valores.
</Note>

```html theme={null}
<!DOCTYPE html>
<html>
<head>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head>
<body>
    <h2>Battle.net SSO Token Demo (Manual Flow)</h2>
    <ol>
        <li>
            <button onclick="openBattleNetLogin()">Log in to Battle.net</button>
        </li>
        <li>
            After login, copy the <b>ST</b> value from the URL (e.g. <code>ST=US-xxxx-xxxx) and paste it here:
            

            <input type="text" id="ssoToken" size="80" placeholder="Paste SSO token (ST=...)" />
        </li>
        <li>
            Click "Exchange SSO Token for id_token"

            <button onclick="exchangeSSOToken()">Exchange SSO Token for id_token</button>
            

            <label>id_token:</label>

            <input type="text" id="idToken" size="80" placeholder="id_token will appear here" />
        </li>
        <li>
            Click "Login to PlayFab" to complete the flow

            <button onclick="loginWithPlayFab()">Login to PlayFab</button>
        </li>
    </ol>
    

    <div id="log"></div>
    <script>
        // Demo configuration variables
        const BNET_TITLE_NAME = 'YOUR_BNET_TITLE_NAME';
        const PLAYFAB_TITLE_ID = 'YOUR_PLAYFAB_TITLE_ID';
        const CLIENT_ID = 'YOUR_CLIENT_ID';
        const CLIENT_SECRET = 'YOUR_CLIENT_SECRET';

        function openBattleNetLogin() {
            const url = `http://account.battle.net/login/en/?app=${encodeURIComponent(BNET_TITLE_NAME)}`;
            window.open(url, '_blank');
        }

        function exchangeSSOToken() {
            const ssoToken = document.getElementById('ssoToken').value.trim();
            if (!ssoToken) {
                logLine("Please enter the SSO token.");
                return;
            }
            logLine("Exchanging SSO token for id_token...");
            // Prepare the request for the token exchange
            const params = new URLSearchParams();
            params.append('scope', 'account.basic openid');
            params.append('grant_type', 'urn:ietf:params:oauth:grant-type:token-exchange');
            params.append('subject_token', ssoToken);
            params.append('subject_token_type', 'urn:blizzard:params:oauth:token-type:sso');
            params.append('requested_token_type', 'urn:ietf:params:oauth:token-type:jwt');

            // Basic Auth header
            const authHeader = 'Basic ' + btoa(CLIENT_ID + ':' + CLIENT_SECRET);

            fetch('https://oauth.battle.net/token', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'Authorization': authHeader
                },
                body: params
            })
            .then(res => res.json())
            .then(data => {
                if (data.id_token) {
                    document.getElementById('idToken').value = data.id_token;
                    logLine("id_token received.");
                } else {
                    logLine("Error: " + JSON.stringify(data));
                }
            })
            .catch(err => logLine("Error: " + err));
        }

        function loginWithPlayFab() {
            const idToken = document.getElementById('idToken').value.trim();
            if (!idToken) {
                logLine("Please exchange for an id_token first.");
                return;
            }
            logLine("Logging in to PlayFab...");
            axios.post(
                `https://${PLAYFAB_TITLE_ID}.playfabapi.com/Client/LoginWithBattleNet`,
                {
                    TitleId: PLAYFAB_TITLE_ID,
                    IdentityToken: idToken,
                    CreateAccount: true
                },
                {
                    headers: {
                        'Content-Type': 'application/json'
                    }
                }
            )
            .then(response => logLine("Response: " + JSON.stringify(response.data)))
            .catch(error => logLine("Error: " + JSON.stringify(error.response ? error.response.data : error)));
        }

        function logLine(message) {
            const logDiv = document.getElementById('log');
            logDiv.innerHTML += message + "
";
        }
    </script>
</body>
</html></code>
```

Lembre-se de abrir a página HTML usando seu servidor Web e certifique-se de acessar essa página usando a URL que você especificou.

1. Quando a página abrir, selecione **Log in to Battle.net**.
2. Depois de entrar, copie o valor **ST** da URL (por exemplo: ST=US-xxxx-xxxx) e insira-o na caixa de diálogo.
3. Selecione **Exchange SSO Token for id\_token** e copie o valor na caixa de diálogo.
4. Selecione **Login to PlayFab** para concluir o fluxo de entrada.
5. Quando terminar, o script tentará se autenticar no lado do PlayFab e mostrará o resultado.

<img src="https://mintcdn.com/microsoft-4404708b/mLCHf0iQv3VidfBe/images/playfab/identity/player-identity/platform-specific-authentication/tutorials/battlenet/battlenet-token-demo.png?fit=max&auto=format&n=mLCHf0iQv3VidfBe&q=85&s=6436d543b2543a12c1842bb36ad4021d" alt="Exemplo de autenticação do Battle.net" width="2027" height="961" data-path="images/playfab/identity/player-identity/platform-specific-authentication/tutorials/battlenet/battlenet-token-demo.png" />


## Related topics

- [Obter IDs do PlayFab a partir de IDs de conta do Battle Net](/pt-BR/services/playfab/api-references/rest/server/account-management/get-playfab-ids-from-battle-net-account-ids.md)
- [Configurar a autenticação do PlayFab com aplicativos UWP](/pt-BR/services/playfab/identity/player-identity/platform-specific-authentication/uwp.md)
- [Autenticação do PlayFab com a entrada com o Google Play Games no Unity](/pt-BR/services/playfab/identity/player-identity/platform-specific-authentication/google-sign-in-unity.md)
- [Fazer logon com Battle.net](/pt-BR/services/playfab/api-references/rest/client/authentication/login-with-battle-net.md)
- [Autenticação específica da plataforma](/pt-BR/services/playfab/identity/player-identity/platform-specific-authentication/index.md)
