# A payment provider of your own

Bring a provider OrbCart does not ship. One module in your Worker and one line in defineCommerce.

Stripe, Adyen, Mollie, PAYONE, PayPal and Amazon Pay are built in. A provider OrbCart does not
ship, such as a regional bank method, is a module in your Worker: you write the calls to its API,
OrbCart keeps deciding what a Payment is.

<Callout type="warn">
This seam is a preview. Its shape may still change before the first release.
</Callout>

## Name it in the Worker

```ts title="src/worker.ts"
import { defineCommerce } from "@orbcart/runtime";
import { acme } from "./payments/acme";

export default defineCommerce({
  paymentProviders: { acme },
  channels: {
    de: {
      currency: "EUR",
      pricesIncludeTax: true,
      locale: "de-DE",
      payments: { card: "stripe", pay_by_bank: "acme" },
      returnUrl: "https://nordgrat.de/checkout/return",
      origins: ["https://nordgrat.de"],
    },
  },
  offers: (lines, { currency }) => pricing.offers(lines, { currency }),
});
```

- The name is yours: lower case, and not a built-in provider's. It is also the path of the
  provider's webhook: `/webhooks/acme`.
- A Channel maps a method to it like to any provider. The method names stay OrbCart's list;
  a provider carries the ones it knows.
- The Worker does not start in `test` or `live` while a binding the provider requires is
  missing. A local Worker leaves the provider's methods out instead.
- Keep the provider in `paymentProviders` while one of its Payments is unresolved or can still
  be refunded, even after no Channel maps to it.

## Write the provider

A provider is a factory: the bindings it needs, and `open`, which returns the provider with the
credentials they hold.

```ts title="src/payments/acme.ts"
import { z } from "zod";
import {
  Duration,
  Instant,
  PaymentId,
  unknownMovement,
  unknownObservation,
} from "@orbcart/runtime/payment";
import type {
  ObservedPaymentState,
  PaymentMethodCapabilities,
  PaymentProviderFactory,
  ProviderMovement,
} from "@orbcart/runtime/payment";

type AcmeEnv = { readonly ACME_API_KEY: string; readonly ACME_WEBHOOK_SECRET: string };

/** The buyer pays on Acme's page, Acme confirms by message, and you capture when you ship. */
const bankRedirect: PaymentMethodCapabilities = {
  flow: "redirect",
  outcome: "async",
  capture: "separate",
  partialCapture: false,
  refund: "partial",
  requires: [],
  needs: [],
};

const AcmePayment = z.object({
  id: z.string(),
  status: z.enum(["open", "declined", "authorized", "captured", "failed", "canceled"]),
  reference: z.string(),
  checkoutUrl: z.string().optional(),
});
const AcmeMessage = z.object({ id: z.string(), created: z.number(), payment: AcmePayment });

export const acme: PaymentProviderFactory<AcmeEnv> = {
  requires: ["ACME_API_KEY", "ACME_WEBHOOK_SECRET"],
  open(env) {
    /** One call to Acme; `undefined` when it gave no usable answer, which is never a refusal. */
    async function call(path: string, body: object, idempotencyKey: string) {
      try {
        const response = await fetch(`https://api.acme.example${path}`, {
          method: "POST",
          headers: {
            authorization: `Bearer ${env.ACME_API_KEY}`,
            "content-type": "application/json",
            "idempotency-key": idempotencyKey,
          },
          body: JSON.stringify(body),
          signal: AbortSignal.timeout(10_000),
        });

        return AcmePayment.safeParse(await response.json()).data;
      } catch {
        return undefined;
      }
    }

    return {
      methods: new Map([["pay_by_bank", bankRedirect]]),
      keyRetention: Duration.minutes(24 * 60),
      browserSetup: () => ({}),

      async start({ payment, idempotencyKey, returnUrl }) {
        const created = await call(
          "/payments",
          { amount: payment.amount, reference: payment.id, returnUrl },
          idempotencyKey,
        );
        if (!created) return unknownObservation("start_unanswered");
        if (created.status === "declined" || !created.checkoutUrl) {
          return { outcome: "refused", providerFacts: { status: created.status } };
        }

        return {
          outcome: "known",
          providerReference: created.id,
          state: {
            status: "requires_action",
            action: { type: "redirect", url: created.checkoutUrl },
          },
          providerFacts: { status: created.status },
        };
      },

      capture: async ({ payment, amount, idempotencyKey }) =>
        movementOf(
          await call(`/payments/${payment.providerReference}/capture`, { amount }, idempotencyKey),
        ),

      refund: async ({ payment, refund, amount, idempotencyKey }) =>
        movementOf(
          await call(
            `/payments/${payment.providerReference}/refunds`,
            { amount, reference: refund },
            idempotencyKey,
          ),
        ),

      cancel: async ({ payment, idempotencyKey }) =>
        movementOf(await call(`/payments/${payment.providerReference}/cancel`, {}, idempotencyKey)),

      async webhook({ headers, body }) {
        const signature = headers.get("acme-signature") ?? "";
        if (!(await signedByAcme(signature, body, env.ACME_WEBHOOK_SECRET))) {
          return { status: "signature_invalid" };
        }
        const message = messageIn(body);
        const state = message && stateOf(message.payment.status);
        if (!message || !state) return { status: "payload_invalid" };
        const payment = PaymentId.parse(message.payment.reference);

        return {
          status: "verified",
          events: [
            {
              id: message.id,
              type: `payment.${message.payment.status}`,
              ...(payment && { payment }),
              createdAt: Instant.from(message.created * 1000),
              observation: {
                outcome: "known",
                providerReference: message.payment.id,
                state,
                providerFacts: { status: message.payment.status },
              },
              // What support sees of the message.
              document: {
                id: message.id,
                payment: message.payment.id,
                status: message.payment.status,
              },
            },
          ],
        };
      },
    };
  },
};

