К основному содержанию
скилл CX Codex

revenuecat-purchase-flow — скилл для Claude Code: покупки и restore

Скилл для ИИ-агента, который пишет логику покупки подписки и восстановления покупок на RevenueCat. Пригодится, когда за кастомным пейволлом нужен рабочий purchase и кнопка Restore.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add RevenueCat/ai-toolkit --skill revenuecat-purchase-flow -a claude-code
Открыть на GitHub

Что делает revenuecat-purchase-flow

Скилл закрывает сторону покупки в RevenueCat: получить offerings, взять Package из текущего offering, вызвать purchase(package). После успеха возвращённый customerInfo уже содержит покупку, и доступ проверяется по customerInfo.entitlements.active["<id>"]. Рендер пейволла и гейтинг фич сюда не входят — это отдельные скиллы.

Сначала агент определяет платформу по файлам проекта: package.json с react-native-purchases, pubspec.yaml, build.gradle.kts с multiplatform-блоками, нативный Android или iOS. Дальше читает соответствующий файл платформы с готовыми функциями покупки и restore. Отмена пользователем — не ошибка приложения: iOS бросает purchaseCancelledError, Android и Flutter — код PurchaseCancelledError, React Native ставит e.userCancelled === true. В этом случае нужно просто выйти без алерта.

Разблокировать контент внутри колбэка покупки не стоит: обновите customer info, а гейтед-UI пусть переключит слушатель entitlements. Так путь покупки и путь restore не разъедутся. Кнопки покупки на время запроса отключайте, иначе двойное списание. restorePurchases() — действие пользователя, а не автоматический шаг: на iOS кнопка восстановления обязательна по требованиям магазина.

Какие задачи решает

  • вызвать purchase для выбранного пакета и обработать результат
  • отличить отмену покупки пользователем от реальной ошибки
  • показать алерт только на отказ платежа или сбой сети
  • добавить кнопку Restore purchases на пейволл и в настройки
  • защититься от двойного списания при повторном нажатии

Примеры запросов агенту

  • добавь покупку подписки через RevenueCat в этом проекте
  • сделай обработку отмены покупки без алерта
  • добавь кнопку Restore purchases на экран пейволла

Как установить revenuecat-purchase-flow

1Через Skills CLI (Vercel)

npx skills add RevenueCat/ai-toolkit --skill revenuecat-purchase-flow -a claude-code

2Вручную: положить файлы

~/.claude/skills/revenuecat-purchase-flow/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/revenuecat-purchase-flow/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о revenuecat-purchase-flow

Как установить revenuecat-purchase-flow в Claude?

Выполните npx skills add RevenueCat/ai-toolkit --skill revenuecat-purchase-flow -a claude-code. Скилл окажется в ~/.claude/skills/revenuecat-purchase-flow/SKILL.md.

Что делает revenuecat-purchase-flow?

Пишет логику покупки и восстановления покупок на RevenueCat: получение offerings, вызов purchase, обработка ошибок и отмены, кнопка Restore. Пейволл и гейтинг фич — в других скиллах набора.

На каких платформах работает скилл?

iOS, Android, Kotlin Multiplatform, Flutter и React Native. Платформу агент определяет по файлам проекта, а если совпало несколько — берёт самый внешний проект или спрашивает вас.

Исходный текст

SKILL.md · MIT
---
name: revenuecat-purchase-flow
description: Implement the RevenueCat purchase and restore flow. Use when the user asks to buy a package, purchase a subscription, fetch offerings, build the purchase logic behind a custom (hand-coded) paywall, handle purchase errors, detect user cancelled, or restore previous purchases on iOS, Android, Kotlin Multiplatform, Flutter, or React Native.
---

# revenuecat-purchase-flow: buy a package and restore purchases

Use this skill when the user wants to complete the purchase side of RevenueCat: fetch offerings, call `purchase`, deal with cancellation and errors, and expose a "Restore" action. It does not cover rendering a paywall UI (that lives in `revenuecat-paywall`) or gating features (that lives in `revenuecat-entitlements-gate`).

If the app has no paywall yet and the user has not asked for a custom one, settle how the paywall is built first (`integrate-revenuecat`, Section 5c). The default is a RevenueCat Paywall, which handles the purchase itself.

## 1. Detect the platform

Inspect the working directory and pick the **first** match, from top to bottom:

1. **React Native**: `package.json` has a `react-native-purchases` entry, or `react-native` as a dependency → read `platforms/react-native.md`. If `expo` is also a dependency, note it as an Expo project.
2. **Flutter**: `pubspec.yaml` exists at the project root → read `platforms/flutter.md`.
3. **Kotlin Multiplatform**: `build.gradle.kts` contains a `kotlin { … }` multiplatform source sets block, or depends on `com.revenuecat.purchases:purchases-kmp*` → read `platforms/kmp.md`.
4. **Android (native)**: `build.gradle(.kts)` applies `com.android.application` (and is not KMP) → read `platforms/android.md`.
5. **iOS (native)**: `Package.swift`, `*.xcodeproj`, `*.xcworkspace`, or `Podfile` at the project root → read `platforms/ios.md`.

If several match (e.g. an `ios/` folder inside a Flutter project), pick the **outermost** project, the one that owns the build. If still ambiguous, ask the user which platform they want to configure.

