Логотип Plan Changes

Plan Changes

Организация
RevenueCat
plan-changes

Use this skill when implementing Google Play subscription upgrades, downgrades, or plan switches with SubscriptionProductReplacementParams (PBL 8.1+) plus SubscriptionUpdateParams.setOldPurchaseToken. Covers the replacement modes (WITH_TIME_PRORATION, CHARGE_PRORATED_PRICE, WITHOUT_PRORATION, CHARGE_FULL_PRICE, DEFERRED, KEEP_EXISTING) and when each applies.

Add to TypingMind

Обзор

ИздательRevenueCat
Репозиторийplay-billing-skills
Название навыкаplan-changes
Звёзды
58
Форки
0
Файлы в комплекте
Только инструкции
ЛицензияApache-2.0
Ссылки
  • Инструкции в формате Markdown

    Модель загружает файл SKILL.md по мере необходимости, поэтому токены расходуются только при подходящем запросе.

  • Работает с любой большой языковой моделью

    Навыки ИИ — это обычный Markdown, а не код для конкретного поставщика, поэтому они работают с GPT, Claude, Gemini, Grok и локальными моделями.

  • Всё необходимое — в инструкциях

    Всё необходимое для модели содержится в инструкциях — никаких дополнительных файлов для синхронизации.

  • Открытый исходный код

    Издатель навыка на GitHub — RevenueCat. Перед установкой изучите исходные материалы.

Установка

Установите навык ИИ Plan Changes в TypingMind, чтобы использовать его с любой LLM, или добавьте его в другой агент, который умеет читать SKILL.md.

1

Установка в TypingMind

TypingMind устанавливает навык прямо из его папки на GitHub: читает SKILL.md, собирает файлы ресурсов и сохраняет результат локально.

  1. Откройте приложение и перейдите в раздел «Плагины → Навыки».
  2. Выберите «Установить из GitHub».
  3. Вставьте указанную ниже ссылку на папку навыка и подтвердите установку.
    https://github.com/RevenueCat/play-billing-skills/tree/main/google-play/plan-changes
  4. Включите навык в каждом чате, где хотите его использовать.
Плагины → Навыки → Добавить навык → По ссылке GitHub, затем вставьте ссылку на папку и нажмите «Продолжить».
2

Установка в другом агенте

Любой агент с поддержкой формата Agent Skills может использовать этот навык — скопируйте папку в каталог навыков этого агента.

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/plan-changes .claude/skills/plan-changes
После копирования перезапустите Claude Code, чтобы загрузить новый навык.

Использование в TypingMind

Включите навык Plan Changes в любом чате TypingMind, и дальше модель всё сделает сама. Его название и описание хранятся в системном промпте, а при появлении подходящего запроса модель сама загружает полные инструкции. Вам не нужно вызывать навык вручную, и до фактического использования он не расходует токены.

Модель сама загружает навык Plan Changes, как только появляется подходящий для него запрос.

Работает с любой моделью ИИ

Навыки ИИ — это обычные инструкции в Markdown, а не код для конкретного поставщика, поэтому навык Plan Changes не привязан к модели, для которой он был создан. Установите его один раз в TypingMind и используйте с GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama или локальной моделью, которую запускаете самостоятельно, — со своими ключами API.

  • Загружается только при необходимости

    Системный промпт содержит только название и описание. Инструкции загружаются при первом подходящем запросе, поэтому неиспользуемый навык не расходует токены.

  • Меняйте модели прямо в чате

    Навык состоит из инструкций, а не кода, поэтому смена модели не нарушает его работу: новая модель читает тот же файл SKILL.md.

Инструкции навыка

Это содержимое файла SKILL.md, которое загружает модель. Прочитайте его перед установкой: навык — это инструкции, которым будет следовать ваша модель.

Plan Changes: Upgrades, Downgrades, and Plan Switches

Plan changes on Google Play Billing Library (PBL) 9.x always mint a new purchase token. You pick a replacement mode that controls two things: when the user gets access to the new plan, and how Google handles the money between the old and new agreement. This skill walks you through selecting the correct mode and wiring it into BillingFlowParams.

Phase 1: Scope the Change

