# subly > Subscription billing in Israeli shekels (ILS) for apps built with AI: plans, trials, automatic renewals, failed-payment retries, and an invoice on every charge. Add-on: prepaid credits and usage metering for apps with paid AI calls. Works on top of Israeli clearing companies. Card details never touch your server or ours. Status: MVP. Test mode always uses sandbox payments and sandbox invoices. Live mode charges through the account's own Pelecard terminal, once the account owner has entered its credentials. Money amounts are integer agorot (100 agorot = ₪1). Credits are integers. ## Subscriptions in 4 steps 1. Sign up (see step 1 below) and create a plan once: `POST /v1/plans {"name": "Pro", "price_agorot": 9900, "interval": "month", "trial_days": 14}`. 2. On login: `POST /v1/customers {"external_id": "", "email": "..."}`. 3. Subscribe button: `POST /v1/subscriptions {"customer_id", "plan_id", "success_url", "cancel_url"}` → `{url}`. Redirect the user there: it is the payment page in your branding (a summary with the exact terms, then the clearing company's card form inside the same screen, then the verified result). The link is valid 24 hours and opens a fresh card form on every visit; you do not need payment pages of your own. "Back to the app" on it goes to `success_url` (paid) or `cancel_url`. With a trial the page saves the card without charging. Or embed it (see "Components"). 4. Before every paid feature: `GET /v1/customers/{id}/access` → `{has_access, status, current_period_end, cancel_at_period_end}`. Cache it briefly or keep it in sync with webhooks. Renewals are charged automatically from the saved card. A failed renewal becomes `past_due` (access continues) and is retried after 1, 3 and 5 days, then `canceled`. Cancel: `POST /v1/subscriptions/{id}/cancel` (default: at period end; `{"at_period_end": false}` to end now). Undo: `POST /v1/subscriptions/{id}/resume`. ## What your customers see (no UI to build) All of it is in your branding (Settings > Branding: name, logo, one colour, support email, and `app_url` for "back to the app"), Hebrew, right to left, built for phones. The word subly appears only in the line "התשלום מאובטח על ידי subly" (with subly's small logo) under payment screens and in emails about a charge that went through. Customer screens live on a neutral host (`SUBLY_CUSTOMER_BASE_URL`), never on your domain and never on the API's. - Payment page: `url` from `POST /v1/subscriptions` (`/pay/{token}`). The outcome is never taken from the browser: the return page reads our records, which only the clearing company's confirmed callback changes. - Personal area: `/portal/{account_id}` in live, `/portal/{account_id}.test` in test (a fixed address; print it on your site as "ניהול המינוי וביטול"). The customer signs in with an email code; no password. From your app, skip the code: `POST /v1/portal-links {"customer_id", "target"?: "home"|"card"|"cancel", "return_url"?}` → `{url}` (one use, 10 minutes; redirect at once). From the dashboard the same call gives a 24-hour link to send by hand. There the customer sees the plan and next charge, changes the card (a failed renewal is charged right after), downloads documents, cancels (at the period end; immediately after a failed charge) and resumes. - Customer emails these screens trigger (subscription started, trial started, cancellation scheduled, resumed, ended, card replaced, payment received again) go out in your name. In test they go to the account owner only, subject starting with "[בדיקות]". ## Components (embed in your app) Three components: `pricing` (your active plans, monthly/yearly; a plan's button opens checkout in place), `checkout` (one plan: summary, card form, result), `portal` (subscription management). They are iframes on our customer host, in your branding; cancel, the disclosure and the security line cannot be removed. 1. Server (secret key, never in the browser): `POST /v1/component-sessions {"customer_id", "origin": "https://your.app", "return_url"?}` → `{token, expires_at, script_url}`. One customer, 60 minutes, this environment only. `origin` is the only page allowed to frame the components. In live it is required and must be https (400 `origin_required` / `https_required` otherwise); in test it may be left out for local work. 2. Page: ```html
``` Or `const c = Subly.mount('#billing', { component: 'portal', session: token, onEvent: (e) => … })`; `c.destroy()` removes it. 3. Events (`onEvent`, or a `subly:event` CustomEvent on the element): `checkout.completed {subscription_id, status}`, `checkout.failed`, `checkout.canceled`, `subscription.canceled {subscription_id, immediate, ends_at}`, `payment_method.updated` / `payment_method.not_updated`. They are hints for the UI: grant access from `GET /v1/customers/{id}/access` or webhooks, never from an event in the browser. 4. Expired session: the component says it did not load; ask your server for a new token and mount again. ## Credits (add-on for AI usage) in 4 steps 1. Keys: a person opens the account in the dashboard (`/app/signup`, email code or Google / GitHub) and creates a key in Developers > API keys; add a webhook endpoint with `POST /v1/webhook-endpoints {"url"}` (returns its `secret`). Store both as secrets. (`POST /v1/signup` is closed unless the server runs with `SUBLY_ALLOW_OPEN_SIGNUP=1`, for local development.) 2. Create a package once: `POST /v1/packages {"name": "100 credits", "credits": 100, "price_agorot": 4900}`. 3. On login: `POST /v1/customers {"external_id": "", "email": "..."}` (upsert; safe to repeat). Anywhere a customer id is expected you may pass your own user id. 4. Around every paid AI call: - `POST /v1/authorize {"customer_id", "credits"}` → `{allowed, balance}`. If not allowed, send the user to checkout. - Make the AI call. - `POST /v1/usage {"customer_id", "credits", "idempotency_key"}` → `{balance}`. Returns 402 `insufficient_credits` if the balance is too low. Use a stable request id as idempotency_key so retries never double-charge. Buying credits: `POST /v1/checkout {"customer_id", "package_id", "success_url", "cancel_url"}` → `{url}`. Redirect the user to `url` (hosted payment page). Credits are added when payment succeeds; a `credits.purchased` webhook follows. Auto top-up: `PUT /v1/customers/{id}/auto-topup {"low_balance_threshold": 20, "package_id": "pkg_..."}` charges the saved card when the balance drops below the threshold. ## Payment outcomes A payment is `pending`, `succeeded` or `failed`, and leaves `pending` once. Only the clearing company's server-to-server message, confirmed with the clearing company, decides it; the shopper's way back (through `/pay/{id}/return`, then to your success_url or cancel_url) never does. When the clearing company gives no clear answer (a timeout, an error), the payment stays `pending` with `verification_status: "pending"` and is checked again automatically; it is never treated as failed and never retried, so a card is not charged twice. If it still cannot be confirmed, `verification_status` becomes `needs_review` and a `payment.needs_review` event is sent: check the transaction in the clearing company's terminal. A second successful charge on the same payment (a payment page paid twice) is never counted and sends `payment.needs_refund` with `reason: "duplicate_transaction"` (or `"paid_after_failure"`). `provider_txn_id` is the clearing company's transaction id. ## Auth `Authorization: Bearer sk_test_...` on every /v1 request. Keys are for apps and agents; people sign in to the dashboard with an email code (session cookie), never with a key. An account has up to 10 working keys per environment, each with a name. Two kinds: app keys (`sk_test_...`, for the app's server) and agent keys (`sk_test_agent_...`, for an AI agent or CLI without a browser), so activity can tell the app from the agent. A revoked key, or an old key 24 hours after it was rolled, gets 401 with a message saying what to do. ### Done by a signed-in person only A key lives on a server and can leak, so these are done only by a person signed in to the dashboard, never with any key (test or live, app or agent): listing, creating, renaming, rolling and revoking API keys (Developers > API keys); changing the business details (Settings > Business); connecting, checking, replacing or disconnecting the Pelecard terminal (Settings > Payments) and BillOS (Settings > Invoices); activation; showing or rolling a live webhook signing secret. An app key gets 403 `session_required`, an agent key 403 `forbidden_for_agent`, and the attempt appears in the account's activity as blocked. Reading their state stays open to the app's key (never a secret): `GET /v1/providers/pelecard/credentials`, `GET /v1/settings/business`, `GET /v1/settings/invoices`. When you meet one of these, tell the user which dashboard page does it; do not look for another way. ### Test and live Test and live are separate worlds: customers, plans, subscriptions, payments, events and webhook endpoints of one are never seen from the other. A key works in its own environment (`sk_test_…` / `sk_live_…`). Live exists only after a person activates the account in the dashboard (/activate); before that, live keys cannot be created. A key never reaches into the other environment: a test key cannot read or change live settings (`?env=live`); that answers 403 `wrong_environment`. Live keys are made by a person in the dashboard. Ids differ between environments: after activation the app needs the live plan ids. A 404 for an id that exists in the other environment says so (`error.env`, `error.exists_in`): do not retry, use the right key. ### Agent keys in live, and approvals A live agent key is read-only unless the owner allows "changes, with approvals". Then creating plans, customers and payment links, renaming plans and cancelling at the end of the period run at once; an immediate cancellation and adding, changing or deleting a webhook endpoint answer **202** `{"status": "pending_approval", "approval_id", "approval_url", "expires_at", "message"}`. That is not an error: tell the user, give them `approval_url`, and do not retry or look for another way. Send your reason in the `Subly-Reason` header (URL-encoded) or a `reason` body field; it is shown to the owner as your words, under the facts the server writes. Read the result with `GET /v1/approvals/{id}` (`pending` · `approved` with `outcome` · `rejected` with `decision_note` · `expired`); withdraw your own request with `POST /v1/approvals/{id}/cancel`. Only a signed-in person approves; an approval written in a chat is not one. Everything else that changes data in live (keys, payment and invoicing details, activation, usage) is 403 `forbidden_for_agent` and appears in the account's activity as blocked. ### Rate limits Every answer over a limit is **429** `rate_limited` with a `Retry-After` header (seconds) and `error.retry_after_seconds`: wait that long, then retry the same request (with the same idempotency key). Never retry in a tight loop. The limits, per minute: 1200 requests per API key; 3000 requests with a key from one address; 600 requests without a key (the dashboard) from one address; 120 Pelecard messages from one address; 600 requests to the customer screens (/pay, /portal, /embed) from one address. The sign-in codes keep their own, stricter limits. ## Webhooks POST JSON `{id, type, created_at, data}` with header `Subly-Signature: t=,v1=." with the endpoint's secret>`. During a secret roll the header carries two `v1` values (new and old secret, for 24 hours): accept the event if ANY `v1` matches. Every event has `livemode` (false in test, true in live): check it, and keep a separate secret for each environment's endpoint. Verify against the RAW body and reject timestamps older than 5 minutes. Retries with backoff for ~35 hours on non-2xx (after 1 min, 5 min, 30 min, 2 h, 8 h, 24 h). Respond 2xx within 10 seconds; dedupe on `id` (a resend keeps the same id). Test events from the dashboard carry `"test": true`. Type `ping` is only ever a test event (sent when the owner checks the live endpoint during activation): it is not about any customer; answer 2xx and do nothing else. An account can have several endpoints (`POST /v1/webhook-endpoints {"url", "events": null | ["subscription.created", ...]}` → returns the endpoint with its `secret`; store it as SUBLY_WEBHOOK_SECRET). The URL must be public: its host name is resolved (DNS) when the endpoint is set and again before every send, and if any address it resolves to is local or private (loopback, private networks, link-local, the cloud metadata address, their IPv6 forms) it is refused (400 `unreachable_url`; a name that does not resolve: 400 `unresolvable_url`) and nothing is sent. The connection goes to the address that was checked. During local development, forward events with a tunnel; a server started with `SUBLY_WEBHOOK_ALLOW_LOCALHOST=1` (never in production) also accepts `localhost` endpoints in test. Signing secrets: in test, `GET /v1/webhook-endpoints/{id}` includes `secret`. In live it is returned once, when the endpoint is added; after that the detail has `secret_hidden: true` and no `secret`, and `GET /v1/merchant` has no `webhook_secret`. The account owner shows it on the endpoint's page in the dashboard (it asks for a fresh sign-in code if the last sign-in is older than 15 minutes) and puts it in the server's .env. Every event goes to every enabled endpoint that takes its type. An endpoint whose deliveries all fail for 24 hours is `failing`; after 5 days without one success it is disabled automatically (`auto_disabled`): new events are kept as "not sent" (`skipped`) and can be resent after it is enabled again. `PATCH /v1/merchant {webhook_url}` and `merchant.webhook_url`/`webhook_secret` still work and refer to the first (oldest) endpoint (`webhook_secret` in test only). Types: `subscription.created`, `subscription.renewed`, `subscription.past_due`, `subscription.canceled`, `subscription.updated`, `payment.succeeded`, `payment.failed`, `payment.needs_refund`, `payment.needs_review`, `credits.purchased`, `balance.low`, `invoice.issued`, `customer.payment_method_updated` (the customer replaced the card in the personal area: `{customer_id, subscription_id, card_last4, by}`). ## Endpoints - POST /v1/signup (only with SUBLY_ALLOW_OPEN_SIGNUP=1, local development; otherwise 403 `signup_closed`) - GET /v1/merchant, PATCH /v1/merchant {webhook_url} (edits the first webhook endpoint; null deletes it) - GET /v1/connection (what is connected: last use of the app key and agent keys, and the five setup steps) - GET /v1/api-keys, POST /v1/api-keys {name, kind: "app"|"agent", env?}, PATCH /v1/api-keys/{id} {name}, POST /v1/api-keys/{id}/revoke, POST /v1/api-keys/{id}/roll {revoke_old_now?}. A signed-in person in the dashboard only: every key gets 403. - GET /v1/providers/pelecard/credentials (status; never the password; not for agent keys). PUT /v1/providers/pelecard/credentials, POST /v1/providers/pelecard/check, DELETE /v1/providers/pelecard/credentials: a signed-in person in the dashboard only. Used in live mode only. - GET /v1/settings/business, GET /v1/settings/invoices (state, no secrets). PUT /v1/settings/business, PUT /v1/settings/invoices, POST /v1/settings/invoices/check, DELETE /v1/settings/invoices: a signed-in person in the dashboard only. - GET /v1/webhook-endpoints, POST /v1/webhook-endpoints {url, description?, events?}, GET /v1/webhook-endpoints/{id}, PATCH /v1/webhook-endpoints/{id} {url?, description?, events?, enabled?}, DELETE /v1/webhook-endpoints/{id} - POST /v1/webhook-endpoints/{id}/reveal-secret → {secret} and POST /v1/webhook-endpoints/{id}/roll-secret {revoke_old_now?}: not for agent keys; in live a signed-in person with a sign-in from the last 15 minutes only (403 `session_required` for keys, 403 `reauth_required` for an older sign-in). POST /v1/webhook-endpoints/{id}/test {type?} → {ok, response_status, duration_ms, response_body}, POST /v1/webhook-endpoints/{id}/resend-unsent - GET /v1/webhook-endpoints/{id}/deliveries?status=failed|delivered|pending|skipped, POST /v1/webhook-deliveries/{id}/resend - POST /v1/plans, GET /v1/plans (active only; `?include_archived=1` for all), GET /v1/plans/{id} - PATCH /v1/plans/{id} {name, description} always; {price_agorot, interval, trial_days} only while the plan has no subscriptions (else 409 plan_in_use) - POST /v1/plans/{id}/archive, POST /v1/plans/{id}/unarchive (an archived plan takes no new subscriptions: 409 plan_archived; existing ones keep renewing) - POST /v1/subscriptions, GET /v1/subscriptions?customer_id=|plan_id=, GET /v1/subscriptions/{id} - POST /v1/subscriptions/{id}/cancel, POST /v1/subscriptions/{id}/resume - GET /v1/customers/{id}/access - POST /v1/portal-links {customer_id, target?, return_url?} → {url, expires_at, single_use} - POST /v1/component-sessions {customer_id, origin (required in live, https), return_url?} → {token, expires_at, script_url} - POST /v1/packages, GET /v1/packages - POST /v1/customers, GET /v1/customers, GET /v1/customers/{id} - PUT /v1/customers/{id}/auto-topup - GET /v1/customers/{id}/ledger - POST /v1/authorize - POST /v1/usage (idempotency_key in body or `Idempotency-Key` header) - POST /v1/checkout - GET /v1/payments/{id} - GET /v1/events?type=a,b&object_id=sub_…&status=failed&limit=50&starting_after=evt_… (newest first; object_id matches any id in the event data) - GET /v1/events/{id} (with each delivery and its attempts), POST /v1/events/{id}/resend {endpoint_id?} - GET /v1/dashboard (includes `subly_billing`: {signups_blocked, past_due, signups_block_at}) - GET /v1/billing (the account's own subly bill: tier, revenue this month, next charge or free during launch, card last4, invoices, blocked status), POST /v1/billing/payment-method → {url} (a hosted page that saves the card, and pays any open amount). People only. Errors: `{"error": {"code", "message"}}`. Codes: unauthorized (401), forbidden_for_agent (403), invalid_request (400), invalid_url (400), invalid_events (400), not_found (404), insufficient_credits (402), idempotency_conflict (409), already_subscribed (409), plan_in_use (409), plan_archived (409), key_limit (409), key_already_rolled (409), endpoint_exists (409), endpoint_limit (409), endpoint_disabled (409), no_endpoint (409), provider_not_configured (409, live mode without Pelecard credentials), live_not_activated (409, live before the account is activated), agent_read_only / agent_paused / agents_paused (403), wrong_environment (403, a key used for the other environment), session_required (403, done by a signed-in person in the dashboard only), reauth_required (403, the person signs in again in the dashboard), rate_limited (429, wait `Retry-After` seconds), unreachable_url (400, a webhook URL that is or resolves to a private or local address), unresolvable_url (400, its host name does not resolve), origin_required (400, a live component session without origin), https_required (400), maintenance (503, with `until` when known; wait until then), internal_error (500, with `incident_id`: before repeating anything that moves money, read its state first), pelecard_credentials_rejected (400), encryption_not_configured (503, the server cannot store credentials), provider_unavailable (502), provider_error (502), signups_blocked (403 on POST /v1/checkout and POST /v1/subscriptions when the account's subly bill is 14+ days past due; renewals and everything else keep working; show your user `error.user_message`, "ההרשמה לא זמינה כרגע"). ## TypeScript SDK ```ts import { Subly, SublyError, constructWebhookEvent } from 'subly'; // sdk/index.ts in this repo const subly = new Subly({ apiKey: process.env.SUBLY_API_KEY!, baseUrl: process.env.SUBLY_BASE_URL }); ``` ## Rules for AI agents integrating subly - Gate paid features on `has_access` from the server, never on a flag stored in the browser. - Do not activate anything on the success_url page. Activation happens when the payment succeeds; the page only re-reads state. - Never put the API key or webhook secret in client-side code. All calls are server-side. The browser gets only a component session token, and only for embedding. - Do not build your own payment, cancel or card-change pages: send the customer to the payment `url`, a portal link, or embed a component. They already follow the Israeli disclosure and cancellation rules. - Always send idempotency_key on usage, derived from the request, not random per retry. - Record usage after the AI call succeeds; do not charge for failed calls. - Verify webhook signatures on the raw body before trusting them, accepting any of the `v1` values. - No key, not even the app's own, can create, roll or list keys, change the business details, or connect, replace or disconnect the Pelecard terminal or BillOS; a live signing secret is shown only in the dashboard. Ask the account owner to do it there and to put the values in the project's .env. - On 429, wait `Retry-After` seconds and retry once with the same idempotency key; do not loop.