function messageIn(body: string) {
  try {
    return AcmeMessage.safeParse(JSON.parse(body)).data;
  } catch {
    return undefined;
  }
}

function movementOf(moved: z.output<typeof AcmePayment> | undefined): ProviderMovement {
  if (!moved) return unknownMovement("unanswered");
  const providerFacts = { status: moved.status };

  return moved.status === "failed" || moved.status === "declined"
    ? { outcome: "failed", providerFacts }
    : { outcome: "succeeded", providerReference: moved.id, providerFacts };
}

function stateOf(status: z.output<typeof AcmePayment>["status"]): ObservedPaymentState | undefined {
  switch (status) {
    case "authorized":
    case "captured":
    case "canceled":
      return { status };
    case "failed":
    case "declined":
      return { status: "failed", reason: "declined" };
    case "open":
      return undefined;
  }
}

/** Acme signs the untouched body with HMAC-SHA256, as base64. */
async function signedByAcme(signature: string, body: string, secret: string): Promise<boolean> {
  const encoder = new TextEncoder();
  const key = await crypto.subtle.importKey(
    "raw",
    encoder.encode(secret),
    { name: "HMAC", hash: "SHA-256" },
    false,
    ["verify"],
  );
  try {
    return await crypto.subtle.verify(
      "HMAC",
      key,
      Uint8Array.fromBase64(signature),
      encoder.encode(body),
    );
  } catch {
    return false;
  }
}
```

## What OrbCart keeps

The provider reports. It never decides.

| You report                                  | OrbCart does                                                              |
| ------------------------------------------- | ------------------------------------------------------------------------- |
| A state, from `start` or a message          | Moves the Payment forward only. A late, older report changes nothing.     |
| An amount other than the Quote's            | Refuses it and has it refunded.                                           |
| `unknown`, when a call got no usable answer | Keeps the Cart locked and asks again. It never guesses failed or paid.    |
| A capture or refund                         | Bounds refunds by what was captured and derives the Order's state.        |
| A message                                   | Stores it before it answers 200, and recognizes a redelivery by its `id`. |

Three duties are yours:

- **Send the key.** Every changing call carries `idempotencyKey`, derived from OrbCart's own IDs.
  A retry sends the same key, so pass it to the provider. `keyRetention` says how long the
  provider keeps it.
- **Answer `unknown` when you cannot tell.** A timeout or an unreadable answer is
  `unknownObservation()` or `unknownMovement()`, never a failure: the provider may have booked.
- **Verify the message.** `webhook` gets the headers and the untouched body. Check the signature
  before you read anything else.

Every answer of your provider is checked before it reaches a Payment. One that is not what the
seam promises counts as `unknown`, and a message that does not parse is not stored, so the
provider delivers it again.

<Callout>
A provider is code with your API keys in the path of every purchase. OrbCart limits what a wrong
answer can do, it cannot remove it: test the provider through your own Worker, as
[Testing](/docs/shop/testing) shows with a fake at the fetch boundary.
</Callout>

## In the browser

If the provider takes the buyer to its own page, the storefront does nothing. A method whose
`flow` is `redirect` is mounted like PayPal: `accept` sends the buyer to the provider's page and
`cart.resume()` takes over when they return.

Only a provider whose field sits on your page needs a browser component. Register it once, before
the checkout mounts, with `registerPaymentComponent` from `@orbcart/client/payment`.

## Not yet

- New method names. A provider carries methods from OrbCart's list.
- Express buttons and wallets of your own provider.