> ## 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.

# 使用 Twitch 和 HTML5 设置 PlayFab 身份验证

> 使用 HTML5 和 JavaScript 将 Twitch 登录添加到 PlayFab title 的分步教程，涵盖 Twitch 应用注册和 OAuth 玩家身份验证。

本教程旨在指导你完成使用 Twitch 和 HTML5/JavaScript 进行 PlayFab 身份验证的过程。

## 要求

在开始之前，你应具备：

* 一个用于测试的 [Twitch 账户](https://www.twitch.tv/)。
* 已注册的 [PlayFab](https://developer.playfab.com/) title。
* 熟悉[登录基础和最佳实践](/services/playfab/identity/player-identity/login/login-basics-best-practices)。
* 至少一个具有有效域名以提供静态 HTML 文件的服务器。

<Note>
  请参阅[为测试运行 HTTP 服务器](/services/playfab/identity/player-identity/platform-specific-authentication/running-an-http-server-for-testing)教程，了解如何设置具有有效域名的服务器。
</Note>

## 服务器和域名

本教程需要一个 Web 服务器才能按照说明操作。如果你还没有注册远程 Web 服务器，请按照我们的[为测试运行 HTTP 服务器](/services/playfab/identity/player-identity/platform-specific-authentication/running-an-http-server-for-testing)教程了解如何运行本地 Web 服务器。

<Note>
  在本教程中，我们假设你的域名是 `[http://localhost/](http://localhost/)`。
</Note>

## 注册 Twitch 应用程序

首先导航到 [Twitch 网站](https://www.twitch.tv/)，并验证你已登录。

1. 导航到 **Account** 下拉菜单。
2. 从提供的菜单中选择 **Settings**。

<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="Twitch account settings" width="1029" height="643" data-path="images/playfab/identity/player-identity/platform-specific-authentication/tutorials/twitch-html5/twitch-account-settings.png" />

在 **Settings** 页面上，选择 **Connections (1)**，如下所示。

<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="Twitch settings connections" width="1016" height="198" data-path="images/playfab/identity/player-identity/platform-specific-authentication/tutorials/twitch-html5/twitch-settings-connections.png" />

在页面底部，选择 **Register your application (1)** 按钮，如下所示。

<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="Twitch open application registration page" width="690" height="227" data-path="images/playfab/identity/player-identity/platform-specific-authentication/tutorials/twitch-html5/twitch-open-application-registration.png" />

允许你配置新应用的页面将打开。

1. 填写 **Application** 的 **Name**。
2. 输入 **Redirect URL**。
3. 输入 **Application Category**。
4. 然后同意 **Twitch** 条款，并选择 **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="Twitch register your application" width="1029" height="643" data-path="images/playfab/identity/player-identity/platform-specific-authentication/tutorials/twitch-html5/twitch-register-your-application.png" />

<Info>
  使用本地 Web 服务器进行测试时，Twitch 允许你使用 `**<http://localhost>**` 作为重定向 URL。请务必包含尾随斜杠 **/**。如果没有尾随斜杠，Twitch 将无法识别 localhost URL。
</Info>

注册应用程序后，页面将更新并显示你的应用程序的 Client ID。

<Note>
  将此 Client ID 保存在安全且易于访问的位置，因为你稍后将使用它来配置你的 PlayFab title。
</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="Twitch manage application" width="1029" height="643" data-path="images/playfab/identity/player-identity/platform-specific-authentication/tutorials/twitch-html5/twitch-manage-application.png" />

## 配置 PlayFab title

获取 Twitch Client ID 后，你可以为 PlayFab title 启用和配置 Twitch 附加组件。

1. 在你的 **PlayFab Title** 屏幕上，转到菜单并选择 **Add-ons** 项。
2. 然后选择 **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="Game Manager Add-ons tab" width="624" height="545" data-path="images/playfab/identity/player-identity/platform-specific-authentication/tutorials/twitch-html5/game-manager-addons-tab-twitch.png" />

在 **Twitch** 页面上：

* **Twitch Add-on** 的 **Settings** 页面将打开。
* 输入你的 **Twitch Client ID**。
* 选择 **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="Game Manager Twitch Add-on settings and install" width="893" height="599" data-path="images/playfab/identity/player-identity/platform-specific-authentication/tutorials/twitch-html5/game-manager-twitch-addon-settings.png" />

花点时间验证附加组件已安装且没有发生错误。至此完成了 PlayFab title 的配置。

## 测试

使用以下 HTML 文件测试使用 Twitch 的 PlayFab 身份验证。

请务必用你自己的值替换 `TWITCH_CLIENT_ID_GOES_HERE` 和 `PLAYFAB_TITLE_ID_GOES_HERE`。

```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. 使用你在 Twitch 应用程序配置期间设置的域名（在我们的例子中为 `<http://localhost>`）从你的服务器请求以下文件。

2. 页面打开后，等待指示 **Twitch SDK** 已初始化的消息。

3. 然后选择 **Login with Twitch** 按钮。

4. 按照弹窗中的任何 **Twitch** 说明操作，并观察输出。

<Info>
  如果你到达页面时*已经有*一个 Twitch 身份验证会话正在进行，则回调可能以不同的、意外的顺序触发。这种情况显示在下面的屏幕截图中。但是，你应确保仅在 **Logged in with Twitch** 之后跟随 **Logging in via PlayFab**。这表示令牌已被接收或从本地存储中恢复，我们不必等待 Twitch SDK 开始登录到 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="Twitch Auth Example" width="489" height="416" data-path="images/playfab/identity/player-identity/platform-specific-authentication/tutorials/twitch-html5/twitch-auth-example.png" />

如果 PlayFab 成功获取 `SessionTicket`，则你已成功将 Twitch 身份验证与你的 PlayFab 应用集成。


## Related topics

- [特定平台的身份验证](/zh-CN/services/playfab/identity/player-identity/platform-specific-authentication/index.md)
- [使用 Google 和 HTML5 设置 PlayFab 身份验证](/zh-CN/services/playfab/identity/player-identity/platform-specific-authentication/google-html5.md)
- [使用 Facebook 和 HTML5 设置 PlayFab 身份验证](/zh-CN/services/playfab/identity/player-identity/platform-specific-authentication/facebook-html5.md)
- [使用 Kongregate 和 HTML5 设置 PlayFab 身份验证](/zh-CN/services/playfab/identity/player-identity/platform-specific-authentication/kongregate-html5.md)
- [为 PlayFab 设置 Sign In with Battle.net](/zh-CN/services/playfab/identity/player-identity/platform-specific-authentication/battlenet-login.md)
