# Add Cycle subscriptions to an app

Cycle bills customers on a schedule and the money goes straight to the business's own Armenian bank account. You integrate it over plain HTTPS: there is no SDK to install. Base URL: `https://cycle.am/api/v1`. Full reference: the reference below, and https://cycle.am/docs/ai.

Work in **test mode** only. You can't touch real money: going live is a step the business takes in the Cycle dashboard, and the same code then works with live keys.

## 1. Look before you ask

Read the project first: the language and framework, where users are stored, how routes, background jobs and environment variables work, and whether any billing exists already. Then tell the user in two or three lines what you found and what you will add.

## 2. Ask what is theirs to decide

Ask these in plain words, each with the suggested default, and write the answers down (for example in a comment next to the billing code). Don't guess them.

1. **Plans**: names, prices, currency (AMD, USD or EUR), monthly or yearly, and any free trial in days. Amounts in AMD are whole dram.
2. **Failed renewals**: when a renewal fails, Cycle retries the card 1, 3 and 5 days after each failure (about 9 days in all; the business can change this under Recovery). Should the customer keep access meanwhile? *Suggested: keep access and show a notice asking them to update their card.*
3. **After the last retry**: Cycle then cancels the subscription (or pauses it, if the business chose that under Recovery). *Suggested: end access when `subscription.canceled` arrives.*
4. **Cancelling**: customers cancel themselves in the customer portal and keep what they paid for until the period ends; `subscription.canceled` arrives then. *Suggested: keep access until that event.*

## 3. Connect the account (one click for the user)

1. `POST https://cycle.am/api/v1/connect` with JSON `{"client_name": "<your name, e.g. Claude Code>"}`. The answer has `device_code` (secret: never show it), `user_code` (like `BKTW-7K4P`), `verification_url_complete`, `interval` and `expires_in`.
2. Show the user the `user_code`, open `verification_url_complete` in their browser (`open` on macOS, `xdg-open` on Linux, `start` on Windows), and ask them to check the code matches and press **Allow**. They may need to sign in or create a free account first.
3. Every `interval` seconds, `POST https://cycle.am/api/v1/connect/token` with `{"device_code": "…"}`. A 400 with `error: authorization_pending` means keep waiting; `slow_down` means wait longer; `access_denied` or `expired_token` means stop and tell the user. A 200 returns `secret_key` (a test key, `sk_test_…`), `business.name` and `api_base`.
4. Save the key **on the server only**: `CYCLE_SECRET_KEY` in the project's local environment file, which must be git-ignored. Never put it in browser code, in git or in your messages. Also save `CYCLE_API_BASE=https://cycle.am/api/v1`.

If the user prefers, they can instead create a test secret key under **Developers → Keys & webhooks** in the dashboard and paste it into the environment file themselves.

Every request: `Authorization: Bearer $CYCLE_SECRET_KEY`, `Accept: application/json`, JSON bodies. Send an `Idempotency-Key` header (a fresh UUID per action) on writes, so a retry never creates something twice.

## 4. Create the plans

`POST /products` with the product and its first price, then `POST /prices` for more prices of the same product (for example yearly):

```json
{"name": "Pro", "amount": 1290000, "currency": "AMD", "interval": "month", "trial_days": 14}
```

Amounts are in **minor units** (100 = 1 dram, 1 dollar or 1 euro). Store the returned price IDs (`price_…`) in configuration, not in code that runs in the browser.

## 5. Add the Subscribe button

On the server, when a signed-in user clicks Subscribe:

1. `POST /checkout/sessions` with `price`, `customer_email` (the user's email), `client_reference_id` (your user's ID) and `success_url` (for example `https://app.example/billing/success?session={CHECKOUT_SESSION_ID}`; Cycle fills in the ID).
2. Redirect the user to the `url` in the answer. They type their card on their bank's secure page; **never build a card form in the app**.
3. On the success page, `GET /checkout/sessions/{id}`: `status` is `completed` once paid (or once the card is saved, for a trial). Show a confirmation, but let the webhook below grant access, so access stays right even if the user closes the tab.

## 6. Keep access in step with payments (webhooks)

1. Add a route that receives `POST` requests, reads the **raw** body and verifies the `Cycle-Signature` header before anything else (how: the reference below, "Webhooks"). Reject a bad signature with 400.
2. Register it: `POST /webhook-endpoints` with `url` (public `https://` only) and `events`. Save the returned `secret` (shown once) as `CYCLE_WEBHOOK_SECRET`.
3. Handle at least:
   - `checkout.session.completed`: link `client_reference_id` (your user) to `customer` and `subscription`, and turn access on.
   - `subscription.updated`: plan changes, renewals, a cancellation scheduled for the period end.
   - `subscription.past_due` and `payment.failed`: apply the user's answer to question 2 (for example, show the notice).
   - `subscription.recovered`: hide the notice.
   - `subscription.canceled`: end access.
4. Answer `200` quickly, do slow work in a background job, and process each event `id` once (deliveries can repeat or arrive out of order; when order matters, read the subscription with `GET /subscriptions/{id}`).