## 2. Shared concepts (all platforms)

- **Flow.** Call `getOfferings()`, pick a `Package` from the current offering, call `purchase(package)`. When it completes successfully, the returned `customerInfo` already reflects the purchase. Read `customerInfo.entitlements.active["<id>"]` to confirm access.
- **User cancellation is not an application error.** Each SDK surfaces it differently: iOS throws a `purchaseCancelledError` code, Android throws a `PurchasesException` with `PurchasesErrorCode.PurchaseCancelledError`, Flutter surfaces a `PlatformException` with that same code, React Native sets `e.userCancelled === true`. Return silently in this case. Do not show an alert.
- **Errors worth messaging.** Payment declined, network errors, store unavailable, receipt already in use. Everything else should be logged and let the user try again. Never silently succeed when the purchase actually failed.
- **Do not unlock content inside the purchase callback.** Refresh customer info and let your entitlements listener (see `revenuecat-entitlements-gate`) flip the gated UI. This keeps one source of truth for access and avoids drift between the purchase path and the restore path.
- **`restorePurchases()` is a user action, not an automatic step.** It asks the store for the current receipt and syncs it to RevenueCat. Expose it from a visible "Restore purchases" button on the paywall and/or settings screen. Legal requirements on iOS mandate such a button.
- **One purchase at a time.** Disable the paywall buy buttons while a purchase is in flight to prevent double charges.

## 3. Implementation

Read the platform file that matches detection:

- `platforms/ios.md`
- `platforms/android.md`
- `platforms/kmp.md`
- `platforms/flutter.md`
- `platforms/react-native.md`

Each platform file contains a complete purchase function and a restore function.

## 4. Verify

Do not claim the flow works until:

1. A sandbox purchase of the current offering's package succeeds end to end, and the user's entitlement flips to active.
2. Cancelling the store sheet does not show an error alert and does not leave the UI in a loading state.
3. A second purchase attempt for the same active subscription is handled cleanly (StoreKit / Play Billing will surface a `productAlreadyPurchased` / `receiptAlreadyInUse` path; the flow should not crash).
4. The restore button, on a fresh install signed in to the same store account, restores the entitlement and updates the UI.

© RevenueCat · MIT · RevenueCat/ai-toolkit

Похожие скиллы

Всё по теме «Мобильная разработка» →
capacitor-in-app-purchases capawesome-team Скилл ведёт агента по шагам: настройка товаров в App Store Connect и Google Play Console, выбор плагина, покупки, валидация чеков и тесты в песочнице. CX Codex +1 728установок asc-revenuecat-catalog-sync rorkai Сверяет каталог подписок и встроенных покупок App Store Connect с продуктами RevenueCat. Нужен перед запуском или при устранении расхождений между каталогами. CX Codex +1 6 100установок paywall-optimization appeeky Скилл для аудита и A/B-тестов пейвола в подписочных приложениях. Помогает найти слабую ступень воронки и починить её. CX Codex +1 1 900установок argent-test-ui-flow software-mansion Скилл для автономного тестирования интерфейсов iOS и Android в Claude Code. Прогоняет цикл из кликов, скриншотов и проверок через MCP-инструменты argent. CX Codex +1 26 300установок subscription-lifecycle appeeky Скилл помогает разбирать подписочный цикл от пробного периода до продления, отмены и возврата ушедших подписчиков. Нужен для анализа конверсии, оттока и неудачных платежей. CX Codex +1 2 500установок post-purchase-upsell-flow autonnel Проектирует воронки допродаж в один клик после чекаута, поднимая средний чек без риска для конверсии основного заказа. Помогает настроить апселлы, даунселлы и техническую логику платежей. CX Codex +1 103 100установок

Из того же набора25

integrate-revenuecat Скилл проводит интеграцию RevenueCat целиком: заводит проект и приложение в дашборде, выдаёт публичный API-ключ и настраивает Purchases SDK в приложении. CX Codex +1 1 000установок revenuecat-testing-setup Настраивает тестовую среду для покупок RevenueCat: Test Store, StoreKit, sandbox, внутреннее тестирование Google Play. CX Codex +1 886установок revenuecat-entitlements-gate Скилл проверяет активные entitlements в RevenueCat и решает, показывать ли платную функцию. Пригодится, когда нужно спрятать фичу за подпиской. CX Codex +1 831установок revenuecat-status Собирает отчёт по проекту RevenueCat: приложения, продукты, entitlements, offerings и вебхуки. Пригодится, когда нужно быстро понять, что настроено. CX Codex +1 825установок revenuecat-identify-user Связывает пользователей приложения с подписчиками RevenueCat: вызывает logIn и logOut в нужный момент авторизации. CX Codex +1 788установок revenuecat-charts Скилл учит агента запрашивать графики RevenueCat: сначала схему опций, потом данные, с разбором метрик подписок. CX Codex +1 757установок revenuecat-customer-center Добавляет в приложение готовый экран Customer Center из RevenueCat: подписчик сам отменяет подписку, запрашивает возврат и восстанавливает покупки. CX Codex +1 715установок revenuecat-migrate Скилл помогает перевести покупки в приложении на RevenueCat или обновить SDK до новой мажорной версии. Сначала определяет платформу, потом ведёт по шагам. CX Codex +1 700установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой