rc-revenuecat-api-quick-reference

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

RevenueCat API Quick Reference

RevenueCat API快速参考

Phase 0: Intent

阶段0:用途

Use this skill when you need a fast lookup of a RevenueCat API surface while writing Android code or server logic. Typical questions you answer from here:
  • Which builder option controls a given
    Purchases.configure
    behavior?
  • What is the return type and signature of
    awaitPurchase
    ,
    awaitOfferings
    ,
    awaitCustomerInfo
    ,
    awaitRestore
    ,
    awaitLogIn
    ,
    awaitLogOut
    ?
  • How do I read offering, package, product, entitlement fields?
  • Which
    PurchasesErrorCode
    should I branch on?
  • Which listener callback do I register for customer info updates?
Do not use this skill as a deep tutorial. Reach for the feature-specific skills (purchase flow, configuring the SDK, error handling, subscription states) when you need step-by-step guidance or design rationale.
当你编写Android代码或服务器逻辑时,需要快速查阅RevenueCat API接口时,可使用此技能。通常可从中解答以下问题:
  • 哪个构建器选项控制指定的
    Purchases.configure
    行为?
  • awaitPurchase
    awaitOfferings
    awaitCustomerInfo
    awaitRestore
    awaitLogIn
    awaitLogOut
    的返回类型和签名是什么?
  • 如何读取offering、package、product、entitlement字段?
  • 应该针对哪个
    PurchasesErrorCode
    进行分支处理?
  • 需要注册哪个监听器回调来接收客户信息更新?
请勿将此技能用作深度教程。当你需要分步指导或设计原理说明时,请使用特定功能的技能(如购买流程、SDK配置、错误处理、订阅状态)。

Phase 1: Locate

阶段1:定位

Decide SDK surface vs REST surface before you search the tables.
Route to the SDK (client side, Android app code):
  • Code runs inside the Android app, in an
    Activity
    ,
    ViewModel
    , or background worker bundled with your app.
  • You need to launch a purchase, restore purchases, read cached
    CustomerInfo
    , fetch
    Offerings
    , identify or log out a user, or listen for updates.
  • You want entitlement gating in the UI.
Route to the REST API (server side):
  • Code runs on your backend, in a webhook handler, in an admin tool, or in a scheduled job.
  • You need to grant or revoke a promotional entitlement, override a subscription, look up a subscriber from another service, refund, or deliver events to another system.
  • You are integrating with a system that cannot embed the SDK.
The tables in this skill cover the Android SDK 10.x surface from appendix A verbatim. For REST endpoint paths, authentication, and payloads, see the full appendix on revenuecat.com together with the backend and webhooks skills, and treat this file as the SDK index.
在查阅表格前,先确定是SDK接口还是REST接口。
选择SDK(客户端,Android应用代码)的场景:
  • 代码运行在Android应用内部,如
    Activity
    ViewModel
    或与应用捆绑的后台工作器中。
  • 需要发起购买、恢复购买、读取缓存的
    CustomerInfo
    、获取
    Offerings
    、识别用户或登出用户,或监听更新。
  • 需要在UI中实现权限限制。
选择REST API(服务端)的场景:
  • 代码运行在你的后端、Webhook处理器、管理工具或定时任务中。
  • 需要授予或撤销促销权限、覆盖订阅、从其他服务查找订阅者、退款,或向其他系统传递事件。
  • 正在与无法嵌入SDK的系统集成。
本技能中的表格完全照搬附录A中的Android SDK 10.x接口内容。如需REST端点路径、认证和负载信息,请查看revenuecat.com上的完整附录,同时结合后端和Webhook技能,将本文件视为SDK索引。

Phase 2: Reference Tables

阶段2:参考表格

SDK Initialization

SDK初始化

kotlin
// Minimum setup
Purchases.configure(
    PurchasesConfiguration.Builder(context, "api_key").build()
)

// Full options
Purchases.configure(
    PurchasesConfiguration.Builder(context, "api_key")
        .appUserID("user_id")                    // null for anonymous
        .showInAppMessagesAutomatically(true)    // default: true
        .purchasesAreCompletedBy(PurchasesAreCompletedBy.REVENUECAT) // default
        .entitlementVerificationMode(EntitlementVerificationMode.INFORMATIONAL)
        .diagnosticsEnabled(false)               // default: false
        .pendingTransactionsForPrepaidPlansEnabled(false) // default: false
        .build()
)

Purchases.logLevel = LogLevel.DEBUG // before configure()
kotlin
// 最小化配置
Purchases.configure(
    PurchasesConfiguration.Builder(context, "api_key").build()
)