Cycle can't reach `localhost`. For local testing, use a public tunnel URL if the user has one, or read the events with `GET /events` and feed them to the same handler.

## 7. Add "Manage subscription"

When the user clicks it, `POST /customers/{customer}/portal-links` and redirect to the returned `url` (valid for an hour; make a new one per click, never email or store it). In the portal the customer changes their card, switches plan or cancels, as the business's portal settings allow.

## 8. Prove it works, in test mode

Run each case, check what the app shows and which events arrived, and report a short list of what passed and what didn't. Test cards are in the reference below; any future expiry date and any CVC work, and the 3-D Secure code is `111111`.

1. Subscribe with `4242 4242 4242 4242`: the session completes and access turns on.
2. Subscribe with `4000 0000 0000 0002`: the bank page declines it and nothing turns on.
3. A plan with a trial: the card is saved, nothing is charged, the subscription is `trialing`.
4. A renewal: `POST /test/subscriptions/{id}/renew` charges the next period now (test keys only).
5. A failing renewal: subscribe with `4000 0000 0000 0341` (the first payment works, later charges fail), then renew: `subscription.past_due` and `payment.failed` arrive and the app applies question 2.
6. Recovery: in the portal, change that customer's card to `4242 4242 4242 4242`, then renew again: `subscription.recovered`.
7. Cancel in the portal: access stays until the period ends, then `subscription.canceled` ends it.
8. A forged webhook (wrong signature) gets 400; a real one gets 200.

## 9. Finish

Tell the user what you added, where, and how to try it. Remind them that real payments start only after they connect their bank and go live in the Cycle dashboard; then they create **live** keys there, put them in the production environment and register the production webhook URL. You can't do those steps, and shouldn't try.


---

# Cycle API reference for integrations

Base URL `https://cycle.am/api/v1`. Authenticate with `Authorization: Bearer sk_test_…` (test) or `sk_live_…` (live). Keys belong to one business and one mode. Full docs: https://cycle.am/docs/ai.

## Conventions

- JSON in and out; send `Accept: application/json`.
- Amounts are integers in minor units (100 = 1 dram, dollar or euro). AMD amounts are whole dram (multiples of 100).
- IDs are strings with a prefix: `prod_`, `price_`, `cus_`, `sub_`, `cs_` (checkout session), `pay_`, `in_`, `evt_`, `we_`.
- Writes accept an `Idempotency-Key` header: repeating a request with the same key returns the first answer.
- Lists are paginated with `?page=` and `?limit=` (up to 100) and return `{"data": [...], "links": {...}, "meta": {...}}`; single objects return `{"data": {...}}`.
- Errors: `422` with `{"message", "errors": {"field": ["…"]}}` for invalid input, `401` for a bad key, `403` for a missing scope or a test helper called with a live key, `404` for an ID in another business or mode, `429` when rate limited (100 requests a minute per key).

## Endpoints

| Method and path | What it does |
| --- | --- |
| `POST /products` | Create a product: `name`, `description`, and optionally its first price (the price fields below). |
| `GET /products`, `GET /products/{id}` | List or read products, with their prices. |
| `POST /prices` | Add a price: `product`, `amount`, `currency` (`AMD`, `USD`, `EUR`), `type` (`recurring` default, or `one_time`), `interval` (`day`, `week`, `month`, `year`), `interval_count` (default 1), `trial_days` (default 0), `nickname`. |
| `GET /prices`, `GET /prices/{id}` | List or read prices (`?product=`, `?active=`). |
| `POST /checkout/sessions` | Open a checkout: `price`, `customer_email`, `success_url` (may contain `{CHECKOUT_SESSION_ID}`; https in live mode), `client_reference_id` (your user ID), `locale` (`hy` or `en`). Redirect the customer to `url`. A recurring price starts a subscription; with a trial the card is saved and nothing is charged yet. A one-time price is a single payment. |
| `GET /checkout/sessions/{id}` | Read a session: `status` (`open`, `completed`, `failed`, `expired`), `customer`, `subscription`, `payment`, `client_reference_id`. An open session is checked with the bank first. |
| `POST /customers` / `PATCH /customers/{id}` | Create or update a customer: `email`, `name`, `phone`, `locale`, `metadata`. Checkout creates customers for you. |
| `GET /customers`, `GET /customers/{id}` | List (`?email=`) or read customers. |
| `POST /customers/{id}/portal-links` | A one-hour sign-in link to the customer portal (`url`). Optional `locale`. |
| `POST /subscriptions` | Start a subscription for a customer who already has a saved card: `customer`, `price`, optional `trial_days`, `quantity`, `coupon`. |
| `GET /subscriptions`, `GET /subscriptions/{id}` | List (`?customer=`, `?status=`) or read subscriptions. `status`: `trialing`, `active`, `past_due`, `paused`, `canceled`, `incomplete`, `scheduled`. |
| `POST /subscriptions/{id}/cancel` | Cancel at the period end (default) or now (`"at_period_end": false`). |
| `GET /payments`, `GET /payments/{id}` | Payments. |
| `POST /payments/{id}/refunds` | Refund all or part of a payment: `amount`, `reason`. |
| `GET /invoices`, `GET /invoices/{id}` | Invoices. |
| `GET /events`, `GET /events/{id}` | Events, newest first (`?type=`), for catching up after downtime or for local testing. |
| `POST /webhook-endpoints` | Register a webhook URL: `url` (public https), `events` (a list, or `["*"]`), `description`. Returns `secret` once. |
| `GET /webhook-endpoints`, `DELETE /webhook-endpoints/{id}` | List or delete endpoints. |
| `POST /test/subscriptions/{id}/renew` | Test keys only: run the next renewal now (a trial ends, a period renews, a past-due subscription gets its next retry). The outcome follows the saved test card. |

