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

# Integrar o plug-in do PlayFab do Unreal Engine Marketplace

> Orientações sobre como integrar o plug-in do PlayFab SDK do UE Marketplace ao seu projeto existente integrado ao PlayFab Online Subsystem.

# Guia de início rápido: integrando o PlayFab Online Subsystem ao plug-in do PlayFab do Unreal Engine Marketplace

Este guia de início rápido ajuda você a integrar o [plug-in do PlayFab SDK do Unreal Engine (UE) Marketplace](/pt-BR/services/playfab/sdks/unreal) ao seu projeto existente integrado ao PlayFab Online Subsystem (OSS).

O plug-in do PlayFab SDK é usado para realizar operações de administrador, cliente e servidor do PlayFab, como autenticação de jogadores, gerenciamento de itens virtuais e moedas e criação de recursos sociais. Usado em conjunto com o PlayFab Online Subsystem, seu projeto pode acessar o conjunto completo de recursos do PlayFab para projetos do Unreal Engine.

Ao usar o PlayFab OSS ou o plug-in do PlayFab SDK de forma independente um do outro, a primeira etapa é autenticar um usuário. Usar ambos no mesmo projeto sem a configuração apropriada significa que o PlayFab OSS e o plug-in do PlayFab SDK farão, cada um, uma chamada de autenticação separada para o mesmo usuário.

Este guia de início rápido ajuda você a se autenticar por meio do PlayFab OSS e a reutilizar essa autenticação com o plug-in do PlayFab SDK, para uma experiência de autenticação do usuário integrada.

## Pré-requisitos

* Certifique-se de integrar o PlayFab OSS como um plug-in no arquivo `<game>.build.cs`. No exemplo abaixo, criamos uma opção de alternância para permitir a integração e definimos uma definição para permitir a proteção com `#ifdef`.
  ```cs theme={null}
  // PlayFab OnlineSubsystem Plugin Settings.
  //
  // While the PlayFab OSS is integrated with the game at an engine level, we cannot directly access
  // PF OSS headers unless we integrate it as a plugin.
  //
  // `bOSSPlayFabAsPlugin` must be set to true to expose the PlayFab OSS headers directly to the game.
  bool bOSSPlayFabAsPlugin = false;
  if (bOSSPlayFabAsPlugin)
  {
      PublicDependencyModuleNames.AddRange(new string[] { "OnlineSubsystemPlayFab" });
      PublicDefinitions.Add("WITH_OSS_PLAYFAB=1");
  }
  ```

* Certifique-se de integrar o plug-in do PlayFab SDK no arquivo `<game>.build.cs`. No exemplo abaixo, criamos uma opção de alternância para permitir a integração e definimos uma definição para permitir a proteção com `#ifdef`.
  ```cs theme={null}
  // PlayFab SDK Plugin Settings.
  //
  // `bPlayFabPlugin` must be set to true to enable compilation and integration with the PlayFab
  // SDK Plugin.
  // Ensure that the PF SDK Plugin is installed via Engine plugin or as a local game plugin.
  bool bPlayFabPlugin = false;
  if (bPlayFabPlugin)
  {
      PrivateDependencyModuleNames.AddRange(new string[] { "PlayFab", "PlayFabCpp", "PlayFabCommon" });
      PublicDefinitions.Add("WITH_PLAYFAB_PLUGIN=1");
  }
  ```

* Depois de atualizar o arquivo `<game.build.cs>` (e sempre que atualizá-lo posteriormente), certifique-se de gerar novamente os arquivos de projeto do Visual Studio do seu jogo clicando com o botão direito do mouse no arquivo `.uproject` e selecionando `Generate Visual Studio Project Files`.

