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

customer-management — скилл для Claude Code

Скилл customer-management для Claude Code управляет клиентами Dodo Payments: создаёт записи, настраивает портал и способы оплаты, ведёт кошельки и связывает пользователей приложения с ID клиентов для биллинга.

MIT 202 установок ★ 14 обновлён 2026-10-20

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

Что делает customer-management

Охватывает полный цикл работы с клиентами: CRUD-операции над записями, портал для просмотра счётов и отмены подписок, управление сохранёнными картами, операции с кошельками (USD и INR). Клиентские записи группируют платежи и подписки; каждому выдаётся ID с префиксом cus_. Портал — это размещённая на сервере Dodo Payments сессия, действующая 24 часа; клиент переходит по ссылке и может управлять счётами, менять планы, обновлять способы оплаты, загружать ключи лицензий.

Кошельки хранят реальные деньги (USD, INR), которые клиент потратит на следующие покупки. Это отличается от usage credits (для них есть отдельный скилл credit-based-billing). Записи в реестре кошелька защищены от дублирования через idempotency_key: если сеть разорвётся после создания записи, повторный запрос с тем же ключом вернёт уже созданную запись, а не создаст дубликат платежа.

Энтайтлменты — это права на функции или файлы. Метод listCreditEntitlements показывает баланс кредитов, listEntitlements — гранты функций, listEntitlementGrants — отдельные выданные права с их статусом. Для работы нужна переменная окружения DODO_PAYMENTS_API_KEY.

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

  • Связать пользователя приложения с клиентом в биллинговой системе
  • Открыть для клиента портал управления счётами и подписками
  • Выдать или отозвать доступ к функциям по условию
  • Обработать возврат или бонус кредитом на кошелёк
  • Получить список сохранённых способов оплаты клиента

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

  • Создай клиента с email [email protected] и меткой userId: user_12345
  • Откройи портал управления подписками для клиента cus_abc123
  • Выдай клиенту $50 на кошелёк со статусом возврата заказа #12345

Как установить customer-management

1Через Skills CLI (Vercel)

npx skills add dodopayments/skills --skill customer-management -a claude-code

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

~/.claude/skills/customer-management/SKILL.md

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

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

Вопросы о customer-management

Как установить customer-management в Claude Code?

Запусти в терминале npx skills add dodopayments/skills --skill customer-management -a claude-code, затем открой ~/.claude/skills/customer-management/SKILL.md в Claude Code.

Что делает этот скилл?

Управляет клиентами в Dodo Payments: создаёт записи, открывает портал самообслуживания, управляет сохранёнными картами, работает с кошельками (балансы, операции) и энтайтлментами (права на функции и кредиты).

В чём разница между кошельком и usage credits?

Кошельки хранят реальные деньги (USD, INR), которые клиент потратит на покупки. Usage credits — это счётчики за использование API или услуг; для них используй скилл credit-based-billing.

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

SKILL.md · MIT
---
name: customer-management
description: Dodo Payments customer management, covering customer CRUD, saved payment methods, real-money customer wallets and ledger entries, entitlements, and hosted customer portal sessions. Use when linking app users to cus_ IDs, opening a Manage billing portal, listing or deleting payment methods, or crediting wallets; use credit-based-billing for usage credits.
---

# Customer Management

Build customer records, hosted self-service portals, saved payment methods, and real-money wallet ledgers. This skill covers the full customer lifecycle: CRUD operations, payment method management, time-bound portal sessions, and idempotent wallet transactions.

## When to use this skill

- Creating, listing, retrieving, or updating customer records
- Building a self-service customer portal for invoices, subscriptions, and payment methods
- Managing saved payment methods and customer payment history
- Implementing customer wallet balances and ledger entries for credits or refunds
- Linking your app's user records to Dodo customers
- Reading customer entitlements and credit balances

## Core concepts

**Customers** are records in Dodo that group payments, subscriptions, and portal access. Each customer has an ID (prefix `cus_`), email, name, and optional metadata.

**Customer Portal** is a hosted, time-bound session that lets customers self-serve: view invoices, cancel subscriptions, change plans, update payment methods, recover on-hold subscriptions, and download license keys. You create a session and redirect to its link.

