---
title: "在 Capacitor SDK 中检查订阅状态"
description: "了解如何在 Capacitor 应用中通过 Adapty 检查订阅状态。"
---

要判断用户是否可以访问付费内容或是否需要显示付费墙，您需要检查用户画像中的[访问等级](access-level)。

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

## 获取订阅状态 \{#get-subscription-status\}

当您决定是否向用户显示付费墙或付费内容时，需要检查其用户画像中的[访问等级](access-level)。您有两种方式：

- 如果需要立即获取最新的用户画像数据（例如应用启动时）或想强制更新，请调用 `getProfile`。
- 设置**自动用户画像更新**，以保留一份本地副本，该副本会在订阅状态发生变化时自动刷新。

### 获取用户画像 \{#get-profile\}

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

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

### 监听订阅更新 \{#listen-to-subscription-updates\}

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

1. 使用 `adapty.addListener('onLatestProfileLoad')` 监听用户画像变化——每当用户的订阅状态发生变化时，Adapty 都会自动调用此方法。
2. 在该方法被调用时存储更新后的用户画像数据，以便在整个应用中使用，而无需发起额外的网络请求。

```typescript showLineNumbers
class SubscriptionManager {
  private currentProfile: any = null;
  
  constructor() {
    // Listen for profile updates
    adapty.addListener('onLatestProfileLoad', (data) => {
      this.currentProfile = data.profile;
      // Update UI, unlock content, etc.
    });
  }
  
  // Use stored profile instead of calling getProfile()
  hasAccess(): boolean {
    return this.currentProfile?.accessLevels?.['YOUR_ACCESS_LEVEL']?.isActive ?? false;
  }
}
```

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

## 将用户画像与付费墙逻辑关联 \{#connect-profile-with-paywall-logic\}

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

```typescript showLineNumbers
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 getAccessLevel = () => {
  return profile?.accessLevels?.['YOUR_ACCESS_LEVEL'];
};

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);
  }
};
```

## 后续步骤 \{#next-steps\}

现在您已了解如何追踪订阅状态，接下来请学习如何[管理用户画像](capacitor-quickstart-identify)，以确保用户可以访问其已付费的内容。