Before touching code, answer four questions about the requested switch:

  1. Direction: is this an upgrade (new plan costs more), a downgrade (new plan costs less), or a lateral switch (same price, different cadence)?
  2. Billing period: are you moving between plans with the same billing period (monthly to monthly) or across periods (monthly to annual, recurring to prepaid)?
  3. Promotional state: is the user currently inside a free trial or introductory price window that should survive the switch?
  4. Additivity: is the new SKU replacing the old subscription, or should it sit alongside the old one as an add on?

Write those four answers down. Every decision in Phase 2 follows directly from them.

You also need three inputs from the client at runtime:

  • oldPurchaseToken: the purchase token for the subscription the user is leaving.
  • oldProductId: the product ID of the subscription being replaced (from the active Purchase.products), for SubscriptionProductReplacementParams.setOldProductId.
  • ProductDetails and offer token for the new plan, fetched through queryProductDetailsAsync.

If any is missing, stop and fetch it first. Launching the billing flow without a valid oldPurchaseToken produces a new standalone subscription when the target is a different subscription (within the same subscription, Play applies the base plan's default replacement mode).

Also confirm the current purchase is acknowledged (Purchase.isAcknowledged); Play blocks plan changes while it is pending acknowledgement. If the original purchase used setObfuscatedAccountId, pass the same value on the plan change BillingFlowParams.

Phase 2: Plan the Replacement Mode

PBL 8.1+ has two ReplacementMode interfaces with different integer values. With SubscriptionProductReplacementParams.setReplacementMode() always use BillingFlowParams.ProductDetailsParams.SubscriptionProductReplacementParams.ReplacementMode (CHARGE_FULL_PRICE=4, DEFERRED=5, KEEP_EXISTING=6). The older BillingFlowParams.SubscriptionUpdateParams.ReplacementMode (CHARGE_FULL_PRICE=5, DEFERRED=6) still compiles against the same int parameter but picks the wrong mode, so never import it next to product level params. UNKNOWN_REPLACEMENT_MODE is a placeholder; do not select it. The five modes you actually pick from are listed below, along with KEEP_EXISTING which arrived in PBL 8.1 for add on bundles.

Mode Decision Table

Use this table to map your Phase 1 answers to a mode.

ScenarioRecommended ModeImmediate Charge?Access Switch
Upgrade to a higher tier (Google's recommendation)CHARGE_PRORATED_PRICEYes, prorated differenceImmediate, renewal unchanged
Upgrade, credit the remaining time instead of charging nowWITH_TIME_PRORATIONNoImmediate, renewal shifts forward
Switch to or from a prepaid planCHARGE_FULL_PRICEYes, full new priceImmediate
Upgrade during a free trial or intro priceWITHOUT_PRORATIONNo, settles at next renewalImmediate, trial preserved
DowngradeDEFERREDNoAt next renewal
Add an add on, keep the current item unchangedKEEP_EXISTING on the current itemProrated charge for the new add onAdd on immediate, current item untouched

For add ons, pass every active item you keep plus the new add on in setProductDetailsParamsList (current base item first). On each kept item, set SubscriptionProductReplacementParams with setOldProductId(<the same product id>) and KEEP_EXISTING, and do not set an offer token. The new add on gets no replacement params. Still set SubscriptionUpdateParams.setOldPurchaseToken. Leaving an active item out of the list schedules it for removal. All items must be auto renewing with the same billing period.

Three rules keep you out of trouble:

  • CHARGE_PRORATED_PRICE only works for upgrades. Using it on a downgrade makes the billing flow fail because Google does not refund through proration.
  • CHARGE_FULL_PRICE is required when switching to a prepaid plan; from prepaid to auto renewing within the same subscription, CHARGE_FULL_PRICE or WITHOUT_PRORATION.
  • Within the same subscription (switching base plans or offers of one Product ID) to an auto renewing plan, only CHARGE_FULL_PRICE or WITHOUT_PRORATION are accepted; anything else fails the purchase. Installment to non installment within one subscription is not allowed. The other rows of the table apply to switches between different subscriptions.

Trade offs to Communicate in Your UI

Each mode has a user facing surprise you need to preempt:

  • WITH_TIME_PRORATION shortens the next renewal interval on upgrades. Show the new renewal date.
  • CHARGE_PRORATED_PRICE posts a small charge now. Show the amount before launching the flow.
  • CHARGE_FULL_PRICE posts the full new price now. Do not hide this behind a generic confirmation.
  • WITHOUT_PRORATION gives paid access until next renewal. Outside trials this is revenue you chose to give away.
  • DEFERRED delays the switch. Tell the user "You will switch to Basic on " using the current line item's expiryTime.

The Play Console Default

You can configure a default replacement mode per subscription in Play Console under Monetize > Subscriptions. Each base plan's "Base plan and offer changes" setting (charge immediately = CHARGE_FULL_PRICE, or at next billing date = WITHOUT_PRORATION) only applies to switches and resubscribes within the same subscription when the client sets no mode; it never applies to a switch to a different subscription. Treat it as a safety net, not a substitute for setting the mode explicitly in code.

Phase 3: Wire Up SubscriptionProductReplacementParams

Starting with PBL 8.1, SubscriptionUpdateParams.setSubscriptionReplacementMode() is deprecated. Set the mode per product with SubscriptionProductReplacementParams on the new product's ProductDetailsParams, and keep passing the old purchase token through SubscriptionUpdateParams.setOldPurchaseToken(). Do not also call setSubscriptionReplacementMode(): if both are set, launchBillingFlow() returns DEVELOPER_ERROR (debug message "...cannot be called at the same time.").

Build the replacement params with the mode you picked in Phase 2, attach them to the new product's ProductDetailsParams, and keep the old purchase token on SubscriptionUpdateParams. The example below implements an upgrade to a higher tier with Google's recommended CHARGE_PRORATED_PRICE, which keeps the billing date stable.

kotlin
val replacement = BillingFlowParams.ProductDetailsParams
    .SubscriptionProductReplacementParams.newBuilder()
    .setOldProductId(currentProductId) // product being replaced
    .setReplacementMode(
        BillingFlowParams.ProductDetailsParams.SubscriptionProductReplacementParams
            .ReplacementMode.CHARGE_PRORATED_PRICE
    )
    .build()

val productParams = BillingFlowParams.ProductDetailsParams.newBuilder()
    .setProductDetails(premiumDetails)
    .setOfferToken(premiumOfferToken)
    .setSubscriptionProductReplacementParams(replacement)
    .build()

val flowParams = BillingFlowParams.newBuilder()
    .setProductDetailsParamsList(listOf(productParams))
    .setSubscriptionUpdateParams(
        BillingFlowParams.SubscriptionUpdateParams.newBuilder()
            .setOldPurchaseToken(currentPurchaseToken)
            .build()
    )
    .build()

billingClient.launchBillingFlow(activity, flowParams)

The structural change from the deprecated setter is that per product replacement data rides with the product, while the old purchase token still rides with the flow. That shape matches what you are saying: "I want this product, and it should replace this existing subscription, using this old token."

Handling the Result

PurchasesUpdatedListener receives a new Purchase with a new purchase token. Send that token to your backend. Your server then calls purchases.subscriptionsv2.get and inspects linkedPurchaseToken:

kotlin
fun handleNewPurchaseToken(newToken: String) {
    val subscription = playApi
        .getSubscriptionV2(packageName, newToken)
    when (subscription.subscriptionState) {
        "SUBSCRIPTION_STATE_PENDING",
        "SUBSCRIPTION_STATE_PENDING_PURCHASE_CANCELED" -> return // pending: keep the old token entitled
    }
    val linked = subscription.linkedPurchaseToken
    if (linked != null) {
        database.markReplaced(linked)
    }
    database.insertSubscription(
        purchaseToken = newToken,
        // DEFERRED: the incoming item has no expiryTime yet, so record the current one
        productId = subscription.lineItems.first { it.expiryTime != null }.productId,
        status = subscription.subscriptionState
    )
}

Walk the chain if you may have missed prior notifications: the linked token might itself have been replaced by an even older token you still show as active.

Deferred Mode Specifics

With DEFERRED, the new token arrives immediately but carries two line items: the current plan (future expiryTime, plus a deferredItemReplacement naming the upcoming product) and the new plan (no expiryTime yet). Grant entitlement based on the current line item and schedule the switch for the expiry time:

kotlin
for (item in subscription.lineItems) {
    val pending = item.deferredItemReplacement ?: continue
    currentProductId = item.productId
    upcomingProductId = pending.productId
    switchAt = item.expiryTime
}

When the renewal fires, Google sends an RTDN and you promote the pending plan to active.

Verification Checklist

Before shipping a plan change flow, confirm all of the following:

  • You set oldPurchaseToken on SubscriptionUpdateParams and oldProductId on SubscriptionProductReplacementParams from the active subscription, not a stale cached value.
  • The replacement mode matches the direction and promotional state from Phase 1.
  • You do not pass CHARGE_PRORATED_PRICE for downgrades.
  • CHARGE_FULL_PRICE is required when switching to a prepaid plan; from prepaid to auto renewing within the same subscription, CHARGE_FULL_PRICE or WITHOUT_PRORATION.
  • Your backend reads linkedPurchaseToken and marks the old record replaced before activating the new one.
  • For DEFERRED, your UI surfaces the scheduled switch date from the current line item's expiryTime.
  • You acknowledge the new purchase on your backend after verification.

References

Часто задаваемые вопросы

Что делает навык ИИ Plan Changes?

Use this skill when implementing Google Play subscription upgrades, downgrades, or plan switches with SubscriptionProductReplacementParams (PBL 8.1+) plus SubscriptionUpdateParams.setOldPurchaseToken. Covers the replacement modes (WITH_TIME_PRORATION, CHARGE_PRORATED_PRICE, WITHOUT_PRORATION, CHARGE_FULL_PRICE, DEFERRED, KEEP_EXISTING) and when each applies.

Зачем использовать Plan Changes в TypingMind?

Потому что вы устанавливаете навык один раз и используете его с любой моделью. Plan Changes — это обычный текст в формате Markdown, а не код для конкретного поставщика, поэтому один и тот же навык работает с GPT-5, Claude, Gemini, Grok или локальной моделью. Вы можете менять модель прямо во время чата, и навык продолжит работать. TypingMind использует ваши собственные ключи API, поэтому вы платите поставщикам напрямую, а не оформляете подписку с оплатой за каждое место. Ваши навыки и чаты остаются в вашем собственном хранилище.

Как установить Plan Changes в TypingMind?

В TypingMind откройте «Плагины → Навыки → Установить из GitHub» и вставьте https://github.com/RevenueCat/play-billing-skills/tree/main/google-play/plan-changes. TypingMind прочитает файл SKILL.md и установит навык, который можно включать отдельно для каждого чата.

Какие модели ИИ могут использовать Plan Changes?

Любая модель, которую вы подключите в TypingMind. Навыки ИИ — это обычные инструкции в формате Markdown, а не код для конкретного поставщика, поэтому GPT, Claude, Gemini, Grok и локальные модели могут загружать этот навык, когда запрос ему соответствует.

Со сколькими моделями ИИ можно использовать Plan Changes?

С любым количеством. В TypingMind вы можете использовать Plan Changes с любой моделью, которая поддерживает навыки, в том числе с GPT, Claude, Gemini, Grok, DeepSeek, Mistral и Llama. Для этого вы используете собственные ключи API.

Бесплатен ли навык ИИ Plan Changes?

Да. Навык опубликован на GitHub по лицензии Apache-2.0. Издатель — RevenueCat. Вы платите только своему поставщику ИИ за использованные токены.

Что такое навыки ИИ?

Навык ИИ — это набор инструкций, которыми модель ИИ может пользоваться каждый раз, когда ей нужно выполнить конкретную задачу. Он соответствует открытому формату Agent Skills: файл SKILL.md с названием и описанием, а также любые скрипты, шаблоны или справочные файлы, которые могут понадобиться модели. Модель читает инструкции, только когда ваш запрос соответствует навыку, поэтому установленный навык ничего не стоит, пока не используется.

Чем навыки ИИ отличаются от плагинов и серверов MCP?

Плагин или сервер MCP даёт модели новые инструменты, которые она может вызывать: при вызове где-то выполняется код и возвращает результат. Навык ИИ, напротив, даёт модели знания и описывает порядок действий: как подойти к задаче, какие шаги выполнить и каким должен быть хороший результат. Навыки — это обычный текст в формате Markdown, поэтому им не нужны сервер, ключ API или среда выполнения, и они работают с любой моделью.

Все

Создайте своё рабочее пространство с ИИ прямо сейчас

Подпишитесь на нашу рассылку, чтобы узнавать о новых функциях и предстоящих розыгрышах 👇