**Payment Methods** are saved cards or other payment instruments linked to a customer. You can list and delete them; creation happens during checkout.

**Customer Wallets** hold real-money balances (USD, INR) that customers can spend on future purchases. They are NOT the same as usage credits (see `credit-based-billing` skill). Wallet ledger entries are idempotent via `idempotency_key` to prevent duplicate charges.

**Entitlements** are feature or file grants. `listCreditEntitlements` returns credit balances; `listEntitlements` returns feature/file grants; `listEntitlementGrants` lists individual grants with revocation status.

## Customer CRUD

Create, list, retrieve, and update customer records.

```typescript
import DodoPayments from 'dodopayments';

const client = new DodoPayments({
  bearerToken: process.env.DODO_PAYMENTS_API_KEY,
  environment: 'test_mode',
});

// Create a customer
const customer = await client.customers.create({
  email: '[email protected]',
  name: 'Alice Chen',
  metadata: {
    userId: 'user_12345',
    tier: 'premium',
  },
});
console.log(customer.customer_id); // cus_...

// List customers
const customers = await client.customers.list({
  page_size: 10,
});

// Retrieve a customer
const retrieved = await client.customers.retrieve('cus_abc123');

// Update a customer
await client.customers.update('cus_abc123', {
  name: 'Alice Chen-Smith',
  metadata: { tier: 'enterprise' },
});
```

## Customer Portal

Create a time-bound session that redirects customers to a hosted portal. In the portal, customers can view invoices, cancel subscriptions, change plans, update payment methods, recover on-hold subscriptions, and download license keys.

Never call the SDK from the browser: it uses your secret API key. Create the session in a server route and return only the link.

```typescript
// Server route: create a portal session
const session = await client.customers.customerPortal.create('cus_abc123', {
  return_url: 'https://yourapp.com/dashboard',
  // send_email: true, // optionally also email the link to the customer
});

return Response.json({ link: session.link });
```

```typescript
// Browser: redirect the customer
const res = await fetch('/api/portal', { method: 'POST' });
const { link } = await res.json();
window.location.href = link;
```

The portal session link is valid for 24 hours. Pass `send_email: true` to have Dodo also email the link to the customer. Customers cannot:
- Create new subscriptions (use checkout for that)
- Refund themselves
- Change their email or name (contact support)
- Access billing history beyond invoices

If you need to rebuild any of these, you're duplicating the portal. Use it instead.

## Saved Payment Methods

List and delete payment methods saved to a customer.

```typescript
// List payment methods for a customer
const methods = await client.customers.retrievePaymentMethods('cus_abc123');
console.log(methods);
// {
//   items: [{ payment_method_id: 'pm_xyz789', payment_method: 'card' }]
// }

// Delete a payment method
await client.customers.deletePaymentMethod('pm_xyz789', {
  customer_id: 'cus_abc123',
});
```

Payment methods are created during checkout when the customer opts to save their card. You cannot create them directly via the API.

## Customer Wallets

Wallets hold real-money balances (USD, INR) that customers can spend on future purchases. They are distinct from usage credits. List wallet balances and create idempotent ledger entries.

```typescript
// List wallets for a customer
const wallets = await client.customers.wallets.list('cus_abc123');
console.log(wallets);
// {
//   items: [
//     { currency: 'USD', balance: 5000, customer_id: 'cus_abc123', ... },
//     { currency: 'INR', balance: 100000, customer_id: 'cus_abc123', ... }
//   ],
//   total_balance_usd: 17000
// }

// List ledger entries
const entries = await client.customers.wallets.ledgerEntries.list('cus_abc123', {
  page_size: 20,
});

// Create a ledger entry (credit or debit)
// Amounts are in the smallest currency unit (cents for USD, paise for INR)
await client.customers.wallets.ledgerEntries.create('cus_abc123', {
  amount: 1000, // $10.00 in USD
  currency: 'USD',
  entry_type: 'credit', // or 'debit'
  reason: 'Refund for order #12345',
  idempotency_key: 'refund_order_12345_v1',
});
```

