---
title: "在 Capacitor SDK 中检查订阅状态"
description: "在 Adapty 中跟踪和管理用户订阅状态，以提高 Capacitor 应用中的客户留存率。"
---

使用 Adapty，跟踪订阅状态变得非常简单。您无需在代码中手动插入产品 ID，只需检查活跃的[访问等级](access-level)，即可轻松确认用户的订阅状态。

<details>
   <summary>在开始检查订阅状态之前（点击展开）</summary>

- 对于 iOS，请设置 [App Store 服务器通知](enable-app-store-server-notifications)
- 对于 Android，请设置[实时开发者通知（RTDN）](enable-real-time-developer-notifications-rtdn)
</details>

## 访问等级与 AdaptyProfile 对象 \{#access-level-and-the-adaptyprofile-object\}

访问等级是 [AdaptyProfile](https://capacitor.adapty.io/interfaces/adaptyprofile) 对象的属性。我们建议在应用启动时（例如[识别用户](capacitor-identifying-users#setting-customer-user-id-on-configuration)时）获取用户画像，并在发生变更时及时更新。这样，您就可以直接使用用户画像对象，而无需反复请求。

如需在用户画像更新时收到通知，请按照下方[监听用户画像更新（包括访问等级）](capacitor-listen-subscription-changes)章节中的说明监听用户画像变更。

:::tip

想了解 Adapty SDK 如何集成到移动应用中的真实示例？请查看我们的[示例应用](sample-apps)，其中展示了完整的配置过程，包括显示付费墙、完成购买以及其他基本功能。

:::

## 从服务器获取访问等级 \{#retrieving-the-access-level-from-the-server\}

要从服务器获取访问等级，请使用 `.getProfile()` 方法：

```typescript showLineNumbers

try {
  const profile = await adapty.getProfile();
  console.log('Profile retrieved successfully');
} catch (error) {
  console.error('Failed to get profile:', error);
}
```

响应参数：

| 参数 | 描述 |
| --------- |----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| **profile**   | 一个 [AdaptyProfile](https://capacitor.adapty.io/interfaces/adaptyprofile) 对象。通常，您只需检查用户画像的访问等级状态，即可判断用户是否拥有应用的高级权限。`.getProfile` 方法始终会尝试查询 API，因此能提供最新的结果。如果由于某种原因（例如无网络连接）Adapty SDK 无法从服务器获取信息，则会返回缓存中的数据。此外，Adapty SDK 会定期更新 `AdaptyProfile` 缓存，以尽可能保持信息的最新状态。 |

`.getProfile()` 方法会返回用户画像，您可以从中获取访问等级状态。每个应用可以拥有多个访问等级。例如，如果您有一个新闻应用，并独立出售不同主题的订阅，可以创建"sports"和"science"两个访问等级。但大多数情况下，您只需要一个访问等级，此时使用默认的"premium"访问等级即可。

以下是检查默认"premium"访问等级的示例：

```typescript showLineNumbers

try {
  const profile = await adapty.getProfile();
  
  const isActive = profile.accessLevels['premium']?.isActive;
  if (isActive) {
    // Grant access to premium features
    console.log('User has premium access');
  } else {
    console.log('User does not have premium access');
  }
} catch (error) {
  console.error('Failed to check subscription status:', error);
}
```

### 监听订阅状态更新 \{#listening-for-subscription-status-updates\}

每当用户的订阅发生变化时，Adapty 都会触发一个事件。

要接收来自 Adapty 的消息，您需要进行一些额外配置：

```typescript showLineNumbers

// Create an "onLatestProfileLoad" event listener
adapty.addListener('onLatestProfileLoad', (data) => {
  const profile = data.profile;
  const isActive = profile.accessLevels['premium']?.isActive;
  
  if (isActive) {
    console.log('Subscription status updated: User has premium access');
  } else {
    console.log('Subscription status updated: User does not have premium access');
  }
});
```

Adapty 也会在应用启动时触发一个事件，此时传递的是缓存中的订阅状态。

### 订阅状态缓存 \{#subscription-status-cache\}

Adapty SDK 中实现的缓存会存储用户画像的订阅状态。这意味着即使服务器不可用，也可以通过访问缓存数据来获取用户画像的订阅状态信息。

但需要注意的是，无法直接从缓存中请求数据。SDK 会每分钟定期查询服务器，检查是否有与用户画像相关的更新或变更。如果存在任何修改（例如新的交易记录或其他更新），这些变更将被同步到缓存数据中，以保持其与服务器的一致性。