在 Unity SDK 中检查订阅状态
要判断用户是否可以访问付费内容或查看付费墙,您需要在用户画像中检查其访问等级。
本文介绍如何访问用户画像状态,以决定向用户展示什么内容——是显示付费墙还是授予付费功能的访问权限。
获取订阅状态
当您需要决定是否向用户显示付费墙或付费内容时,需要检查其用户画像中的访问等级。您有两种选择:
- 如果需要立即获取最新的用户画像数据(例如在应用启动时)或希望强制更新,请调用
GetProfile。 - 设置自动用户画像更新,以在订阅状态发生变化时自动刷新本地副本。
获取用户画像
获取订阅状态最简单的方法是使用 GetProfile 方法访问用户画像:
Adapty.GetProfile((profile, error) => {
if (error != null) {
// handle the error
return;
}
// check the access
});
监听订阅更新
要在应用中自动接收用户画像更新:
- 继承
AdaptyEventListener并实现OnLoadLatestProfile方法——每当用户的订阅状态发生变化时,Adapty 会自动调用此方法。 - 在该方法被调用时保存最新的用户画像数据,这样就可以在应用各处直接使用,无需额外发起网络请求。
Note
在 SDK 4.1 中,监听器接口遵循 C# I-前缀命名规范——请实现 IAdaptyEventListener 而非 AdaptyEventListener——同时该接口还新增了一个方法 OnReceivePromotedPurchase。详情请参阅迁移指南。
public class SubscriptionManager : MonoBehaviour, AdaptyEventListener {
private AdaptyProfile currentProfile;
void Start() {
// Register this object as an Adapty event listener
Adapty.SetEventListener(this);
}
// Store the profile when it updates
public void OnLoadLatestProfile(AdaptyProfile profile) {
currentProfile = profile;
// Update UI, unlock content, etc.
}
public void OnInstallationDetailsSuccess(AdaptyInstallationDetails details) { }
public void OnInstallationDetailsFail(AdaptyError error) { }
// Use stored profile instead of calling getProfile()
public bool HasAccess() {
if (currentProfile?.AccessLevels != null &&
currentProfile.AccessLevels.ContainsKey("premium")) {
return currentProfile.AccessLevels["premium"].IsActive;
}
return false;
}
}
Note
Adapty 会在应用启动时自动调用 OnLoadLatestProfile,即使设备处于离线状态,也能提供缓存的订阅数据。
将用户画像与付费墙逻辑关联
当你需要立即决定是否显示付费墙或授予付费功能访问权限时,可以直接检查用户的用户画像。这种方式适用于应用启动、进入高级功能区域或展示特定内容之前等场景。
private void CheckAccessLevel()
{
Adapty.GetProfile((profile, error) => {
if (error != null) {
Debug.LogError("Error checking access level: " + error.Message);
// Show paywall if access check fails
return;
}
if (!profile.AccessLevels.TryGetValue("YOUR_ACCESS_LEVEL", out var accessLevel)
|| !accessLevel.IsActive) {
// Show paywall if no access
}
});
}
private void InitializePaywall()
{
LoadPaywall();
CheckAccessLevel();
}
后续步骤
现在您已了解如何追踪订阅状态,接下来请学习如何使用用户画像,以确保用户能够访问其已付费的内容。