借助 Adapty,跟踪订阅状态变得轻而易举。您无需在代码中手动插入产品 ID,只需检查用户是否拥有有效的访问等级,即可轻松确认其订阅状态。
在开始检查订阅状态之前,请先配置实时开发者通知 (RTDN)。
访问等级与 AdaptyProfile 对象
访问等级是 AdaptyProfile 对象的属性。我们建议在应用启动时(例如识别用户时)获取用户画像,并在发生变更时及时更新。这样,您就可以直接使用用户画像对象,而无需反复请求。
若要在用户画像更新时收到通知,请按照下方监听用户画像更新(包括访问等级变更)部分的说明,监听用户画像变更事件。
想了解 Adapty SDK 如何集成到移动应用中的真实示例?请查看我们的示例应用,其中展示了完整的配置过程,包括显示付费墙、完成购买以及其他基本功能。
从服务器获取访问等级
使用 .getProfile() 方法从服务器获取访问等级:
Adapty.getProfile { result ->
when (result) {
is AdaptyResult.Success -> {
val profile = result.value
// check the access
}
is AdaptyResult.Error -> {
val error = result.error
// handle the error
}
}
}
Adapty.getProfile(result -> {
if (result instanceof AdaptyResult.Success) {
AdaptyProfile profile = ((AdaptyResult.Success<AdaptyProfile>) result).getValue();
// check the access
} else if (result instanceof AdaptyResult.Error) {
AdaptyError error = ((AdaptyResult.Error) result).getError();
// handle the error
}
});
响应参数:
| 参数 | 说明 |
|---|
| Profile | AdaptyProfile 对象。通常情况下,您只需检查用户画像的访问等级状态,即可判断用户是否拥有应用的高级访问权限。 .getProfile 方法始终尝试查询 API,因此能提供最新的结果。如果由于某些原因(例如无网络连接)导致 Adapty SDK 无法从服务器获取信息,则会返回缓存中的数据。此外,Adapty SDK 会定期更新 AdaptyProfile 缓存,以尽可能保持信息的实时性。
|
.getProfile() 方法会返回用户画像,您可以从中获取访问等级状态。每个应用可以拥有多个访问等级。例如,如果您有一个新闻应用并独立销售不同主题的订阅,可以创建”sports”和”science”等访问等级。但在大多数情况下,您只需要一个访问等级,此时直接使用默认的”premium”访问等级即可。
以下是检查默认”premium”访问等级的示例:
Adapty.getProfile { result ->
when (result) {
is AdaptyResult.Success -> {
val profile = result.value
if (profile.accessLevels["premium"]?.isActive == true) {
// grant access to premium features
}
}
is AdaptyResult.Error -> {
val error = result.error
// handle the error
}
}
}
Adapty.getProfile(result -> {
if (result instanceof AdaptyResult.Success) {
AdaptyProfile profile = ((AdaptyResult.Success<AdaptyProfile>) result).getValue();
AdaptyProfile.AccessLevel premium = profile.getAccessLevels().get("premium");
if (premium != null && premium.isActive()) {
// grant access to premium features
}
} else if (result instanceof AdaptyResult.Error) {
AdaptyError error = ((AdaptyResult.Error) result).getError();
// handle the error
}
});
监听订阅状态更新
每当用户的订阅发生变化,Adapty 都会触发一个事件。
要接收来自 Adapty 的消息,您需要进行一些额外配置:
Adapty.setOnProfileUpdatedListener { profile ->
// handle any changes to subscription state
}
Adapty.setOnProfileUpdatedListener(profile -> {
// handle any changes to subscription state
});
Adapty 也会在应用启动时触发一个事件,此时将传递缓存的订阅状态。
订阅状态缓存
Adapty SDK 中实现的缓存会存储用户画像的订阅状态。这意味着即使服务器不可用,也可以访问缓存数据以获取用户画像的订阅状态信息。
但请注意,目前无法直接从缓存请求数据。SDK 会每分钟定期查询服务器,以检查与用户画像相关的任何更新或变更。如有任何修改(例如新的交易或其他更新),这些变更将被同步到缓存数据中,以保持与服务器的一致性。