Connecting an app (no key needed; see `SKILL.md`, step 3): `POST /connect` with `client_name`, then poll `POST /connect/token` with `device_code` every `interval` seconds.

## Webhooks

Cycle sends `POST` requests with the event as JSON:

```json
{"id": "evt_…", "object": "event", "type": "subscription.past_due", "livemode": false, "created_at": "2026-11-12T09:31:02+00:00", "data": {"object": {"id": "sub_…", "object": "subscription"}}}
```

`data.object` is the object as the API returns it. Headers include `Cycle-Event-Id`, `Cycle-Event-Type` and `Cycle-Signature: t=<unix time>,v1=<signature>`.

**Verify every request.** The signature is the hex HMAC-SHA256 of `<t>.<raw body>` with the endpoint's secret (`whsec_…`). Recompute it from the raw body (before JSON parsing), compare in constant time, and reject timestamps more than 300 seconds old.

Node.js:

```js
import crypto from 'node:crypto';

export function verifyCycleSignature(rawBody, header, secret) {
    const parts = Object.fromEntries(header.split(',').map((part) => part.split('=')));
    const expected = crypto.createHmac('sha256', secret).update(`${parts.t}.${rawBody}`).digest('hex');
    const fresh = Math.abs(Date.now() / 1000 - Number(parts.t)) <= 300;

    return fresh && crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(parts.v1 ?? ''));
}
```

PHP:

```php
function verifyCycleSignature(string $rawBody, string $header, string $secret): bool
{
    parse_str(str_replace(',', '&', $header), $parts);
    $expected = hash_hmac('sha256', ($parts['t'] ?? '').'.'.$rawBody, $secret);

    return hash_equals($expected, $parts['v1'] ?? '') && abs(time() - (int) ($parts['t'] ?? 0)) <= 300;
}
```

Python:

```python
import hashlib, hmac, time

def verify_cycle_signature(raw_body: bytes, header: str, secret: str) -> bool:
    parts = dict(part.split("=", 1) for part in header.split(","))
    expected = hmac.new(secret.encode(), f"{parts.get('t', '')}.".encode() + raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, parts.get("v1", "")) and abs(time.time() - int(parts.get("t", 0))) <= 300
```

Answer with a `2xx` within 10 seconds. Failed deliveries are retried for about a day. Event types:

- `customer.created`: A customer was created (dashboard, checkout or API).
- `customer.updated`: A customer's details or default card changed.
- `customer.deleted`: A customer was deleted.
- `subscription.created`: A subscription was created.
- `subscription.updated`: A subscription changed: renewed, paused, resumed, set to cancel, plan or discount changed.
- `subscription.past_due`: A renewal failed and the subscription is waiting for a retry.
- `subscription.recovered`: A past-due subscription was paid and is active again.
- `subscription.canceled`: A subscription ended.
- `checkout.session.completed`: A customer finished a checkout: paid, or saved a card for a trial. Carries your client_reference_id.
- `payment.succeeded`: A card payment succeeded.
- `payment.failed`: A card payment was declined.
- `payment.needs_review`: The bank couldn't confirm a charge for a long time: check it in your bank's portal and record what happened.
- `refund.succeeded`: A payment was refunded, in full or in part.
- `invoice.finalized`: An invoice got its number and can be paid.
- `invoice.paid`: An invoice was paid.
- `invoice.voided`: An invoice was voided.
- `invoice.uncollectible`: An invoice was closed after the last failed retry.
- `dispute.opened`: A customer disputed a payment with their bank (a chargeback).
- `dispute.closed`: The bank decided a dispute: won or lost.

## Test cards (test mode)

Any future expiry and any CVC. The 3-D Secure code is `111111`.

| Card | Brand | What happens |
| --- | --- | --- |
| `4242 4242 4242 4242` | Visa | Approves, including later renewals |
| `5555 5555 5555 4444` | Mastercard | Approves (Mastercard) |
| `9051 0000 0000 0003` | ArCa | Approves (ArCa) |
| `4000 0000 0000 0002` | Visa | Declined: card declined |
| `4000 0000 0000 9995` | Visa | Declined: insufficient funds |
| `4000 0000 0000 0069` | Visa | Declined: expired card |
| `4000 0000 0000 3220` | Visa | Requires 3-D Secure (code 111111), including on renewals |
| `4000 0000 0000 0341` | Visa | First payment approves; later charges of the saved card fail |
| `4000 0000 0000 0119` | Visa | First payment approves; later charges go through but the bank's reply is lost (the follow-up check finds them) |
