处理令牌过期
PlayFab 服务 SDK 会自动尝试处理 SDK 中的重新登录和令牌刷新。 当 PlayFab 实体令牌过期时,SDK 会检测失败并试图使用最初提供给登录请求的图柄或令牌来获取新的实体令牌。 如果这次全新登录成功,则 SDK 会自动重试最初失败的调用。 此外,初始登录调用返回的“PFEntityHandle”继续有效。
自动刷新失败
自动令牌刷新可能会失败。 此功能失败的原因可能是最初提供给登录请求的图柄或令牌不再有效。 为解决此场景,游戏可以注册回叫来提供新的图柄或令牌并尝试重新登录。 使用 PFEntityRegisterTokenExpiredEventHandler 注册回调,并使用 PFAuthenticationReLoginWith*Async 提供新的图柄或令牌并尝试重新登录。
PFRegistrationToken registrationTokenExpired{};
hr = PFEntityRegisterTokenExpiredEventHandler(nullptr, nullptr, [](void* ctx, PFEntityKey const* entityKey)
{
PFAuthenticationLoginWithXUserRequest request{};
request.createAccount = true;
request.user = user; // An XUserHandle obtained from XUserAddAsync
XAsyncBlock async{};
HRESULT hr = PFAuthenticationReLoginWithXUserAsync(GlobalState()->entityHandle, &request, &async); // This assumes the entity handle was stored in the game's global state
hr = XAsyncGetStatus(&async, true); // This is doing a blocking wait for completion, but you can use the XAsyncBlock to set a callback instead for async style usage
// After login we could potentially get back a new player entity with a new entity key
PFEntityKey const* pEntityKey{};
std::vector<char> entityKeyBuffer;
size_t size{};
hr = PFEntityGetEntityKeySize(GlobalState()->entityHandle, &size); // Add your own error handling when FAILED(hr) == true
entityKeyBuffer.resize(size);
hr = PFEntityGetEntityKey(GlobalState()->entityHandle, entityKeyBuffer.size(), entityKeyBuffer.data(), &pEntityKey, nullptr);
}, ®istrationTokenExpired);
透明刷新
如果希望游戏知道 SDK 何时自动刷新玩家的实体令牌,可以注册回调。
PFRegistrationToken registrationTokenRefreshed{};
hr = PFEntityRegisterTokenRefreshedEventHandler(nullptr, nullptr, [](void* ctx, PFEntityKey const* entityKey, const PFEntityToken* newToken)
{
// Perform any logging or other desired actions on token refresh
}, ®istrationTokenRefreshed);
注销处理程序
关闭 PlayFab 或想要停止接收令牌过期和刷新回调时,请调用相应的注销函数。
PFEntityUnregisterTokenExpiredEventHandler(registrationTokenExpired);
PFEntityUnregisterTokenRefreshedEventHandler(registrationTokenRefreshed);