Logo de Subscription States

Subscription States

Organização
RevenueCat
subscription-states

Use this skill when mapping a Google Play subscription to the eight states (PENDING, ACTIVE, IN_GRACE_PERIOD, ON_HOLD, PAUSED, CANCELED, EXPIRED, PENDING_PURCHASE_CANCELED) and deciding what access your app should grant in each state.

Visão geral

Publicado porRevenueCat
Repositórioplay-billing-skills
Nome da habilidadesubscription-states
Estrelas
58
Forks
0
Arquivos incluídos
Somente instruções
LicençaApache-2.0
Links
  • Instruções em Markdown

    Um arquivo SKILL.md que o modelo carrega sob demanda, consumindo tokens apenas quando uma solicitação é realmente relevante para a habilidade.

  • Funciona com qualquer LLM

    As habilidades de IA são escritas em Markdown simples, não em código específico de um provedor. Por isso, funcionam com GPT, Claude, Gemini, Grok ou um modelo local.

  • Sem arquivos extras

    Tudo de que o modelo precisa está nas instruções — sem arquivos extras para sincronizar.

  • Código aberto

    Publicada por RevenueCat no GitHub. Leia os arquivos da habilidade antes de instalá-la.

Instalação

Instale a habilidade de IA Subscription States no TypingMind para usá-la com qualquer LLM ou adicione-a a outro agente que leia SKILL.md.

1

Instalar no TypingMind

O TypingMind instala uma habilidade diretamente da pasta dela no GitHub — lê o arquivo SKILL.md, reúne os arquivos de recursos em um pacote e armazena o resultado localmente.

  1. Abra o app e vá para Plugins → Habilidades.
  2. Escolha "Instalar do GitHub".
  3. Cole a URL abaixo, que aponta para a pasta da habilidade, e confirme.
    https://github.com/RevenueCat/play-billing-skills/tree/main/google-play/subscription-states
  4. Ative a habilidade em cada chat em que quiser disponibilizá-la.
Plugins → Habilidades → Adicionar habilidade → Via URL do GitHub. Depois, cole a URL da pasta e pressione Continuar.
2

Instalar em outro agente

Qualquer agente que leia o formato Agent Skills pode usar esta habilidade — copie a pasta para o diretório de habilidades desse agente.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/RevenueCat/play-billing-skills.git /tmp/play-billing-skills
mkdir -p .claude/skills
cp -r /tmp/play-billing-skills/google-play/subscription-states .claude/skills/subscription-states
Reinicie Claude Code após copiar para que a nova habilidade seja reconhecida.

Use no TypingMind

Ative Subscription States em qualquer chat do TypingMind e o modelo cuida do resto. O nome e a descrição da habilidade ficam no prompt do sistema e, assim que uma solicitação relevante aparece, o modelo carrega as instruções completas automaticamente — sem precisar de acionamento manual e sem consumir tokens até que ela seja realmente usada.

O modelo carrega Subscription States automaticamente assim que uma solicitação é relevante para essa habilidade.

Funciona com qualquer modelo de IA

Habilidades de IA são instruções em Markdown simples, não código específico de um provedor. Por isso, Subscription States não fica vinculada ao modelo para o qual foi criada. Instale-a uma vez no TypingMind e use-a com GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama ou um modelo local executado por conta própria — tudo com suas próprias chaves de API.

  • Carregada apenas quando necessário

    O prompt do sistema contém apenas o nome e a descrição. As instruções são buscadas na primeira solicitação relevante, então uma habilidade sem uso não gera custo.

  • Troque de modelo durante a conversa

    Como a habilidade é composta de instruções, não de código, trocar de modelo não afeta seu funcionamento — o próximo modelo lê o mesmo arquivo SKILL.md.

Instruções da habilidade

Este é o conteúdo de SKILL.md que o modelo carrega. Leia antes de instalar — uma habilidade é um conjunto de instruções que seu modelo seguirá.

Subscription States

A Google Play subscription moves through eight states between the first purchase and final termination. Each state has a concrete access decision: grant, retain until expiry, or revoke. Get the mapping wrong and you either give away paid content or revoke access a user already paid for.

This skill walks you through confirming your app reads the correct state source, deciding the access rule for each state, and writing the mapping code.

Phase 1: Discovery

Before changing anything, confirm where your entitlement decision reads subscription state from. The authoritative source is the subscriptionState field on the SubscriptionPurchaseV2 resource returned by purchases.subscriptionsv2.get on the Google Play Developer API. The client Purchase object from queryPurchasesAsync() does not carry this field.

