# PayPal

Taking payments and subscriptions with [PayPal](https://developer.paypal.com),
from the back end, with no package and no script of PayPal's in the page.
An [extension](../extensions/README.md): ordinary Mote in
`extensions/paypal/`, over [`net.send`](data.md#netsend) (JSON, a
`PayPal-Request-Id` on every write, tries again on 429 and 5xx),
[`secret`](back-end.md#secrets), a [route](back-end.md#routes) for PayPal's
events, and a [`job fn`](back-end.md#later-job-fn) that does them. Back to
the [map](README.md).

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

model Order
  item: string
  cents: number
  by: id = me
  paid: bool = false
  read if by == me

// The buyer is sent to PayPal to approve; the amount is the program's own, never the page's.
server fn payWithPaypal(order: id): string requires signedIn
  let o = Order.get(order)?
  if o == none fail("no such order")?
  let made = paypalOrder({amount: o.cents, currency: "USD", description: o.item, user: `${auth.me()?.id}`, ref: `${o.id}`, back: `${route.origin}/paid`, cancel: `${route.origin}/cart`, key: `order-${o.id}`})?
  return made.approve

// Back from PayPal at /paid?token=<the order>: the money is taken (once, however often this runs).
server fn paypalBackHere(token: string): string requires signedIn
  let o = paypalCapture(token) else err => fail(err.kind == "declined" ? "PayPal refused that way of paying: choose another." : `${err}`)?
  return o.captureStatus

// Told by an event that money was captured: give what was bought. Safe to run twice.
fn paypalPaid(c: PaypalCapture): bool
  Order.set(c.ref, {paid: true})?
  return true
```

```toml
# mote.toml, beside the entry
[packages]
paypal = "../mote/extensions/paypal"
```

```sh
PAYPAL_CLIENT_ID=… PAYPAL_SECRET=… PAYPAL_WEBHOOK_ID=… bun dist/server/main.js   # the sandbox
PAYPAL_LIVE=1 PAYPAL_CLIENT_ID=… PAYPAL_SECRET=… PAYPAL_WEBHOOK_ID=… bun dist/server/main.js
```

**None of this has met the real PayPal.** Every call was written from
PayPal's REST reference (Orders v2, Payments v2, Subscriptions v1, Payouts
v1, Notifications v1) and run against a stand-in that speaks its shape
(`tests/svc_standin.mjs paypal`): the token, what was sent, the request ids,
refusals, and events signed as PayPal signs them and checked by the
stand-in's own verify call. The steps to check it against PayPal's sandbox
are [below](#checking-it-against-paypals-sandbox).

## The settings

| | |
|---|---|
| `PAYPAL_CLIENT_ID` | The REST app's client id (Developer Dashboard → Apps & Credentials). |
| `PAYPAL_SECRET` | Its secret. A [`secret`](back-end.md#secrets): the back end does not start without it, and the log never holds it (nor the token got with it). |
| `PAYPAL_LIVE` | `1` for the live API (`api-m.paypal.com`). Unset: the sandbox (`api-m.sandbox.paypal.com`), so nothing is charged by a forgotten setting. |
| `PAYPAL_WEBHOOK_ID` | With `webhooks.mote`: the id PayPal gave the webhook (the app's page → Webhooks). It is part of what PayPal signs. |
| `PAYPAL_VERIFY` | Unset: PayPal's verify call checks each event. `cert`: each event's signature is checked here, by PayPal's certificate ([below](#events-webhooksmote)). |
| `PAYPAL_CAPTURE_ON_APPROVAL` | `0`: an approved order is left to the page to capture. Unset: the event captures it, for a buyer who never came back. |
| `PAYPAL_PLANS` | The plans `paypalStart` and `PaypalButton` may begin, with commas between (`P-…`). Or the program's own `fn paypalSells(plan: string): bool`. |
| `PAYPAL_API` | Another address for the API: a stand-in, in tests. |

**The token.** Each call is made with an access token got from
`/v1/oauth2/token` (client credentials, the id and secret as Basic), kept
in a row (`PaypalToken`, its value `hidden`) until a minute before it ends,
and got again once if PayPal answers 401 to it.

## The calls

Plain fns of the back end's, each typed, each able to fail. **Money is in
the currency's smallest unit** (cents), as in the Stripe extension; PayPal's
decimal text (`"45.00"`, `"4500"` for yen) is written and read here.

| Call | Gives |
|---|---|
| `paypalOrder({amount, currency, description?, user?, ref?, back, cancel, intent?, brand?, key?})` | A `PaypalOrder`: send the buyer to `.approve`, PayPal's page. `user` goes as `custom_id` and comes back on the capture and its events; `ref` (`invoice_id`) is the program's own name for it, and PayPal refuses a second order paid with the same one. PayPal sends the buyer back to `back` with `?token=<the order's id>&PayerID=…`. `intent`: `"CAPTURE"` (unsaid) or `"AUTHORIZE"`. |
| `paypalCapture(order)` | Takes the money of an approved order: a `PaypalOrder` with `capture` and `captureStatus` (`COMPLETED`, or `PENDING` with a reason). Its request id is the order's, so the page's capture and the event's are one; one captured already is read again and given. A refused way of paying is `kind "declined"`, `err.data.approve` where to send the buyer to choose another. |
| `paypalOrderGet(id)` | The order again. |
| `paypalAuthorize(order)` · `paypalTake(authorization, amount, currency, final, key)` · `paypalVoid(authorization)` | Money held, then taken (all, `amount` 0, or part; `final`: the last time), or let go. |
| `paypalCaptureGet(id)` | A `PaypalCapture`. |
| `paypalRefund(capture, amount, currency, note, key)` | A `PaypalRefund`: all (`amount` 0) or that many cents. `key` names it: asked twice, one refund. |
| `paypalPlans(product)` · `paypalPlanGet(id)` | `PaypalPlan`s (every page): the regular cycle's `amount`, `currency`, `interval` (`MONTH`…), `intervalCount`, and whether there is a `trial`. Plans are made in PayPal's dashboard. |
| `paypalSubscribe({plan, user?, email?, quantity?, back, cancel, brand?, key?})` | A `PaypalSubscription` waiting for approval: send the buyer to `.approve`. |
| `paypalSubscriptionGet(id)` | `status` (`APPROVAL_PENDING`, `ACTIVE`, `SUSPENDED`, `CANCELLED`, `EXPIRED`), `user`, `nextBilling`, `lastPaid`, `lastAmount`, `failedPayments`. |
| `paypalCancel(id, reason)` · `paypalSuspend(id, reason)` · `paypalActivate(id, reason)` | The subscription, as it is after. One in that state already is no failure. PayPal has no "cancel at the period's end": what was paid for runs to `nextBilling`, and `paypalActive` counts it until then. |
| `paypalPayout(ref, subject, to)` · `paypalPayoutGet(id)` | Money sent to people by their PayPal address (`to`: `{email, amount, currency, note?, ref?}`); `ref` names the batch, and PayPal refuses a second batch of the same `ref` for 30 days. The app must have Payouts turned on at PayPal. |

For a page, whoever is signed in: `paypalStart(plan, back)` (a `server fn`,
`requires signedIn`, 20 a minute: a subscription to a plan the program
sells, PayPal's address), `paypalSubscribeGo(plan)` (an action that goes
there), and `PaypalButton plan= label=`. An order's amount is the program's
own business, so there is no "buy" `server fn`: write one, as above, that
reads the amount from the program's own data.

## When it fails

| Kind | |
|---|---|
| `"declined"` | The buyer's way of paying was refused (`INSTRUMENT_DECLINED`, `PAYER_CANNOT_PAY`, …): send them to `err.data.approve` again. |
| `"invalid"` | PayPal did not take what was asked: `err.data.issue` (`ORDER_NOT_APPROVED`, `REFUND_AMOUNT_EXCEEDED`) and `err.data.field` say what. |
| `"auth"` | The client id or secret is wrong, or the app may not do this. |
| `"conflict"` | It was done already (`ORDER_ALREADY_CAPTURED`, `SUBSCRIPTION_STATUS_INVALID`, `DUPLICATE_INVOICE_ID`, `DUPLICATE_SENDER_BATCH_ID`). |
| `"limited"` | Too many requests, after the call's own tries. |
| `"paypal"` | PayPal broke (5xx), after the call's own tries. |
| `"offline"` | PayPal did not answer. |

`err.data` is `{status, name, issue, field, debug}`: `debug` is PayPal's
`debug_id`, which their support asks for. The sentence is PayPal's own
`description` where it gave one.

## Events: webhooks.mote

`use "pkg:paypal/webhooks.mote"` adds `POST /paypal/webhook`, which checks
the event, keeps it once by its id (`PaypalEvent`, in the same turn as
queuing its job), answers at once, and leaves the work to `job fn
paypalDeliver` (tried again eight times if a hook or a call fails).

**Checking that PayPal sent it**: PayPal is asked
(`POST /v1/notifications/verify-webhook-signature`, with the five
`paypal-*` headers, `PAYPAL_WEBHOOK_ID` and the event), and the event is
taken when it answers `SUCCESS`: one call for each event. PayPal works the
CRC-32 out over the event as it is sent to that call, which is the event
parsed and written again: a body whose JSON does not come back byte for
byte (a number written `1.50`) can be refused though PayPal sent it.

**Or by the certificate, with `PAYPAL_VERIFY=cert`**: no call to PayPal
but the certificate's fetch. What PayPal signs is
`<paypal-transmission-id>|<paypal-transmission-time>|<webhook id>|<the
CRC-32 of the body as it was sent, in decimal>`, with SHA256withRSA, the
signature in `paypal-transmission-sig` (base64), under the key of the
certificate at `paypal-cert-url`. That address is taken only from PayPal's
own API hosts (`https://api.paypal.com/`, `https://api.sandbox.paypal.com/`
and their `api-m.` names), since whoever posts an event picks it; the
certificate, fetched over HTTPS from there, is read by
[`crypto.cert`](data.md#signatures-with-a-key-pair), must be good at this
moment and made out to `messageverificationcerts.…` (PayPal's name for
them). The signature is checked over the body as it came, so the `1.50`
edge of the verify call is not there. Anything else is refused with a 400
and why. (The certificate is fetched for each event; nothing keeps it.)

An event is then applied:

| Event | |
|---|---|
| `CHECKOUT.ORDER.APPROVED` | An order of intent `CAPTURE` is captured (with the request id the page's capture uses), for the buyer who approved and never came back. `PAYPAL_CAPTURE_ON_APPROVAL=0` leaves it. |
| `PAYMENT.CAPTURE.COMPLETED` | `fn paypalPaid(c: PaypalCapture): bool`: give what was bought. |
| `PAYMENT.CAPTURE.DENIED`, `.DECLINED`, `.REVERSED` | `fn paypalNotPaid(c: PaypalCapture): bool`. |
| `PAYMENT.CAPTURE.REFUNDED` | `fn paypalRefunded(r: PaypalRefund): bool` (`capture` from the refund's `up` link). |
| `BILLING.SUBSCRIPTION.*`, `PAYMENT.SALE.COMPLETED` | The subscription is **read again from PayPal** (never taken from the event's copy: events come in any order) into `PaypalSubscriptionKept`, then `fn paypalSubscriptionChanged(s)`, or `fn paypalPaymentFailed(s)` for `BILLING.SUBSCRIPTION.PAYMENT.FAILED`. |
| every event | `fn paypalEvent(e: PaypalEventSeen): bool`, after the above. |

Each hook is a `wants fn` with a default; a hook's failure makes the job
fail and be tried again: **make each safe to run twice**.
`paypalActive(user, plan)` is whether an account has an `ACTIVE`
subscription (or a `CANCELLED` one whose paid time has not run out), read
from the rows; `paypalMine()` is a `server fn` that gives whoever asks
their rows. Events are kept a month.

At PayPal: the app's page → Webhooks → Add webhook, at
`https://<the site>/paypal/webhook`, with the events above (or all
events). Its id is `PAYPAL_WEBHOOK_ID`.

## Checking it against PayPal's sandbox

Ten minutes, with a PayPal developer account:

1. Developer Dashboard → Apps & Credentials, **Sandbox**: make an app; copy
   its client id and secret. Testing Tools → Sandbox Accounts lists a
   personal (buyer) account: note its address and password.
2. Expose the program (`cloudflared tunnel --url localhost:4870` or any
   tunnel), and in the app's Webhooks add `https://<tunnel>/paypal/webhook`
   with all events; copy the webhook's id.
3. Start it: `PAYPAL_CLIENT_ID=… PAYPAL_SECRET=… PAYPAL_WEBHOOK_ID=…`.
   Call `paypalOrder` for 1000 cents USD (the example above); open
   `.approve`, sign in as the sandbox buyer, approve. You come back to
   `back?token=…`; `paypalCapture(token)` gives `COMPLETED`.
4. In the dashboard's Event Logs (the webhook's page), see
   `CHECKOUT.ORDER.APPROVED` and `PAYMENT.CAPTURE.COMPLETED` delivered with
   200; `paypalPaid` ran once; capturing again gives the same capture.
5. Change one byte of a delivered body (saved from the log) and post it
   with the same headers: 400, `PayPal says the signature is not its own`.
6. `paypalRefund(capture, 300, "USD", "", "r1")` twice: one refund in the
   sandbox buyer's account; `PAYMENT.CAPTURE.REFUNDED` reaches
   `paypalRefunded`.
7. Make a product and a monthly plan (dashboard, or the Catalog Products and
   Plans APIs); `paypalSubscribe`, approve as the buyer:
   `BILLING.SUBSCRIPTION.ACTIVATED` arrives and `paypalActive` is true.
   `paypalCancel`: `CANCELLED`.
8. A declined capture: the sandbox's negative testing (an order with
   `PayPal-Mock-Response: {"mock_application_codes": "INSTRUMENT_DECLINED"}`,
   which this extension does not send: try it with `curl`) should come back
   as `kind "declined"`.
9. Start it again with `PAYPAL_VERIFY=cert`, and resend an event from the
   Event Logs: 200 with no call to `verify-webhook-signature`; the changed
   body of step 5: 400, `the signature is not PayPal's for this body and
   this webhook`. (The sandbox's certificate is the one to look at: its
   subject should be `CN=messageverificationcerts.sandbox.paypal.com` or
   like it; the check takes any `messageverificationcerts.` name.)

What to look for against the shapes here: where PayPal puts the payer
(`payer` and `payment_source.paypal`: both are read), whether
`next_billing_time` stays on a cancelled subscription (the row keeps the
last one it saw), and the exact `issue` names, which were written from
PayPal's error reference and the stand-in.

## Stripe, PayPal and a merchant of record: why there is no one billing facade

The three were written side by side, and no common `billing.*` fell out of
them, on purpose:

- **The nouns differ.** Stripe has customers, prices, subscriptions and
  invoices the program drives; PayPal has an order the buyer approves and the
  program then captures, and subscriptions to plans made in its dashboard;
  [Paddle](paddle.md) has transactions, and is itself the seller;
  [Polar](polar.md) has checkouts, orders and benefits granted to the buyer.
- **The lifecycles differ.** Stripe's Checkout is paid when the buyer
  leaves it; PayPal's order is only approved, and money moves at the
  capture, which the program must make (and which may come back
  `PENDING`). Stripe cancels at the period's end; PayPal cancels now and
  the paid time is the program's to honour.
- **Who owns tax and refunds differs.** With Stripe or PayPal the program
  (the seller) owes the tax and decides refunds; with a merchant of record
  the provider owes the tax, sends the receipts, and approves refunds.
- A facade would be the intersection (a one-off payment, a subscription,
  "is active"), and every product needs something outside it within a week
  (a trial, proration, a capture that is pending, a refund that waits for
  approval). Each extension instead names its own things plainly, and a
  program that offers two writes its own `fn proActive(user)` over
  `stripeActive` and `paypalActive`: three lines it can read.

## What is kept

| Model | |
|---|---|
| `PaypalToken` | The access token (`hidden`) and when it ends. |
| `PaypalEvent` | Each event once: `id`, `type`, `created`, `resource`, `state`. A month. |
| `PaypalSubscriptionKept` | Each subscription, as PayPal last said it. |

Recorded in `tests/expect/real_svc_paypal.txt` (`tests/all.sh
real_svc_paypal`): the shop of `tests/svc_paypal/app.mote` against the
stand-in, twice (checking events by PayPal's call; and set to
`PAYPAL_VERIFY=cert`, which checks each signature by the stand-in's certificate,
and refuses one signed for another webhook, a body changed on the way, a
certificate from another host and another alg): the
token and its refresh, orders captured once, declined, refunded, held and
let go, plans page by page, a subscription's states, a payout asked twice,
events signed, refused (signed for another webhook), sent twice, out of
order; then the
extension's own `mote test` (`extensions/paypal/tests.mote`).