**Idempotency is critical.** If your network fails after creating a ledger entry, retrying with the same `idempotency_key` returns the existing entry instead of creating a duplicate charge. Always use a stable, unique key per transaction.

Wallets are real money. Do not create entries without idempotency keys, and do not expose wallet balances to the client without verification.

## Reading Customer Entitlements

Entitlements are feature or file grants. There are three methods:

```typescript
// List credit entitlements (credit balances)
const credits = await client.customers.listCreditEntitlements('cus_abc123');
console.log(credits);
// {
//   items: [{
//     credit_entitlement_id: 'cred_ent_1',
//     balance: '5000',
//     name: 'API Calls',
//     overage: '0',
//     unit: 'calls'
//   }]
// }

// List feature/file entitlements
const features = await client.customers.listEntitlements('cus_abc123');
console.log(features);
// {
//   items: [
//     {
//       grant_id: 'entg_feature_1',
//       entitlement_id: 'ent_feature_1',
//       entitlement_name: 'Pro Features',
//       integration_type: 'feature_flag',
//       status: 'delivered',
//       created_at: '2026-01-01T00:00:00Z',
//       updated_at: '2026-01-01T00:00:00Z'
//     }
//   ]
// }

// List individual grants (with revocation status)
const grants = await client.customers.listEntitlementGrants('cus_abc123', {
  page_size: 50,
});
console.log(grants);
// {
//   items: [{
//     id: 'entg_feature_1',
//     entitlement_id: 'ent_feature_1',
//     status: 'Delivered',
//     revoked_at: null
//   }]
// }
```

## Linking Your App's Users to Dodo Customers

Store the Dodo customer ID in your user record, or use metadata to link them.

```typescript
// Option 1: Store the Dodo customer ID in your database
const customer = await client.customers.create({
  email: user.email,
  name: user.name,
});
await db.users.update(user.id, { dodo_customer_id: customer.customer_id });

// Option 2: Use metadata to store your user ID
const customer = await client.customers.create({
  email: user.email,
  name: user.name,
  metadata: {
    app_user_id: user.id,
  },
});

// Later, retrieve by email (not a direct API call, but common pattern)
// You must store the mapping yourself or query Dodo's list endpoint
const customers = await client.customers.list({ page_size: 100 });
const found = customers.items.find(c => c.email === user.email);
```

**Email matching pitfall:** if a user changes their email in your app, the Dodo customer email won't update automatically. Always sync email changes explicitly via `client.customers.update()`.

## Common mistakes

**Creating duplicate customers per checkout.** Passing `customer: { email }` does not create a new customer each time: by default, checkout uses the email to find an existing customer and attaches the session to it. Duplicates come from setting `feature_flags.always_create_new_customer: true`, or from calling `customers.create` before every checkout. Create the customer once (or let the first checkout create it), store its `customer_id`, and pass that on later checkouts.

```typescript
// WRONG: forces a new customer record on every checkout
const session = await client.checkoutSessions.create({
  product_cart: [{ product_id: 'pdt_abc', quantity: 1 }],
  customer: { email: user.email },
  feature_flags: { always_create_new_customer: true },
});

// RIGHT: reuse the stored customer ID, or fall back to email (matched to an existing customer by default)
const session = await client.checkoutSessions.create({
  product_cart: [{ product_id: 'pdt_abc', quantity: 1 }],
  customer: user.dodo_customer_id
    ? { customer_id: user.dodo_customer_id }
    : { email: user.email },
});
```

**Building a bespoke billing UI instead of using the portal.** The portal handles invoices, cancellations, plan changes, payment method updates, and on-hold recovery. If you rebuild these, you're duplicating work and missing edge cases.

**Mutating wallet balances without an idempotency key.** Retries will create duplicate entries and charge the customer twice.

```typescript
// WRONG
await client.customers.wallets.ledgerEntries.create('cus_abc123', {
  amount: 1000,
  currency: 'USD',
  entry_type: 'credit',
  reason: 'Refund',
  // No idempotency_key
});

// RIGHT
await client.customers.wallets.ledgerEntries.create('cus_abc123', {
  amount: 1000,
  currency: 'USD',
  entry_type: 'credit',
  reason: 'Refund',
  idempotency_key: 'refund_order_12345_v1',
});
```