Answer these questions:

  1. Does your backend call purchases.subscriptionsv2.get (not the legacy purchases.subscriptions.get)?
  2. Does your entitlement function read subscriptionState from that response rather than inferring state from the RTDN notification type?
  3. Does the function check expiryTime when the state is SUBSCRIPTION_STATE_CANCELED?
  4. Does your client code treat a Purchase returned by queryPurchasesAsync() as "has a purchase," not "has access"?

If any answer is no, fix the source of truth first. Inferring state from the notification type is the single most common cause of wrong entitlement decisions, because two different transitions can produce the same RTDN type. For example, SUBSCRIPTION_RECOVERED fires both when a user fixes payment during account hold and when a paused subscription resumes, while a payment fixed during grace period arrives as SUBSCRIPTION_RENEWED.

Confirm the app is on subscriptionsv2 before moving on.

Phase 2: Plan the Decision Per State

Decide the access rule for each of the eight states. Use this table as the contract your code must match:

StateAccess DecisionReason
PENDINGDo not grantPayment has not settled yet.
PENDING_PURCHASE_CANCELEDDo not grant on this tokenPending payment canceled or expired; if linkedPurchaseToken is set, the previous subscription keeps its own state.
ACTIVEGrantPaid and within the current billing period.
IN_GRACE_PERIODGrantPayment failed, Google is retrying, user keeps access during the configured window.
CANCELEDRetain until expiryTimeUser canceled but already paid for the current period.
ON_HOLDRevokeGrace period expired without recovery.
PAUSEDRevokeVoluntary pause, no billing during the window.
EXPIREDRevokeSubscription has ended.

Three rules flow from this table:

  • Treat CANCELED as a delayed revocation, not an immediate one. Schedule the revocation for expiryTime.
  • Treat ON_HOLD as an immediate revocation. A default queryPurchasesAsync() omits subscriptions in account hold; if you query with includeSuspendedSubscriptions(true) (PBL 8.1+), they come back with isSuspended == true and must not grant access.
  • Treat PENDING as "no access yet." Wait for the transition to ACTIVE before entitling the user.

Plan the UI message for each revoking or warning state:

  • IN_GRACE_PERIOD: show a "fix your payment" prompt with the Play Store deep link.
  • ON_HOLD: show the same prompt, since recovery is still possible until the hold expires.
  • PAUSED: show the resume date, not a payment failure message.
  • CANCELED: show a resubscribe prompt that references expiryTime.
  • EXPIRED: show a fresh purchase offer.

Phase 3: Execute

Map the state string to an access decision

Encode the decision table directly. Keep the function pure so it is easy to test.

kotlin
fun shouldGrantAccess(
    state: String,
    expiryTimeMillis: Long
): Boolean = when (state) {
    "SUBSCRIPTION_STATE_ACTIVE",
    "SUBSCRIPTION_STATE_IN_GRACE_PERIOD" -> true
    "SUBSCRIPTION_STATE_CANCELED" ->
        System.currentTimeMillis() < expiryTimeMillis
    else -> false
}

Everything not listed (ON_HOLD, PAUSED, EXPIRED, PENDING, and anything unknown) returns false. This is the safe default.

Gate the client path with the backend state

The client must not decide entitlement alone. The client cannot see grace period (it looks like a normal active purchase) and omits account hold unless includeSuspendedSubscriptions(true) is set, in which case check isSuspended.

kotlin
suspend fun checkEntitlement(
    client: BillingClient,
    api: YourBackendApi
): Boolean {
    val params = QueryPurchasesParams.newBuilder()
        .setProductType(ProductType.SUBS).build()
    val result = client.queryPurchasesAsync(params)
    val purchase = result.purchasesList.firstOrNull()
        ?: return false
    if (purchase.purchaseState == PurchaseState.PENDING) {
        return false
    }
    return api.verifyEntitlement(purchase.purchaseToken)
}

The client check filters out "no purchase" and pending payments. The backend call resolves the real subscription state.

Route the backend handler by state, not by notification type

When an RTDN arrives, fetch the subscription and branch on subscriptionState.

kotlin
fun handle(notification: SubscriptionNotification) {
    val token = notification.purchaseToken
    val sub = playApi.getSubscriptionV2(pkg, token)
    when (sub.subscriptionState) {
        "SUBSCRIPTION_STATE_ACTIVE" -> grant(token)
        "SUBSCRIPTION_STATE_IN_GRACE_PERIOD" -> grantWithWarning(token)
        "SUBSCRIPTION_STATE_CANCELED" -> scheduleRevoke(token, sub)
        "SUBSCRIPTION_STATE_ON_HOLD",
        "SUBSCRIPTION_STATE_PAUSED",
        "SUBSCRIPTION_STATE_EXPIRED" -> revoke(token)
        "SUBSCRIPTION_STATE_PENDING" -> hold(token)
        "SUBSCRIPTION_STATE_PENDING_PURCHASE_CANCELED" -> cleanUpPending(token, sub.linkedPurchaseToken)
    }
}

