在 React Native SDK 中检查订阅状态

要决定用户是否可以访问付费内容或查看付费墙,您需要检查用户画像中的访问等级

本文介绍如何访问用户画像状态,以决定向用户展示什么内容——是显示付费墙还是授予付费功能的访问权限。

获取订阅状态

当您决定是否向用户显示付费墙或付费内容时,需要检查其用户画像中的访问等级。您有两种方式:

  • 如果需要立即获取最新的用户画像数据(例如在应用启动时)或希望强制更新,可调用 getProfile
  • 设置自动用户画像更新,以在订阅状态发生变化时自动刷新本地副本。

获取用户画像

获取订阅状态最简单的方式是使用 getProfile 方法访问用户画像:

try {
    const profile = await adapty.getProfile();
} catch (error) {
  // handle the error
}

监听订阅更新

要在应用中自动接收用户画像更新:

  1. 使用 adapty.addEventListener('onLatestProfileLoad') 监听用户画像变化——每当用户的订阅状态发生变化时,Adapty 会自动调用此方法。
  2. 当该方法被调用时,存储更新后的用户画像数据,以便在整个应用中使用,无需额外发起网络请求。
class SubscriptionManager {
    private currentProfile: any = null;
    
    constructor() {
        // Listen for profile updates
        adapty.addEventListener('onLatestProfileLoad', (profile) => {
            this.currentProfile = profile;
            // Update UI, unlock content, etc.
        });
    }
    
    // Use stored profile instead of calling getProfile()
    hasAccess(): boolean {
        return this.currentProfile?.accessLevels?.['premium']?.isActive ?? false;
    }
}

当您的应用启动时,Adapty 会自动调用 onLatestProfileLoad 事件监听器,即使设备处于离线状态也能提供缓存的订阅数据。

将用户画像与付费墙逻辑关联

当您需要立即决定是否显示付费墙或授予付费功能访问权限时,可以直接检查用户的用户画像。这种方式适用于以下场景:应用启动、进入付费专区,或在展示特定内容之前。

const checkAccessLevel = async () => {
  try {
    const profile = await adapty.getProfile();
    return profile.accessLevels['YOUR_ACCESS_LEVEL']?.isActive === true;
  } catch (error) {
    console.warn('Error checking access level:', error);
    return false; // Show paywall if access check fails
  }
};

const initializePaywall = async () => {
  try {
    await loadPaywall();
    
    const hasAccess = await checkAccessLevel();
    if (!hasAccess) {
      // Show paywall if no access
    }
  } catch (error) {
    console.warn('Error initializing paywall:', error);
  }
};

后续步骤

现在您已了解如何跟踪订阅状态,接下来请学习如何使用用户画像,以确保用户能够访问他们已付费的内容。