// 完整配置选项
Purchases.configure(
    PurchasesConfiguration.Builder(context, "api_key")
        .appUserID("user_id")                    // 匿名用户传null
        .showInAppMessagesAutomatically(true)    // 默认值:true
        .purchasesAreCompletedBy(PurchasesAreCompletedBy.REVENUECAT) // 默认值
        .entitlementVerificationMode(EntitlementVerificationMode.INFORMATIONAL)
        .diagnosticsEnabled(false)               // 默认值:false
        .pendingTransactionsForPrepaidPlansEnabled(false) // 默认值:false
        .build()
)

Purchases.logLevel = LogLevel.DEBUG // 需在configure()之前设置

Core Operations (Coroutine)

核心操作(协程)

kotlin
// Fetch offerings
val offerings: Offerings = Purchases.sharedInstance.awaitOfferings()

// Fetch specific products
val products: List<StoreProduct> = Purchases.sharedInstance.awaitGetProducts(
    listOf("product_id"),
    type = ProductType.INAPP // or SUBS, or null for all
)
kotlin
// Purchase
val result: PurchaseResult = Purchases.sharedInstance.awaitPurchase(
    PurchaseParams.Builder(activity, packageOrStoreProductOrSubscriptionOption).build()
)

// Purchase upgrade/downgrade
val result = Purchases.sharedInstance.awaitPurchase(
    PurchaseParams.Builder(activity, newPackage)
        .oldProductId("old_product_id")
        .googleReplacementMode(GoogleReplacementMode.WITH_TIME_PRORATION)
        .build()
)
kotlin
// Get customer info
val customerInfo: CustomerInfo = Purchases.sharedInstance.awaitCustomerInfo()
val fresh: CustomerInfo = Purchases.sharedInstance.awaitCustomerInfo(
    fetchPolicy = CacheFetchPolicy.FETCH_CURRENT
)

// Restore
val customerInfo: CustomerInfo = Purchases.sharedInstance.awaitRestore()

// Log in / log out
val loginResult: LogInResult = Purchases.sharedInstance.awaitLogIn("user_id")
// loginResult.customerInfo, loginResult.created (Boolean)
val customerInfo: CustomerInfo = Purchases.sharedInstance.awaitLogOut()
kotlin
// 获取offerings
val offerings: Offerings = Purchases.sharedInstance.awaitOfferings()

// 获取指定产品
val products: List<StoreProduct> = Purchases.sharedInstance.awaitGetProducts(
    listOf("product_id"),
    type = ProductType.INAPP // 或SUBS,传null则获取全部
)
kotlin
// 购买
val result: PurchaseResult = Purchases.sharedInstance.awaitPurchase(
    PurchaseParams.Builder(activity, packageOrStoreProductOrSubscriptionOption).build()
)

// 购买升级/降级
val result = Purchases.sharedInstance.awaitPurchase(
    PurchaseParams.Builder(activity, newPackage)
        .oldProductId("old_product_id")
        .googleReplacementMode(GoogleReplacementMode.WITH_TIME_PRORATION)
        .build()
)
kotlin
// 获取客户信息
val customerInfo: CustomerInfo = Purchases.sharedInstance.awaitCustomerInfo()
val fresh: CustomerInfo = Purchases.sharedInstance.awaitCustomerInfo(
    fetchPolicy = CacheFetchPolicy.FETCH_CURRENT
)

// 恢复购买
val customerInfo: CustomerInfo = Purchases.sharedInstance.awaitRestore()

// 登录/登出
val loginResult: LogInResult = Purchases.sharedInstance.awaitLogIn("user_id")
// loginResult.customerInfo, loginResult.created (Boolean)
val customerInfo: CustomerInfo = Purchases.sharedInstance.awaitLogOut()

Offerings Structure

Offerings结构

kotlin
val offerings: Offerings
offerings.current          // current Offering
offerings.all              // Map<String, Offering>
offerings["my_offering"]   // by identifier
offerings.getCurrentOfferingForPlacement("placement_id") // targeting
kotlin
val offering: Offering
offering.identifier
offering.monthly           // Package? (shortcut)
offering.annual            // Package?
offering.weekly            // Package?
offering.availablePackages // List<Package>
offering.metadata          // Map<String, Any>
kotlin
val pkg: Package
pkg.identifier             // "$rc_monthly", "$rc_annual", custom
pkg.packageType            // PackageType enum
pkg.product                // StoreProduct
pkg.webCheckoutURL         // URL? (RevenueCat web billing)
kotlin
val product: StoreProduct
product.productId
product.title
product.description
product.price.formatted    // "$4.99"
product.price.amountMicros
product.price.currencyCode
product.period             // Period? (null for INAPP); use period.iso8601 for "P1M", "P1Y", etc.
product.subscriptionOptions // List<SubscriptionOption>? (null for INAPP)
product.defaultOption       // SubscriptionOption? best available offer
kotlin
val offerings: Offerings
offerings.current          // 当前Offering
offerings.all              // Map<String, Offering>
offerings["my_offering"]   // 通过标识符获取
offerings.getCurrentOfferingForPlacement("placement_id") // 定向获取
kotlin
val offering: Offering
offering.identifier
offering.monthly           // Package?(快捷方式)
offering.annual            // Package?
offering.weekly            // Package?
offering.availablePackages // List<Package>
offering.metadata          // Map<String, Any>
kotlin
val pkg: Package
pkg.identifier             // "$rc_monthly", "$rc_annual", 自定义值
pkg.packageType            // PackageType枚举
pkg.product                // StoreProduct
pkg.webCheckoutURL         // URL?(RevenueCat网页计费)
kotlin
val product: StoreProduct
product.productId
product.title
product.description
product.price.formatted    // "$4.99"
product.price.amountMicros
product.price.currencyCode
product.period             // Period?(INAPP产品为null);使用period.iso8601获取"P1M"、"P1Y"等值
product.subscriptionOptions // List<SubscriptionOption>?(INAPP产品为null)
product.defaultOption       // SubscriptionOption? 最优可用优惠

