# Polar

Selling software through [Polar](https://polar.sh), a **merchant of
record** with **benefits** (what a purchase grants: a license key, files, a
repository's access, or a feature of the program's own), from the back end
with no package. An [extension](../extensions/README.md): ordinary Mote in
`extensions/polar/`, over [`net.send`](data.md#netsend),
[`secret`](back-end.md#secrets), a [route](back-end.md#routes) for Polar's
events and a [`job fn`](back-end.md#later-job-fn) that does them. Back to the
[map](README.md).

As with [Paddle](paddle.md), Polar is the seller: it works out, collects and
remits the tax, sends the receipts and invoices, and pays the business out.
Totals here are **tax in** (`total`, `tax`); refunds are Polar's to make, and
may wait (`pending`).

```mote
use "pkg:polar/polar.mote"
use "pkg:polar/webhooks.mote"

// Told by an event that an order was paid: give what was bought. Safe to run twice.
fn polarPaid(o: PolarOrder): bool
  Account.set(o.user, {plan: "pro"})?
  return true

server fn mayExport(): bool requires signedIn
  return polarCan(auth.me()?.id ?? "", env("EXPORT_BENEFIT"))?

column gap=8 padding=16
  PolarButton product="d9c1…" label="Go Pro, $12 a month"
  button "Manage my plan" press=polarManageGo
```

```toml
[packages]
polar = "../mote/extensions/polar"
```

```sh
POLAR_TOKEN=polar_oat_… POLAR_WEBHOOK_SECRET=… POLAR_PRODUCTS=<product id> bun dist/server/main.js
```

**None of this has met the real Polar.** Every call was written from
Polar's API reference (`/v1`) and run against a stand-in that speaks its
shape (`tests/svc_standin.mjs polar`). The steps to check it in Polar's
sandbox are [below](#checking-it-in-polars-sandbox).

## The settings

| | |
|---|---|
| `POLAR_TOKEN` | An organization access token (`polar_oat_…`; Settings → Developers). A secret. |
| `POLAR_LIVE` | `1` for the live API (`api.polar.sh`). Unset: the sandbox (`sandbox-api.polar.sh`, its tokens made at `sandbox.polar.sh`). |
| `POLAR_WEBHOOK_SECRET` | With `webhooks.mote`: the endpoint's secret, as Polar shows it. A secret. |
| `POLAR_PRODUCTS` | The products `polarBuy` and `PolarButton` may sell (their ids), with commas between; or the program's own `fn polarSells(product: string): bool`. |
| `POLAR_API` | Another address for the API: a stand-in, in tests. |

**No idempotency key.** Polar keeps none: a write is made once and never
tried again by itself (a read is, on 429 and 5xx, after `Retry-After`); a
write with no answer fails `kind "offline"` with words that say it may have
been done. A customer is found by its `external_id` (the program's account)
before one is made.

## The calls

Money is in the currency's smallest unit; moments are milliseconds.

| Call | Gives |
|---|---|
| `polarProducts()` · `polarProductGet(id)` | `PolarProduct`s (every page): `recurring`, `interval`, the first price's `amount` and `currency`. Products and their benefits are made in Polar's dashboard. |
| `polarCustomerFor(user, email)` · `polarCustomerByUser(user)` | The customer whose `external_id` is the account: found, else made. (An address Polar has for a customer without that id is refused, `kind "invalid"`, `err.data.field` `email`.) |
| `polarCheckout({products, user?, email?, success, discount?, metadata?})` | A `PolarCheckout`: send the buyer to `.url`, Polar's page. `user` goes as `customer_external_id`, so the customer Polar makes or finds is the account's; `{CHECKOUT_ID}` in `success` is the checkout's id. |
| `polarCheckoutGet(id)` · `polarCheckoutLink(products, success, label)` | The checkout again; a checkout link, an address that stays (a pricing page, a mail), each visit a checkout of its own. |
| `polarSubscriptionGet(id)` · `polarSubscriptions(customer, all)` | A `PolarSubscription`: `status`, `user`, `product`, `amount`, `interval`, `periodEnd`, `cancelAtPeriodEnd`, `canceledAt`, `endedAt`. |
| `polarChange(id, product, proration)` | Another product; `"prorate"` (the difference on the next invoice) or `"invoice"` (now). |
| `polarCancel(id)` · `polarKeep(id)` · `polarRevoke(id)` | Cancels at the period's end; takes that back; ends it now, and its benefits (no refund is made by it). |
| `polarOrderGet(id)` · `polarOrders(customer)` · `polarInvoice(order)` | A `PolarOrder`: `status`, `reason` (`purchase`, `subscription_create`, `subscription_cycle`, …), `total` with tax, `tax`, `refunded`; its invoice's address. |
| `polarRefund(order, amount, reason, revoke)` | A `PolarRefund` of that many cents (0: what is left of it); `revoke`: its benefits go too. |
| `polarPortal(user)` | The address of Polar's customer portal for the account: orders, invoices, subscriptions, the card, cancelling. |
| `polarGranted(user)` | The benefits the account is granted now, as Polar says (its customer state). |

For a page: `polarBuy(product, back)` and `polarManage()` (`server fn`s,
`requires signedIn`), the actions `polarGo(product)` and `polarManageGo`,
and `PolarButton product= label=`. `back` is an address of the site's own;
anything else is its first page.

Failures: a sentence (Polar's `detail`; for a 422, the first field and its
message) and a kind: `"invalid"` (`err.data.field`, `products.0`), `"auth"`,
`"missing"`, `"conflict"`, `"limited"`, `"polar"` (5xx), `"offline"`.

## Events: webhooks.mote

`POST /polar/webhook` checks the signature as **Standard Webhooks** sign
(Polar's way): `webhook-signature` holds `v1,<base64>` signatures, each an
HMAC-SHA256 of `<webhook-id>.<webhook-timestamp>.<the body as sent>`, under
the endpoint's secret taken as its UTF-8 bytes; a timestamp more than five
minutes from now is refused. The check is the runtime's
[`webhook.check(…, "polar", …)`](back-end.md#webhooks), the one copy of
that scheme (Resend's and Replicate's events go through it too). Polar's
secret is handed to it as `whsec_` and the secret's bytes in base64
(`polarKey`).

Each event is kept once by its `webhook-id` (`PolarEvent`), answered at
once, and done in `job fn polarDeliver`:

| Event | |
|---|---|
| `order.paid` | `fn polarPaid(o: PolarOrder): bool`: give what was bought (`o.user` is the account). |
| `order.refunded` | `fn polarRefunded(o: PolarOrder): bool`. |
| `subscription.*` | The subscription is **read again from Polar** into `PolarSubscriptionKept`, then `fn polarSubscriptionChanged(s)`. |
| `benefit_grant.*`, `customer.state_changed` | The account's granted benefits are **read again** (its customer state) into `PolarGrant`, then `fn polarGrantsChanged(user)`. |
| every event | `fn polarEvent(e: PolarEventSeen)`. |

`polarActive(user, product)` is whether the account has a subscription
that is `active`, `trialing` or `past_due`; **`polarCan(user, benefit)`** is
whether it is granted that benefit now: both read the rows, which the events
keep, never Polar on each page. At Polar: Settings → Webhooks → an
endpoint at `https://<the site>/polar/webhook`, format Raw, with the events
above; its secret is `POLAR_WEBHOOK_SECRET`.

## Checking it in Polar's sandbox

1. At `sandbox.polar.sh`: an organization; Settings → Developers, an
   access token; Products, a monthly product with a Custom benefit (copy
   both ids).
2. Settings → Webhooks: an endpoint at `https://<tunnel>/polar/webhook`
   (Raw), all events; copy its secret.
3. Start with `POLAR_TOKEN=… POLAR_WEBHOOK_SECRET=… POLAR_PRODUCTS=<id>`,
   sign in, press `PolarButton`, pay with `4242 4242 4242 4242`.
4. The endpoint's deliveries show `order.paid`, `subscription.created`,
   `benefit_grant.created` answered 200; `polarPaid` ran once,
   `polarActive` and `polarCan(user, <benefit id>)` are true. Redeliver
   one: `again: true`.
5. `polarChange` to a yearly product (`"prorate"`), `polarCancel` then
   `polarKeep`, `polarRevoke`: `benefit_grant.revoked` arrives and
   `polarCan` is false.
6. `polarRefund(order, 0, "", false)`: a refund in the dashboard;
   `order.refunded` reaches `polarRefunded`. `polarPortal(user)` opens the
   portal.

What to look for: whether the subscription and the order carry `customer`
with its `external_id` (read from there), the customer state's
`granted_benefits` (`benefit_id`, `benefit_type`), and the exact 422 shape
(`detail` as a list of `{loc, msg}`), all written from the reference.

Why there is no one `billing` facade over Stripe, PayPal, Paddle and Polar:
see [paypal.md](paypal.md#stripe-paypal-and-a-merchant-of-record-why-there-is-no-one-billing-facade).

Recorded in `tests/expect/real_svc_polar.txt` (`tests/all.sh
real_svc_polar`): the shop of `tests/svc_polar/app.mote` against the
stand-in, then the extension's own `mote test`
(`extensions/polar/tests.mote`).