Schedule the CANCELED revocation at expiryTime so the user keeps the time they paid for.

kotlin
fun scheduleRevoke(token: String, sub: SubscriptionPurchaseV2) {
    val expiry = Instant.parse(
        sub.lineItems.first().expiryTime
    ).toEpochMilli()
    if (System.currentTimeMillis() >= expiry) {
        revoke(token)
    } else {
        db.setExpiry(token, expiry)
        scheduler.scheduleAt(expiry) { revoke(token) }
    }
}

Verify

Before shipping, confirm these behaviors with fixtures or a staging account:

  • A CANCELED subscription with expiryTime in the future still grants access.
  • An ON_HOLD subscription revokes access; queryPurchasesAsync() omits it by default or returns it with isSuspended == true.
  • A PENDING subscription does not grant access until it transitions to ACTIVE.
  • An unknown or new state string returns false rather than defaulting to true.

References

Perguntas frequentes

O que a habilidade de IA Subscription States faz?

Use this skill when mapping a Google Play subscription to the eight states (PENDING, ACTIVE, IN_GRACE_PERIOD, ON_HOLD, PAUSED, CANCELED, EXPIRED, PENDING_PURCHASE_CANCELED) and deciding what access your app should grant in each state.

Por que usar Subscription States no TypingMind?

Porque basta instalar uma vez para usar com qualquer modelo. A habilidade Subscription States é escrita em Markdown simples, e não em código específico de um provedor, então a mesma habilidade funciona com GPT-5, Claude, Gemini, Grok ou um modelo local — e é possível trocar de modelo no meio do chat sem que ela deixe de funcionar. No TypingMind, você usa suas próprias chaves de API e paga diretamente aos provedores, em vez de pagar uma assinatura por licença de usuário. Suas habilidades e chats permanecem no seu próprio armazenamento.

Como instalar Subscription States no TypingMind?

Abra Plugins → Habilidades → Instalar do GitHub no TypingMind e cole https://github.com/RevenueCat/play-billing-skills/tree/main/google-play/subscription-states. O TypingMind lê o arquivo SKILL.md e instala a habilidade para que possa ser ativada em cada chat.

Quais modelos de IA podem usar Subscription States?

Qualquer modelo conectado no TypingMind. As habilidades de IA são instruções em Markdown simples, e não código específico de um provedor. Assim, GPT, Claude, Gemini, Grok e modelos locais podem carregar esta habilidade quando uma solicitação corresponder a ela.

Quantos modelos de IA posso usar com Subscription States?

Quantos quiser. Desde que o modelo ofereça suporte a habilidades, é possível usar Subscription States com ele — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama e outros — tudo no TypingMind com suas próprias chaves de API.

A habilidade de IA Subscription States é gratuita?

Sim. A habilidade é publicada no GitHub por RevenueCat sob a licença Apache-2.0. O pagamento é feito apenas ao seu provedor de IA pelos tokens usados.

O que são habilidades de IA?

Uma habilidade de IA é um conjunto reutilizável de instruções que ensina um modelo de IA a realizar uma tarefa específica. Ela segue o formato aberto Agent Skills: um arquivo SKILL.md com nome e descrição, além de scripts, templates ou arquivos de referência de que o modelo possa precisar. O modelo lê as instruções apenas quando sua solicitação corresponde à habilidade, então uma habilidade instalada não gera custos até ser usada.

Qual é a diferença entre habilidades de IA e plugins ou servidores MCP?

Um plugin ou servidor MCP oferece ao modelo novas ferramentas que ele pode acionar — código que é executado em algum lugar e retorna um resultado. Já uma habilidade de IA dá ao modelo o conhecimento e as orientações de que ele precisa: como abordar uma tarefa, quais etapas seguir e como deve ser um bom resultado. As habilidades são escritas em Markdown simples, por isso não precisam de servidor, chave de API nem ambiente de execução, e funcionam com qualquer modelo.

Ver lista completa

Crie seu próprio espaço de trabalho com IA agora

Inscreva-se na nossa newsletter para receber avisos sobre novos recursos e futuros sorteios 👇