Entitlements

权限(Entitlements)

kotlin
val customerInfo: CustomerInfo
customerInfo.entitlements.active         // Map<String, EntitlementInfo> (active only)
customerInfo.entitlements.all            // Map<String, EntitlementInfo> (all)
customerInfo.entitlements["pro_access"]  // EntitlementInfo?
customerInfo.activeSubscriptions         // Set<String> of "productId:basePlanId"
customerInfo.nonSubscriptionTransactions // List<Transaction>
customerInfo.managementURL               // Uri? to Play Store management
kotlin
val entitlement: EntitlementInfo
entitlement.isActive                     // Boolean, the main access gate
entitlement.willRenew                    // false if canceled
entitlement.expirationDate               // Date? (null for lifetime)
entitlement.periodType                   // NORMAL, TRIAL, INTRO, PREPAID
entitlement.billingIssueDetectedAt       // Date? (non-null = grace/hold)
entitlement.unsubscribeDetectedAt        // Date? (non-null = canceled)
entitlement.store                        // PLAY_STORE, APP_STORE, etc.
entitlement.productIdentifier            // subscription product ID
entitlement.productPlanIdentifier        // base plan ID (Google only)
entitlement.verification                 // VerificationResult
kotlin
val customerInfo: CustomerInfo
customerInfo.entitlements.active         // Map<String, EntitlementInfo>(仅活跃权限)
customerInfo.entitlements.all            // Map<String, EntitlementInfo>(全部权限)
customerInfo.entitlements["pro_access"]  // EntitlementInfo?
customerInfo.activeSubscriptions         // "productId:basePlanId"的Set<String>
customerInfo.nonSubscriptionTransactions // List<Transaction>
customerInfo.managementURL               // Uri? 跳转至Play Store管理页面
kotlin
val entitlement: EntitlementInfo
entitlement.isActive                     // Boolean,主要的权限访问开关
entitlement.willRenew                    // 取消订阅则为false
entitlement.expirationDate               // Date?(终身权限为null)
entitlement.periodType                   // NORMAL、TRIAL、INTRO、PREPAID
entitlement.billingIssueDetectedAt       // Date?(非null表示处于宽限期/暂停状态)
entitlement.unsubscribeDetectedAt        // Date?(非null表示已取消订阅)
entitlement.store                        // PLAY_STORE、APP_STORE等
entitlement.productIdentifier            // 订阅产品ID
entitlement.productPlanIdentifier        // 基础方案ID(仅Google)
entitlement.verification                 // VerificationResult

Error Handling

错误处理

kotlin
// Purchase errors
try {
    Purchases.sharedInstance.awaitPurchase(params)
} catch (e: PurchasesTransactionException) {
    e.userCancelled     // Boolean
    e.error.code        // PurchasesErrorCode
    e.error.message     // description string
}

// Other errors
try {
    Purchases.sharedInstance.awaitOfferings()
} catch (e: PurchasesException) {
    e.error.code        // PurchasesErrorCode
}
kotlin
// Key error codes
PurchasesErrorCode.PurchaseCancelledError
PurchasesErrorCode.ProductAlreadyPurchasedError
PurchasesErrorCode.PaymentPendingError
PurchasesErrorCode.NetworkError
PurchasesErrorCode.StoreProblemError
PurchasesErrorCode.IneligibleError
PurchasesErrorCode.ConfigurationError
kotlin
// 购买错误
try {
    Purchases.sharedInstance.awaitPurchase(params)
} catch (e: PurchasesTransactionException) {
    e.userCancelled     // Boolean
    e.error.code        // PurchasesErrorCode
    e.error.message     // 描述字符串
}

