# Paddle

Selling through [Paddle Billing](https://developer.paddle.com), a
**merchant of record**, from the back end with no package. An
[extension](../extensions/README.md): ordinary Mote in
`extensions/paddle/`, over [`net.send`](data.md#netsend),
[`secret`](back-end.md#secrets), a [route](back-end.md#routes) for Paddle's
events and a [`job fn`](back-end.md#later-job-fn) that does them. Back to the
[map](README.md).

**Why a product picks a merchant of record.** With Stripe or
[PayPal](paypal.md) the program's business is the seller: it registers for
and remits sales tax and VAT wherever it sells, and answers for each sale.
With Paddle, Paddle is the seller: it works out the tax at the checkout,
collects and remits it, sends the receipts and invoices in its own name,
handles the buyer's questions and chargebacks, and pays the business out.
That is worth its higher fee to a small product selling worldwide. What it
means here: **prices are said with or without tax as Paddle is set up, the
total of a transaction includes the tax Paddle worked out** (`total`,
`tax`); **a refund is a request** (an adjustment) that Paddle approves or
rejects (`pending_approval` first); and the buyer's details belong to
Paddle's checkout, which this extension sends the buyer to.

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

// Told by an event that a transaction was paid and processed: give what was bought.
fn paddlePaid(t: PaddleTransaction): bool
  Account.set(t.user, {plan: "pro"})?
  return true

server fn pro(): bool requires signedIn
  return paddleActive(auth.me()?.id ?? "", "")?

column gap=8 padding=16
  PaddleButton price="pri_01h…" label="Go Pro, $12 a month"
  button "Manage my plan" press=paddleManageGo
```

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

```sh
PADDLE_KEY=pdl_sdbx_apikey_… PADDLE_WEBHOOK_SECRET=pdl_ntfset_… PADDLE_PRICES=pri_… bun dist/server/main.js
```

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

## The settings

| | |
|---|---|
| `PADDLE_KEY` | The API key (`pdl_sdbx_apikey_…` in the sandbox, `pdl_live_apikey_…` live). A secret. |
| `PADDLE_LIVE` | `1` for the live API (`api.paddle.com`). Unset: the sandbox (`sandbox-api.paddle.com`). |
| `PADDLE_WEBHOOK_SECRET` | With `webhooks.mote`: the notification destination's secret key (`pdl_ntfset_…`). A secret. |
| `PADDLE_WEBHOOK_TOLERANCE` | How old a signature may be, in seconds: 300 unsaid (Paddle's own libraries take 5; the clocks of a back end and Paddle's are seldom that close). |
| `PADDLE_PRICES` | The prices `paddleBuy` and `PaddleButton` may sell, with commas between; or the program's own `fn paddleSells(price: string): bool`. |
| `PADDLE_CHECKOUT` | The address of the checkout page a transaction is paid at, if not the "default payment link" set in Paddle's dashboard. |
| `PADDLE_API` | Another address for the API: a stand-in, in tests. |

**The checkout page.** A transaction's `checkout` is the default payment
link set in Paddle's dashboard (Checkout → Checkout settings) with
`?_ptxn=<the transaction>`. That page is the program's own, and it opens
Paddle's checkout with Paddle.js, a script of Paddle's: this extension does
not write it (a page of one line of `extern script`, [js.md](js.md), does),
and has not checked whether Paddle's newer hosted checkouts, which need no
page of the program's, take a transaction made here.

**No idempotency key.** Paddle keeps none: a write (`POST`, `PATCH`) 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. What a write made is kept by the program:
`paddleCustomerFor` finds the customer Paddle already has for an address
(Paddle refuses a second one, `customer_already_exists`).

## The calls

Money is in the currency's smallest unit (Paddle writes it as text,
`"1200"`); moments are milliseconds.

| Call | Gives |
|---|---|
| `paddleProducts()` · `paddlePrices(product)` · `paddlePriceGet(id)` | `PaddleProduct` (`taxCategory`), `PaddlePrice` (`amount`, `currency`, `interval`, `frequency`, a trial's `trialInterval` and `trialFrequency`). Every page. |
| `paddleCustomerFor(user, email)` · `paddleCustomerGet(id)` · `paddleUserOf(customer)` | The Paddle customer of an account (`PaddleLink`), made once or found. |
| `paddleCheckout({items, customer?, user?, discount?})` | A `PaddleTransaction`, `ready`: send the buyer to `.checkout`. `user` goes as `custom_data.user`, on the transaction and on the subscription it makes. |
| `paddleTransactionGet(id)` · `paddleInvoice(id)` | The transaction (`status`, `total` with tax, `tax`, `subscription`, `invoice`); the address of a paid one's invoice PDF (Paddle's, for an hour). |
| `paddleSubscriptionGet(id)` · `paddleSubscriptions(customer)` | A `PaddleSubscription`: `status`, `items` (and the first's `price`, `product`, `quantity`), `periodEnd`, `nextBilled`, a waiting `scheduled` change and `scheduledAt`, Paddle's pages `updateCard` and `cancelPage`. |
| `paddleChange(id, items, proration)` · `paddlePreview(id, items, proration)` | Other items (the whole list as it is to be), billed `"prorated_immediately"`, `"prorated_next_billing_period"`, `"full_immediately"`, `"full_next_billing_period"` or `"do_not_bill"`; the preview says what would be charged `now` (a credit is negative) and on the `next` bill, without changing anything. |
| `paddleCancel(id, atEnd)` · `paddleKeep(id)` | Cancels at the period's end or now; takes back a cancel (or pause) still waiting. |
| `paddlePause(id, atEnd, resumeAt)` · `paddleResume(id)` | Pauses now or at the period's end, until a moment (0: until resumed); resumes. |
| `paddleRefund(transaction, reason)` | A `PaddleAdjustment` for the whole of a completed transaction, `pending_approval` until Paddle decides. |
| `paddlePortal(customer, subscriptions)` | The address of Paddle's customer portal: payments, the card, cancelling. |

For a page: `paddleBuy(price)` and `paddleManage()` (`server fn`s,
`requires signedIn`), the actions `paddleGo(price)` and `paddleManageGo`,
and `PaddleButton price= label=`.

Failures: a sentence (Paddle's `detail`, and the first field's message) and
a kind: `"invalid"` (`err.data.field`), `"auth"`, `"conflict"`,
`"limited"`, `"paddle"` (5xx), `"offline"`; `err.data` is `{status, type,
code, field, request}` (`request`: Paddle's request id).

## Events: webhooks.mote

`POST /paddle/webhook` checks the `Paddle-Signature` header (`ts=<seconds>;
h1=<hex>`: an HMAC-SHA256, under `PADDLE_WEBHOOK_SECRET`, of `<ts>:<the
body as it was sent>`, compared in constant time with each `h1` by
[`webhook.check`](back-end.md#webhooks)'s `"paddle"`, two while a
key is rotated; a `ts` too far from now is a replay), keeps each event once
by its `event_id` (`PaddleEvent`), answers at once and does it in `job fn
paddleDeliver`:

| Event | |
|---|---|
| `transaction.completed` | `fn paddlePaid(t: PaddleTransaction): bool`: paid, and Paddle has done its part. The account in `custom_data.user` is linked to the customer. |
| `transaction.payment_failed` | `fn paddlePaymentFailed(t)`. |
| `subscription.*` | The subscription is **read again from Paddle** into `PaddleSubscriptionKept`, then `fn paddleSubscriptionChanged(s)`. |
| `adjustment.*` | `fn paddleAdjusted(a: PaddleAdjustment)`: a refund made, approved, rejected. |
| every event | `fn paddleEvent(e: PaddleEventSeen)`. |

`paddleActive(user, product)` is whether the account has a subscription
that is `active`, `trialing` or `past_due` (Paddle is still trying the
card, and ends it if every try fails). At Paddle: Developer Tools →
Notifications → a destination at `https://<the site>/paddle/webhook`, with
the events above; its secret key is `PADDLE_WEBHOOK_SECRET`.

## Checking it in Paddle's sandbox

1. At `sandbox-vendors.paddle.com`: Developer Tools → Authentication, make
   an API key; Catalog → Products, a product with a monthly price (copy
   `pri_…`); Checkout → Checkout settings, a default payment link (a page of
   yours that loads Paddle.js, or the address Paddle suggests).
2. Developer Tools → Notifications: a destination at
   `https://<tunnel>/paddle/webhook`, all events; copy its secret key.
3. Start with `PADDLE_KEY=… PADDLE_WEBHOOK_SECRET=… PADDLE_PRICES=pri_…`,
   sign in, press `PaddleButton`; pay with Paddle's test card `4242 4242
   4242 4242` (any future date, CVC 100).
4. In Notifications → the destination's log: `transaction.completed`,
   `subscription.created` answered 200; `paddlePaid` ran once and
   `paddleActive` is true. Replay one from the log: `again: true`.
5. `paddlePreview` then `paddleChange` to the yearly price with
   `prorated_immediately`: the preview's `now` matches the transaction
   Paddle makes. `paddleCancel(id, true)`, then `paddleKeep(id)`.
6. `paddleRefund(transaction, "test")`: an adjustment `pending_approval`;
   approve it in the dashboard; `adjustment.updated` reaches `paddleAdjusted`.

What to look for: where the totals are (`details.totals.grand_total` and
`.tax` are read), the preview's `update_summary` (its `result.action` and
`amount` were written from the reference, not seen), and whether
subscriptions carry the transaction's `custom_data` (if not, the account
comes from the customer linked at `transaction.completed`).

Why there is no one `billing` facade over Stripe, PayPal and Paddle: 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_paddle.txt` (`tests/all.sh
real_svc_paddle`): the shop of `tests/svc_paddle/app.mote` against the
stand-in, then the extension's own `mote test`
(`extensions/paddle/tests.mote`).
