---
name: subly-billing
description: Add subscription billing in Israeli shekels (ILS) to a SaaS or AI app using subly — plans, free trials, automatic renewals, cancellation, Israeli invoices, and optional prepaid credits for paid AI calls. Use when the user wants to charge their users monthly/yearly, add a paywall or "pay in shekels", sell credits, or needs a Stripe alternative in Israel.
---

# Add subly billing

subly runs subscriptions (and optionally prepaid credits) for the app's end users and issues an invoice on every charge. All calls are server-side.

Full API reference: `<SUBLY_BASE_URL>/llms.txt`. SDK: `sdk/index.ts` in the subly repo.

## 1. Secrets

Ask the user for `SUBLY_API_KEY` (sk_test_...) and `SUBLY_WEBHOOK_SECRET`. The user opens the account in the dashboard (`/app/signup`, with an email code) and creates the key in Developers > API keys. Never ask the user for a sign-in code. Server env vars only. Never in client code, never committed.

Only the account owner, signed in to the dashboard, can do these; no key can (app keys get 403 `session_required`, agent keys 403 `forbidden_for_agent`): API keys, the business details, the Pelecard terminal, BillOS, activation. In live, the webhook signing secret is shown once when the endpoint is added, and after that only on the endpoint's page in the dashboard (it may ask the owner for a fresh sign-in code). Tell the user which page to open; do not look for a workaround.

## 2. Plans

Ask the user what they sell: plan names, monthly or yearly price, trial length. Create each plan once (`subly.plans.create`, price in agorot: ₪99 → 9900). Save the plan ids in config.

## 3. Customer

Where the app handles login, call `subly.customers.upsert({ external_id: user.id, email })`. From then on use the app's own user id as `customer_id`.

## 4. Subscribe button

Server route:

```ts
const { url } = await subly.subscriptions.start({ customer_id: user.id, plan_id, success_url, cancel_url });
return redirect(url);
```

`url` is the payment page in the app's branding (summary, card form, verified result). Do not build one. Do not mark the user as subscribed on `success_url`. That page only re-reads access.

Embedded instead of a redirect: create a component session on the server and mount it in the page.

```ts
const { token, script_url } = await subly.componentSessions.create({ customer_id: user.id, origin: 'https://your.app' });
// page: <script src={script_url}></script> <div data-subly-component="pricing" data-subly-session={token}></div>
```

`origin` is the app's own https page. In live it is required (400 `origin_required` without it) and the components load only there; read it from config, not from the request.

## 5. Paywall

Server-side, before every paid feature:

```ts
const { has_access } = await subly.access(user.id);
if (!has_access) return redirect('/pricing');
```

`past_due` still has access (payment retries are running). Show a banner asking to update the card.

## 6. Account page

Easiest: a "ניהול המינוי" button that sends the user to the personal area, signed in:

```ts
const { url } = await subly.portalLinks.create({ customer_id: user.id, return_url: 'https://your.app/account' });
return redirect(url); // one use, 10 minutes
```

Or embed it: `data-subly-component="portal"` with a component session (see step 4). The personal area has the card change, documents and cancel (two taps, never hidden). Building your own is possible with `subly.subscriptions.cancel(id)` / `resume(id)`, but the cancel button must stay as easy as the signup.

## 7. Webhooks

The endpoint URL must be public: a host that is or resolves to a local or private address is refused (400 `unreachable_url`). During local development, use a tunnel.

`POST /webhooks/subly`: read the RAW body, `constructWebhookEvent(rawBody, req.headers['subly-signature'], SUBLY_WEBHOOK_SECRET)`, return 200 fast, dedupe on `event.id`.
Useful: `subscription.past_due` → email "update your card"; `subscription.canceled` → downgrade; `payment.needs_refund` → alert the owner.

## 8. Optional: credits for AI usage

Only if each request has a real cost (model calls, SMS, transcription). Create packages (`subly.packages.create`), then around each paid call:

```ts
const { allowed } = await subly.authorize({ customer_id: user.id, credits: COST });
if (!allowed) return { error: 'insufficient_credits' };
const result = await callModel(input);          // charge only on success
await subly.usage.record({ customer_id: user.id, credits: COST, idempotency_key: requestId });
```

`requestId` must be stable across retries of the same user action.

## Rate limits

Over a limit the API answers 429 `rate_limited` with `Retry-After` (seconds; `SublyError.retryAfterSeconds` in the SDK). Wait, then retry the same request once with the same idempotency key. Never retry in a loop.

## Test it

The `url` from step 4 opens the test payment page: sample cards 4242 4242 4242 4242 (succeeds), 4000 0000 0000 0002 (declined), 4000 0000 0000 0077 (succeeds after a few seconds), 4000 0000 0000 0341 (succeeds, the next charge is declined). Check: access turns on, cancel works in the personal area (`/portal/<account_id>.test`), webhook verifies.

## Hebrew UI strings

מינוי · תוכנית · תקופת ניסיון · החיוב הבא ב-<date> · ביטול המינוי · המינוי יסתיים ב-<date> · המשך המינוי · ניהול המינוי · החיוב נכשל, יש לעדכן כרטיס · קרדיטים · יתרה · טעינת קרדיטים