// 其他错误
try {
    Purchases.sharedInstance.awaitOfferings()
} catch (e: PurchasesException) {
    e.error.code        // PurchasesErrorCode
}
kotlin
// 关键错误码
PurchasesErrorCode.PurchaseCancelledError
PurchasesErrorCode.ProductAlreadyPurchasedError
PurchasesErrorCode.PaymentPendingError
PurchasesErrorCode.NetworkError
PurchasesErrorCode.StoreProblemError
PurchasesErrorCode.IneligibleError
PurchasesErrorCode.ConfigurationError

Listeners

监听器

kotlin
// CustomerInfo updates
Purchases.sharedInstance.updatedCustomerInfoListener =
    UpdatedCustomerInfoListener { customerInfo -> }

// Show in-app messages manually
Purchases.sharedInstance.showInAppMessagesIfNeeded(activity)
kotlin
// 客户信息更新
Purchases.sharedInstance.updatedCustomerInfoListener =
    UpdatedCustomerInfoListener { customerInfo -> }

// 手动显示应用内消息
Purchases.sharedInstance.showInAppMessagesIfNeeded(activity)

Phase 3: Typical Snippets

阶段3:典型代码片段

Gate a feature on an entitlement.
kotlin
val info = Purchases.sharedInstance.awaitCustomerInfo()
val hasPro = info.entitlements["pro_access"]?.isActive == true
if (hasPro) unlockFeature() else showPaywall()
Buy the monthly package from the current offering.
kotlin
val current = Purchases.sharedInstance.awaitOfferings().current ?: return
val monthly = current.monthly ?: return
val result = Purchases.sharedInstance.awaitPurchase(
    PurchaseParams.Builder(activity, monthly).build()
)
Handle cancel vs real failure.
kotlin
try {
    Purchases.sharedInstance.awaitPurchase(params)
} catch (e: PurchasesTransactionException) {
    if (e.userCancelled) return
    when (e.error.code) {
        PurchasesErrorCode.PaymentPendingError -> showPendingUi()
        PurchasesErrorCode.NetworkError -> showRetry()
        else -> showGenericError(e.error.message)
    }
}
Force a fresh CustomerInfo fetch after a server side grant.
kotlin
val fresh = Purchases.sharedInstance.awaitCustomerInfo(
    fetchPolicy = CacheFetchPolicy.FETCH_CURRENT
)
Log in an identified user and detect first login.
kotlin
val login = Purchases.sharedInstance.awaitLogIn("user_123")
val isNewAlias = login.created
val info = login.customerInfo
React to background entitlement changes.
kotlin
Purchases.sharedInstance.updatedCustomerInfoListener =
    UpdatedCustomerInfoListener { info ->
        val active = info.entitlements["pro_access"]?.isActive == true
        uiState.update { it.copy(hasPro = active) }
    }
根据权限限制功能访问。
kotlin
val info = Purchases.sharedInstance.awaitCustomerInfo()
val hasPro = info.entitlements["pro_access"]?.isActive == true
if (hasPro) unlockFeature() else showPaywall()
购买当前offering中的月度套餐。
kotlin
val current = Purchases.sharedInstance.awaitOfferings().current ?: return
val monthly = current.monthly ?: return
val result = Purchases.sharedInstance.awaitPurchase(
    PurchaseParams.Builder(activity, monthly).build()
)
区分用户取消和实际失败情况。
kotlin
try {
    Purchases.sharedInstance.awaitPurchase(params)
} catch (e: PurchasesTransactionException) {
    if (e.userCancelled) return
    when (e.error.code) {
        PurchasesErrorCode.PaymentPendingError -> showPendingUi()
        PurchasesErrorCode.NetworkError -> showRetry()
        else -> showGenericError(e.error.message)
    }
}
服务器端授予权限后强制获取最新的CustomerInfo。
kotlin
val fresh = Purchases.sharedInstance.awaitCustomerInfo(
    fetchPolicy = CacheFetchPolicy.FETCH_CURRENT
)
登录已识别用户并检测是否为首次登录。
kotlin
val login = Purchases.sharedInstance.awaitLogIn("user_123")
val isNewAlias = login.created
val info = login.customerInfo
响应后台权限变更。
kotlin
Purchases.sharedInstance.updatedCustomerInfoListener =
    UpdatedCustomerInfoListener { info ->
        val active = info.entitlements["pro_access"]?.isActive == true
        uiState.update { it.copy(hasPro = active) }
    }

References

参考资料

  • Related skills in this repo: rc-configuring-the-sdk, rc-purchase-flow, rc-error-handling, rc-subscription-states, rc-backend, rc-webhooks.
  • 本仓库中的相关技能:rc-configuring-the-sdkrc-purchase-flowrc-error-handlingrc-subscription-statesrc-backendrc-webhooks