# Steam

> Provide a Steam sign-in option to enable players to authenticate using their Steam accounts in your game.

###### 最小 SDK バージョン: 2.0.0##minimum-sdk-version-200

このセクションでは、Steam アカウントを使用してゲーム内でのプレイヤーの認証を設定する以下のシナリオについて説明します。

* Steam アカウントサインインを設定する。
* 戻ってきたプレイヤーをサインインする、または新しいプレイヤーを作成する。
* 匿名ログインから Steam アカウントを介したプラットフォームログインへとプレイヤーを更新する。

ゲーム内のプレイヤーに Steam サインインのオプションを提供するには、SteamWorks パートナーポータルでアプリケーションを作成し、[Steamworks.Net SDK](https://partner.steamgames.com/doc/webapi_overview/auth) をインストールしてプレイヤーをサインインし、セッションチケットを取得してください。

## Steam アカウントサインインの設定

1. アプリケーションを作成し、[Steamworks のドキュメント](https://partner.steamgames.com/doc/store/application#creating_applications) に従ってアプリケーション ID をメモします。

2. [ウェブ API キーを使用した認証](https://partner.steamgames.com/doc/webapi_overview/auth) のドキュメントに従って、パブリッシャーウェブ API キーを作成します。

3. [Unity 用に SDK をインストールするための手順](http://steamworks.github.io/installation/) に従って、[SteamWorks.Net SDK](https://github.com/rlabrecque/Steamworks.NET/releases) をインストールします。

   1. SteamWorks.Net SDK をプロジェクトの *Assets/* フォルダーにコピーします。
   2. Unity プロジェクトのルートにある *steam\_appid.txt* ファイルを開き、480 を自分のアプリケーション ID に置き換えます。
   3. シーン内のゲームオブジェクトに Steam Manager ゲームコンポーネントを追加します。これにより、Steam ライブラリが初期化されます。
   4. テストを行う前に、Steam がインストールされ、サインインされていることを確認してください。Steam ユーザーのライブラリには、開発中のゲームが表示されます。

4. Unity Authentication について、ID プロバイダーを Steam に設定します。

   1. Unity エディターメニューで、**Edit** (編集) > **Project Settings...** (プロジェクト設定...) を選択し、ナビゲーションメニューから **Services** (サービス) > **Authentication** を選択します。
   2. **ID Providers** (ID プロバイダー) を **Steam** に設定し、**Add** (追加) を選択します。
   3. **App ID** テキストフィールドにアプリケーション ID を入力します。
   4. **Key** テキストフィールドにパブリッシャーウェブ API キーを入力し、**Save** (保存) を選択します。

   > **Note:**
   >
   > (任意) Demo、PlayTest、Alpha ビルド用の App ID を追加します。まだ **Authentication Settings** (認証設定) 内です。
   >
   > 1. **Additional App ID** (追加の App ID) の横にある矢印を選択します。
   > 2. 展開されたビューの下部にある **Add App ID** (App ID を追加) を選択します。
   > 3. **App ID** と **Description** (説明) を入力します。
   > 4. **Save** (保存) を選択します。

5. 以下のサンプルコードを使用して Steam サインインを実装します。[GetAuthTicketForWebApi](https://partner.steamgames.com/doc/api/ISteamUser#GetAuthTicketForWebApi) のドキュメントを参照してください。Unity Authentication SDK は Steam セッションチケットのみを受け入れます。暗号化されたアプリケーションチケットは受け入れられません。

> **Warning:**
>
> **重要**: Steam SDK で提供される **OnAuthCallback** に登録することは非常に重要です。これにより、適切な認証チケットの検証が行われます。詳細については、[こちら](https://partner.steamgames.com/doc/api/ISteamUser#GetAuthTicketForWebApi) を参照してください。以下のコードは、Steam 認証の効果的な使用例です。**重要**:Unity Player Authentication では、英数字で構成された、5 文字以上 30 文字以下の文字列だけが **identity** フィールドとして受け入れられます。チケットをリクエストする際には、これと同じ要件に従って同じ文字列を使用するようにしてしてください。

```cs
Callback<GetTicketForWebApiResponse_t> m_AuthTicketForWebApiResponseCallback;
string m_SessionTicket;
string identity = "unityauthenticationservice"

void SignInWithSteam()
{
    // It's not necessary to add event handlers if they are 
    // already hooked up.
    // Callback.Create return value must be assigned to a 
    // member variable to prevent the GC from cleaning it up.
    // Create the callback to receive events when the session ticket
    // is ready to use in the web API.
    // See GetAuthSessionTicket document for details.
    m_AuthTicketForWebApiResponseCallback = Callback<GetTicketForWebApiResponse_t>.Create(OnAuthCallback);

    SteamUser.GetAuthTicketForWebApi(identity);
}

void OnAuthCallback(GetTicketForWebApiResponse_t callback)
{
    m_SessionTicket = BitConverter.ToString(callback.m_rgubTicket).Replace("-", string.Empty);
    m_AuthTicketForWebApiResponseCallback.Dispose();
    m_AuthTicketForWebApiResponseCallback = null;
    Debug.Log("Steam Login success. Session Ticket: " + m_SessionTicket);
    // Call Unity Authentication SDK to sign in or link with Steam, displayed in the following examples, using the same identity string and the m_SessionTicket.
}
```

> **Note:**
>
> **ノート**: 以下のコード例は、`GetAuthTicketForWebApi` メソッドを使用してプレイヤーの Steam セッションチケットをすでに取得済みであることと、チケットを発行するために同じ `identity` パラメーターを渡していることを前提としています。

## 戻ってきたプレイヤーのサインインまたは新しいプレイヤーの作成##sign-in-a-returning-player-or-create-new-player

`SignInWithSteamAsync` メソッドを使用して、以下のいずれかを行います。

* Steam の認証情報を使用して新しい Unity Authentication プレイヤーを作成する。
* Steam の認証情報を使用して既存のプレイヤーをサインインする。

プロジェクト内の Unity Authentication プレイヤーが認証情報と関連付けられていない場合、`SignInWithSteamAsync` は新しいプレイヤーを作成します。プロジェクト内の Unity Authentication プレイヤーが認証情報と関連付けられている場合、`SignInWithSteamAsync` はそのプレイヤーのアカウントにサインインします。この関数ではキャッシュされたプレイヤーは考慮されません。`SignInWithSteamAsync` はキャッシュされたプレイヤーを置き換えます。

```cs
async Task SignInWithSteamAsync(string ticket, string identity)
{
    try
    {
        await AuthenticationService.Instance.SignInWithSteamAsync(ticket, identity);
        Debug.Log("SignIn is successful.");
    }
    catch (AuthenticationException ex)
    {
        // Compare error code to AuthenticationErrorCodes
        // Notify the player with the proper error message
        Debug.LogException(ex);
    }
    catch (RequestFailedException ex)
    {
        // Compare error code to CommonErrorCodes
        // Notify the player with the proper error message
        Debug.LogException(ex);
    }
}
```

## プレイヤーを匿名から Steam アカウントへと更新する##update-a-player-from-anonymous-to-a-steam-account

匿名認証を設定した後、プレイヤーが匿名からアップグレードし、Steam アカウントを作成してサインインすることを希望する場合は、ゲームのプレイヤーにプロンプトを表示し、Steam サインインをトリガーして Steam からセッションチケットを取得するよう求める必要があります。その後、LinkWithSteamAsync API を呼び出して、プレイヤーを Steam セッションチケットにリンクします。

キャッシュされたプレイヤーが SDK に存在する場合は、キャッシュされたプレイヤーを Steam アカウントにリンクできます。

1. `SignInAnonymouslyAsync` を使用して、キャッシュされたプレイヤーのアカウントにサインインします。
2. `LinkWithSteamAsync` を使用して、キャッシュされたプレイヤーのアカウントを Steam アカウントにリンクします。

```cs
async Task LinkWithSteamAsync(string ticket, string identity)
{
    try
    {
        await AuthenticationService.Instance.LinkWithSteamAsync(ticket, identity);
        Debug.Log("Link is successful.");
    }
    catch (AuthenticationException ex) when (ex.ErrorCode == AuthenticationErrorCodes.AccountAlreadyLinked)
    {
        // Prompt the player with an error message.
        Debug.LogError("This user is already linked with another account. Log in instead.");
    }
    catch (Exception ex)
    {
        Debug.LogError("Link failed.");
        Debug.LogException(ex);
    }
}
```

プレイヤーが、サインインまたは新しいプレイヤープロファイルの作成によって Steam サインインをトリガーする場合、同じ **identity** パラメーターを使用して Steam アクセストークンを受け取ったら、以下の API を呼び出してプレイヤーの認証を行います。

```cs
async Task SignInWithSteamAsync(string ticket, string identity)
{
    try
    {
        await AuthenticationService.Instance.SignInWithSteamAsync(ticket, identity);
    }
    catch (AuthenticationException ex)
    {
        // Compare error code to AuthenticationErrorCodes
        // Notify the player with the proper error message
        Debug.LogException(ex);
    }
    catch (RequestFailedException ex)
    {
        // Compare error code to CommonErrorCodes
        // Notify the player with the proper error message
        Debug.LogException(ex);
    }
}
```

## 戻ってきたプレイヤーをサインインするか、追加の App ID 用に新しいプレイヤーを作成する##sign-in-a-returning-player-or-create-new-player-for-additional-app-ids

追加の App ID (Demo、PlayTest、Alpha など) にプレイヤーをサインインするには、同じ `SignInWithSteamAsync` メソッドを使用します。

> **Note:**
>
> **ノート**: 以下のコード例は、`GetAuthTicketForWebApi` メソッドを使用してプレイヤーの Steam セッションチケットをすでに取得済みであることと、チケットを発行するために同じ `identity` パラメーターを渡していることを前提としています。

> **Warning:**
>
> **重要**: プレイヤーは、同じプロジェクト内のすべての App ID で同一の Unity Authentication プレイヤー ID を持つことになります。そのため、本番データと非本番データが混在しないように最善の判断をした上で、異なる環境を設定し、各 App ID に対するプレイヤーデータ (Economy、Cloud Save など) のスコープが維持されるようにしてください。

```cs
async Task SignInWithSteamAsync(string ticket, string identity, string appId)
{
    try
    {
        await AuthenticationService.Instance.SignInWithSteamAsync(ticket, identity, appId);
        Debug.Log("SignIn is successful.");
    }
    catch (AuthenticationException ex)
    {
        // Compare error code to AuthenticationErrorCodes
        // Notify the player with the proper error message
        Debug.LogException(ex);
    }
    catch (RequestFailedException ex)
    {
        // Compare error code to CommonErrorCodes
        // Notify the player with the proper error message
        Debug.LogException(ex);
    }
}
```

## Steam サインイン認証を実装する##unlink-steam-account

Steam セッションチケットを使用して、Steam アカウントでサインインまたはリンクすることができます。プレイヤーをサインインするには、以下の API を呼び出します。 `SignInWithSteamAsync(string ticket, string identity)`

```cs
Unlink Steam account#
Use the `UnlinkSteamAsync` API so your players can unlink their Steam account. Once unlinked, if their account isn’t linked to any additional identity, it transitions to an anonymous account.

async Task UnlinkSteamAsync(string idToken)
{
   try
   {
       await AuthenticationService.Instance.UnlinkSteamAsync(idToken);
       Debug.Log("Unlink is successful.");
   }
   catch (AuthenticationException ex)
   {
       // Compare error code to AuthenticationErrorCodes
       // Notify the player with the proper error message
       Debug.LogException(ex);
   }
   catch (RequestFailedException ex)
   {
       // Compare error code to CommonErrorCodes
       // Notify the player with the proper error message
       Debug.LogException(ex);
   }
}
```