* O PlayFab OSS agora oferece um delegate público `AuthenticateUserComplete` que é disparado na conclusão do fluxo de autenticação de usuário do PlayFab OSS. Associe-se a esse delegate para recuperar os detalhes da sua autenticação no PlayFab OSS.
  ```cpp theme={null}
  /**
  * Delegate used on the completion of FOnlineIdentityPlayFab::AuthenticateUser().
  *
  * @param LocalUserNum the controller number of the associated user that made the request
  * @param bWasSuccessful true if authentication was successful, false if there was an error
  * @param PlatformUserIdStr user identifier returned from the service.
  * @param ErrorStr string representing the error condition
  */
  DECLARE_MULTICAST_DELEGATE_FourParams(FOnAuthenticateUserComplete, int32 /*LocalUserNum*/, bool /*bWasSuccessful*/, const FString& /*PlatformUserIdStr*/, const FString& /*ErrorStr*/);
  typedef FOnAuthenticateUserComplete::FDelegate FOnAuthenticateUserCompleteDelegate;
  ```

## Etapas

Você também pode ir direto para o [Exemplo de código completo](#exemplo-de-código-completo).

1. **Incluir os cabeçalhos corretos**
   ```cpp theme={null}
   #ifdef WITH_OSS_PLAYFAB
   #include "OnlineSubsystemPlayFab.h"
   #endif // WITH_OSS_PLAYFAB

   #ifdef WITH_PLAYFAB_PLUGIN
   #include "PlayFab.h"
   #include "PlayFabCommon.h"
   #include "Core/PlayFabClientDataModels.h"
   #endif // WITH_PLAYFAB_PLUGIN
   ```

2. **Recuperar o PlayFab OSS**
   ```cpp theme={null}
   FOnlineSubsystemPlayFab* PFOnlineSub = static_cast<FOnlineSubsystemPlayFab*>(IOnlineSubsystem::Get(TEXT("PLAYFAB")));
   ```

3. **Associar-se ao delegate `AuthenticateUserComplete`**

   ```cpp theme={null}
   const FOnlineIdentityPlayFabPtr PlayFabIdentityInterface = PFOnlineSub->GetIdentityInterfacePlayFab();
   PlayFabIdentityInterface->AddOnAuthenticateUserCompleteDelegate_Handle
   (
       0, // LocalUserNum
       FOnAuthenticateUserCompleteDelegate::CreateUObject(this, &UGameInstance::OnAuthenticateUserComplete)
   );
   ```

   As funções associadas a esse delegate devem ter a mesma assinatura do delegate. Por exemplo:

   ```cpp theme={null}
   void UGameInstance::OnAuthenticateUserComplete(int32 localUserNum, bool bWasSuccessful, const FString& platformUserIdStr, const FString& error)
   ```

   Você também pode associar uma lambda ao delegate. Por exemplo:

   ```cpp theme={null}
   // We don't pass the `FOnlineIdentityPlayFabPtr` pointer through the lambda capture since the original
   // local isn't guaranteed to live longer than the lambda and we want to avoid dangling references.
   //
   // You can retrieve `FOnlineIdentityPlayFabPtr` again inside the lambda.
   PlayFabIdentityInterface->AddOnAuthenticateUserCompleteDelegate_Handle
   (
       0, // LocalUserNum
       FOnAuthenticateUserCompleteDelegate::CreateLambda([this](int32 localUserNum, bool bWasSuccessful, const FString& platformUserIdStr, const FString& error)
       {
           // lambda execution
       });
   )
   ```

4. **Tratar o resultado da autenticação**: Na função associada ao delegate, trate o resultado da autenticação. Se a autenticação for bem-sucedida, recupere o usuário local autenticado por meio do `platformUserIdStr` do disparo do delegate. Em seguida, construa um `LoginResult` do PlayFab a partir do `LocalUser` do PlayFab OSS.
   ```cpp theme={null}
   void UGameInstance::OnAuthenticateUserComplete(int32 localUserNum, bool bWasSuccessful, const FString& platformUserIdStr, const FString& error)
   {
       if (!bWasSuccessful)
       {
           UE_LOG(LogOnlineGame, Error, TEXT("OSS PlayFab AuthenticateLocalUser Failed. Error: %s"), *error);
           return;
       }

       UE_LOG(LogOnlineGame, Display, TEXT("[%s] AuthenticateLocalUser Complete"), ANSI_TO_TCHAR(__FUNCTION__));

       FOnlineSubsystemPlayFab* PFOnlineSub = static_cast<FOnlineSubsystemPlayFab*>(IOnlineSubsystem::Get(TEXT("PLAYFAB")));
       const FOnlineIdentityPlayFabPtr PlayFabIdentityInterface = PFOnlineSub->GetIdentityInterfacePlayFab();

       if (PlayFabIdentityInterface)
       {
           if (const auto LocalUser = PlayFabIdentityInterface->GetPartyLocalUserFromPlatformIdString(platformUserIdStr))
           {
               // Setting PlayFab SDK Settings for future API calls
               auto& PFCommonModule = IPlayFabCommonModuleInterface::Get();
               PFCommonModule.SetClientSessionTicket(LocalUser->GetSessionTicket());
               PFCommonModule.SetEntityToken(LocalUser->GetEntityToken());

               // Create EntityKey
               auto LocalEntityKey = MakeShared<PlayFab::ClientModels::FEntityKey>();
               LocalEntityKey->Id = LocalUser->GetEntityId();
               LocalEntityKey->Type = LocalUser->GetEntityType();

               // Create EntityToken
               auto LocalEntityToken = MakeShared<PlayFab::ClientModels::FEntityTokenResponse>();
               LocalEntityToken->Entity = LocalEntityKey;
               LocalEntityToken->EntityToken = LocalUser->GetEntityToken();

               // Create LoginResult
               PlayFab::ClientModels::FLoginResult LoginResult;
               LoginResult.EntityToken = LocalEntityToken;
               LoginResult.LastLoginTime = LocalUser->GetEntityTokenUpdateTime();
               LoginResult.PlayFabId = LocalUser->GetPlayFabId();
               LoginResult.SessionTicket = LocalUser->GetSessionTicket();

               // With `LoginResult` populated, we can now use the PlayFab SDK Plugin APIs
               // however we wish. This state is considered "authenticated".
               //
               // This delegate signature functions does not return anything. You can pass `LoginResult`
               // out of this function however you wish.
               // 
               // Example psuedocode for a non-existent function that takes `LoginResult` as a parameter:
               // void UGameInstance::OnAPILoginSuccess(PlayFab::ClientModels::FLoginResult LoginResult);
           }
       }
   }
   ```

5. **Usar as APIs do plug-in do PlayFab SDK**: Com o `LoginResult` preenchido, agora você pode usar as APIs do plug-in do PlayFab SDK como quiser. Esse estado é considerado "autenticado".

## Exemplo de código completo

```cpp theme={null}
#ifdef WITH_OSS_PLAYFAB
#include "OnlineSubsystemPlayFab.h"
#endif // WITH_OSS_PLAYFAB

#ifdef WITH_PLAYFAB_PLUGIN
#include "PlayFab.h"
#include "PlayFabCommon.h"
#include "Core/PlayFabClientDataModels.h"
#endif // WITH_PLAYFAB_PLUGIN

...

void UGameInstance::Init()
{
    Super::Init();
    ...

    // This is an example scenario of integrating the PlayFab OnlineSubsystem with the
    // PlayFab SDK Plugin.
    //
    // In this scenario, you can authenticate via the PlayFab OSS,
    // and then re-use that authentication with the PlayFab SDK Plugin.
    // 
    // PF OSS offers a public `AuthenticateUserComplete` delegate that can be bound;
    // this delegate triggers on completion of the PF OSS user authentication flow.
    // 
    // Below is an example of a game binding to that delegate, retrieving the
    // authenticated local user via the `platformUserIdStr` from the delegate
    // trigger, and then constructing a PlayFab `LoginResult` from the PF OSS
    // `LocalUser.`
    // 
    // These definitions are defined in `<game>.build.cs`.
#if defined(WITH_OSS_PLAYFAB) && defined(WITH_PLAYFAB_PLUGIN)
    // Explicitly retrieve the PlayFab OSS - we can't assume it's the default OSS.
    FOnlineSubsystemPlayFab* PFOnlineSub = static_cast<FOnlineSubsystemPlayFab*>(IOnlineSubsystem::Get(TEXT("PLAYFAB")));

    UE_LOG(LogOnlineGame, Warning, TEXT("Retrieved PFOnlineSub"));

    if (PFOnlineSub)
    {
        const FOnlineIdentityPlayFabPtr PlayFabIdentityInterface = PFOnlineSub->GetIdentityInterfacePlayFab();

        PlayFabIdentityInterface->AddOnAuthenticateUserCompleteDelegate_Handle
        (
            0, // LocalUserNum
            FOnAuthenticateUserCompleteDelegate::CreateUObject(this, &UGameInstance::OnAuthenticateUserComplete)
        );
    }
    else
    {
        UE_LOG(LogOnlineGame, Error, TEXT("UGameInstance::Init: Unable to find OnlineSubsystemPlayFab"));
    }
#endif // WITH_OSS_PLAYFAB && WITH_PLAYFAB_PLUGIN

    ...
}

void UGameInstance::OnAuthenticateUserComplete(int32 localUserNum, bool bWasSuccessful, const FString& platformUserIdStr, const FString& error)
{
    if (!bWasSuccessful)
    {
        UE_LOG(LogOnlineGame, Error, TEXT("OSS PlayFab AuthenticateLocalUser Failed. Error: %s"), *error);
        return;
    }

    UE_LOG(LogOnlineGame, Display, TEXT("[%s] AuthenticateLocalUser Complete"), ANSI_TO_TCHAR(__FUNCTION__));

    FOnlineSubsystemPlayFab* PFOnlineSub = static_cast<FOnlineSubsystemPlayFab*>(IOnlineSubsystem::Get(TEXT("PLAYFAB")));
    const FOnlineIdentityPlayFabPtr PlayFabIdentityInterface = PFOnlineSub->GetIdentityInterfacePlayFab();

    if (PlayFabIdentityInterface)
    {
        if (const auto LocalUser = PlayFabIdentityInterface->GetPartyLocalUserFromPlatformIdString(platformUserIdStr))
        {
            // Setting PlayFab SDK Settings for future API calls
            auto& PFCommonModule = IPlayFabCommonModuleInterface::Get();
            PFCommonModule.SetClientSessionTicket(LocalUser->GetSessionTicket());
            PFCommonModule.SetEntityToken(LocalUser->GetEntityToken());

            // Create EntityKey
            auto LocalEntityKey = MakeShared<PlayFab::ClientModels::FEntityKey>();
            LocalEntityKey->Id = LocalUser->GetEntityId();
            LocalEntityKey->Type = LocalUser->GetEntityType();

            // Create EntityToken
            auto LocalEntityToken = MakeShared<PlayFab::ClientModels::FEntityTokenResponse>();
            LocalEntityToken->Entity = LocalEntityKey;
            LocalEntityToken->EntityToken = LocalUser->GetEntityToken();

            // Create LoginResult
            PlayFab::ClientModels::FLoginResult LoginResult;
            LoginResult.EntityToken = LocalEntityToken;
            LoginResult.LastLoginTime = LocalUser->GetEntityTokenUpdateTime();
            LoginResult.PlayFabId = LocalUser->GetPlayFabId();
            LoginResult.SessionTicket = LocalUser->GetSessionTicket();

            // With `LoginResult` populated, we can now use the PlayFab SDK Plugin APIs
            // however we wish. This state is considered "authenticated".
            //
            // This delegate signature functions does not return anything. You can pass `LoginResult`
            // out of this function however you wish.
            // 
            // Example psuedocode for a non-existent function that takes `LoginResult` as a parameter:
            // void UGameInstance::OnAPILoginSuccess(PlayFab::ClientModels::FLoginResult LoginResult);
        }
    }
}
```


## Related topics

- [Visão geral do plug-in PlayFab Unreal GSDK](/pt-BR/services/playfab/multiplayer/servers/server-sdks/unreal-gsdk/index.md)
- [Início rápido da Unreal Engine](/pt-BR/services/playfab/sdks/unreal/quickstart.md)
- [Notas de versão do PlayFab OnlineSubsystem para Unreal Engine](/pt-BR/services/playfab/multiplayer/networking/unreal-release-notes.md)
- [Visão geral do PlayFab para Unreal Engine](/pt-BR/services/playfab/sdks/unified-unreal/overview.md)
- [Obtendo as bibliotecas do PlayFab Party e do Multiplayer](/pt-BR/services/playfab/multiplayer/networking/party-unreal-engine-oss-obtaining-playfab-party-libraries.md)
