# Contracts in another system

Let your ERP, a Laravel shop or another Worker answer offers, stock, tax and order handoff, over HTTP or a Service Binding.

Every contract of OrbCart, [`offers`](/docs/integrate/offers), [`inventory`](/docs/integrate/inventory),
[`tax`](/docs/integrate/tax) and `deliverOrder`, is a function. It does not have to live in the
Worker of OrbCart. Attach an HTTP endpoint or another Worker instead, and OrbCart calls it with the
same arguments, the same time budget and the same rules for a wrong answer.

```ts title="src/worker.ts"
import { defineCommerce, http, service } from "@orbcart/runtime";

export default defineCommerce({
  channels,
  offers: service("PRICES"), // another Worker, through a Service Binding
  inventory: {
    check: http((vars) => vars.get("SHOP_URL") + "/commerce/stock"),
    reserve: http((vars) => vars.get("SHOP_URL") + "/commerce/reserve"),
    release: http((vars) => vars.get("SHOP_URL") + "/commerce/release"),
    commit: http((vars) => vars.get("SHOP_URL") + "/commerce/commit"),
    restock: http((vars) => vars.get("SHOP_URL") + "/commerce/restock"),
  },
  deliverOrder: http("https://middleware.nordgrat.de/edge/orders", { timeoutMs: 20_000 }),
});
```

An HTTP address follows the [rules of event endpoints](/docs/integrate/order-events#receive-events-over-http):
`https` on port 443, a name instead of an IP address, nothing private. A contract takes no `types`
and no `previews`, which belong to events. A preview environment calls an HTTP contract like every
other, so read its address from the deployment's variables if it should call something else.

## The call

Each call is a `POST` with `Content-Type: application/json`. The body names the arguments of the
contract and carries the `context`, as you know it from the function:

| Contract                 | Service Binding path       | Body                           |
| ------------------------ | -------------------------- | ------------------------------ |
| `offers`                 | `/offers`                  | `lines`, `context`             |
| `tax`                    | `/tax`                     | `draft`, `context`             |
| `shippingRates`          | `/shipping-rates`          | `request`, `context`           |
| `deliverOrder`           | `/deliver-order`           | `order`, `context`             |
| `pickupLocations`        | `/pickup-locations`        | `context`                      |
| `inventory.check`        | `/inventory/check`         | `references`, `context`        |
| `inventory.reserve`      | `/inventory/reserve`       | `hold`, `context`              |
| `inventory.release`      | `/inventory/release`       | `holdId`, `context`            |
| `inventory.commit`       | `/inventory/commit`        | `holdId`, `orderId`, `context` |
| `inventory.restock`      | `/inventory/restock`       | `restock`, `context`           |
| `appointments.reserve`   | `/appointments/reserve`    | `hold`, `context`              |
| `appointments.release`   | `/appointments/release`    | `holdId`, `reason`, `context`  |
| `appointments.commit`    | `/appointments/commit`     | `hold`, `orderId`, `context`   |
| `appointments.freeTimes` | `/appointments/free-times` | `query`, `context`             |
| `appointments.move`      | `/appointments/move`       | `move`, `context`              |
| `orderActions.<id>`      | `/order-actions/<id>`      | `order`, `context`             |

`context` is what a function gets, without the `signal`: `channel`, `environment`, `requestId` and
the fields of the contract, such as `currency` and `purpose` for `offers`. An HTTP endpoint is called
at exactly the address you gave. Answer with a `2xx` and the JSON the contract describes, which is the
value its function returns. An empty body is `{}`. Anything else, a redirect included, counts as
unreachable, and a call that changes something is then repeated with the same key.

Every call carries two headers:

- `Orbcart-Request-Id`: the request, for finding it in the diagnosis. A repeat has a new one.
- `Idempotency-Key`, on calls that change something, such as handing off an Order, reserving
  stock or moving an appointment. A retry uses the same key. Scope it by endpoint: `reserve`,
  `release` and `commit` of one hold carry the same key, so a handler that stores only the key
  would answer a `commit` with the stored answer of the `reserve`.

## Verify an HTTP call

An HTTP call is signed with the environment's key, like an [event](/docs/integrate/order-events#verify-a-delivery).
Check it in the endpoint:

```ts title="middleware/orders.ts"
import { verifyRequest } from "@orbcart/admin";

export async function handle(request: Request): Promise<Response> {
  const { body, idempotencyKey } = await verifyRequest(request, {
    url: "https://commerce.nordgrat.de",
    contract: "deliverOrder",
  });
  const { order } = body;

  const reference = await erp.createSalesOrder(order, { idempotencyKey });
  return Response.json({ reference });
}
```

Choose the `contract` your endpoint handles. After verifying the signature, `verifyRequest` parses
the body against that contract and returns typed arguments. The signed URL is the HTTPS address
you configured, not the Service Binding path above. For an action, pass its name, such as
`orderActions.parcelLabel`.

A bad signature or a body that does not match the contract throws a `RequestVerificationError`
with a `code`; answer those with a 4xx. A signature made for an event never passes here, and a
contract's never passes `verifyEvent`. A Service Binding is not signed: only your own account can
reach it.

To try your endpoint against the real thing, `@orbcart/runtime/testing` builds the signed request:

```ts
import { signedContractCall } from "@orbcart/runtime/testing";

const request = await signedContractCall(
  env,
  "deliverOrder",
  "https://middleware.nordgrat.de/edge/orders",
  { order },
);
```

The signature covers `@method`, `@authority`, `@path`, `@query`, `content-type`, `content-digest` and
`orbcart-request-id`, and `idempotency-key` where the call carries one, with `tag="orbcart-contract"`.
`verifyRequest()` refuses a body larger than 1 MiB as `body_too_large`, and behind a proxy that
rewrites the URL takes the one OrbCart sent to as `target`. For another language, any library for
[RFC 9421](https://www.rfc-editor.org/rfc/rfc9421) verifies it against the keys at
`/.well-known/jwks.json`.