**Exposing portal links publicly.** Portal sessions are time-bound and tied to a customer ID. Don't log them or share them in URLs; generate them server-side and redirect immediately.

**Confusing wallets with credits.** Wallets hold real money (USD, INR). Credits are usage-based entitlements. See the `credit-based-billing` skill for credit management.

## Resources

- [Customer Management](https://docs.dodopayments.com/features/customers)
- [Customer Portal](https://docs.dodopayments.com/features/customer-portal)
- [Customer Wallets](https://docs.dodopayments.com/features/customer-wallet)
- [Customers API Reference](https://docs.dodopayments.com/api-reference/customers)

© dodopayments · MIT · dodopayments/skills

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

Все скиллы по теме «Бэкенд и API» →
signals-scout-customer-analytics-billing-and-usage PostHog Скилл signals-scout-customer-analytics-billing-and-usage для Claude Code отслеживает изменения использования продуктов и прогнозного MRR в отдельных аккаунтах, выявляя сдвиги при стабильном общем показателе. CX Codex +1 149установок aws-billing-and-cost-management aws Скилл aws-billing-and-cost-management анализирует расходы в AWS, ищет резервы экономии и настраивает бюджеты. Помогает проверить аномалии цен, оценить Savings Plans и снизить затраты на инфраструктуру. CX Codex +1 10 300установок subscription-management claude-office-skills Скилл subscription-management для Claude Code управляет жизненным циклом SaaS-подписок: биллингом, сменой тарифов, удержанием и выручкой. Проектирует сценарии подписки. CX Codex +1 5 200установок azure-cost-management MicrosoftDocs Помогает настроить работу с биллингом Azure, бюджетами и выгрузкой в Storage. Запускается при интеграции с Azure Cost Management API. CX Codex +1 222установок windsurf-license-management Jeremy Longshore Скилл windsurf-license-management ведёт учёт лицензий Windsurf: инвентаризация мест, правила распределения, отчёты по расходам и для аудита. CX Codex +1 1установок AWS Billing and Cost Management awslabs MCP-сервер, через который агент читает данные AWS Billing and Cost Management: расходы, бюджеты, аномалии, обязательства по скидкам и счета. CX Codex +1 ★ 9 939звёзд репо

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

Весь набор →
testing-and-go-live Скилл testing-and-go-live проводит платёжную интеграцию Dodo Payments через тестовый режим: карты, отказы, продления, вебхуки. И доводит до боевого запуска по чек-листу. CX Codex +1 219установок framework-adapters Скилл framework-adapters подключает официальные адаптеры Dodo Payments в Next.js, Express, Hono или Nuxt. Настраивает маршруты для чекаута, портала клиента и вебхуков. CX Codex +1 209установок refunds-and-disputes Скилл refunds-and-disputes обучает агента управлять возвратами и спорами в Dodo Payments. Помогает настроить вебхуки, частичные выплаты по позициям заказа и отзыв доступа у клиентов. CX Codex +1 208установок product-catalog-management Скилл product-catalog-management управляет каталогом Dodo Payments: создание разовых и регулярных тарифов, работа с аддонами и загрузка изображений. CX Codex +1 208установок discounts-and-promotions Скилл discounts-and-promotions помогает настроить промокоды Dodo Payments: создать скидку, проверить её ограничения и разобраться, почему код не применяется. CX Codex +1 199установок localized-pricing Скилл localized-pricing помогает настроить мультивалютные расчёты в Dodo Payments: фиксированные региональные цены, конвертацию Adaptive Currency и скидки паритета покупательской способности (PPP). CX Codex +1 198установок mobile-checkout Скилл mobile-checkout помогает встроить оплату Dodo Payments в мобильные приложения на React Native, Flutter, iOS и Android через системный браузер. CX Codex +1 192установок better-auth-integration Скилл better-auth-integration для Claude Code связывает Better Auth с Dodo Payments: синхронизирует клиентов, запускает checkout и принимает проверенные вебхуки. CX Codex +1 192установок

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

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