# Sending the buyer's emails

Confirm Orders, tell buyers a payment did not go through and follow up on a Cart, from your own mail system and OrbCart's events.

**OrbCart does not send emails.** It tells your systems what is due, and you send the mail from
the system you already have, in your design and under your sender. Every email a buyer expects
starts with an [event](/docs/integrate/order-events):

| Email                           | Event                                | You load                                                                 |
| ------------------------------- | ------------------------------------ | ------------------------------------------------------------------------ |
| Order confirmation              | `order.created`                      | the Order                                                                |
| Your payment did not go through | `payment.failed`, `payment.canceled` | the Cart, or the Order once there is one                                 |
| You left something in your Cart | `cart.abandoned`                     | the Cart                                                                 |
| Receipt of a withdrawal         | `withdrawal.received`                | the declaration                                                          |
| Gift card                       | `gift_card.issued` with an order     | `admin.giftCards.delivery(event.data.giftCard)`: code, value, print page |

The events carry no personal data: no email address, no name. You load them with your secret key,
which is also what keeps a late or repeated event harmless: you always read the current state.

All four recipes run in an endpoint of yours that takes events over HTTP. Attach it once, for
the types you need:

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

export default defineCommerce({
  channels,
  offers,
  events: {
    mails: http("https://mail.nordgrat.de/orbcart", {
      types: [
        "order.created",
        "payment.failed",
        "payment.canceled",
        "cart.abandoned",
        "withdrawal.received",
      ],
    }),
  },
});
```

And take them in the endpoint, after verifying them:

```ts title="mail.nordgrat.de/orbcart.ts"
import { createAdmin, verifyEvent } from "@orbcart/admin";
import type { EventOf } from "@orbcart/admin";

const admin = createAdmin({ url: env.ORBCART_URL, key: env.ORBCART_SECRET_KEY });

export async function handle(request: Request): Promise<Response> {
  const event = await verifyEvent(request, { url: env.ORBCART_URL });

  switch (event.type) {
    case "order.created":
      await confirmOrder(event);
      break;
    case "payment.failed":
    case "payment.canceled":
      await paymentDidNotGoThrough(event);
      break;
    case "cart.abandoned":
      await cartLeftBehind(event);
      break;
    case "withdrawal.received":
      await confirmWithdrawal(event);
      break;
  }
  return new Response(null, { status: 204 });
}
```

Any 2xx **acknowledges** the event, so return it only once the mail is safely yours: sent, or
stored in your own queue. Anything else is retried for 72 hours, always with the same `id`, so
**deduplicate by `event.id`**: pass it to your mail provider as its idempotency key, or keep the
ids you handled. A type you do not handle is acknowledged too.

## Order confirmation

`order.created` arrives once the buyer's payment is secured and the Order exists. Load the Order and
send the confirmation:

```ts continues
async function confirmOrder(event: EventOf<"order.created">) {
  const order = await admin.orders.get(event.subject);

  await mail.send({
    idempotencyKey: event.id,
    to: order.contact.email,
    locale: order.locale, // the buyer's language, such as "de-DE"
    template: "order-confirmation",
    data: {
      number: order.number,
      lines: order.quote.lines.map((line) => ({
        title: line.offer.title,
        quantity: line.quantity,
      })),
      total: order.quote.totals.total,
      shipTo: order.quote.shipTo,
      orderUrl: order.url, // the buyer's link to their order page
    },
  });
}
```

Your endpoint's acknowledgement is the only receipt OrbCart looks for: there is no call to make
besides returning 2xx. Whether the mail reaches the buyer is your mail system's affair.

An email is a durable medium, so it should contain your terms and the right of withdrawal as
shown to the buyer, not only a link. `order.quote.legal` names each text the buyer saw by type and
`version`: attach your texts in exactly that version.

## Receipt of a withdrawal

A shopper who withdraws through your shop's [withdrawal function](/docs/shop/withdrawal) sees the receipt
on screen at once, and the law asks for it on a durable medium without delay too, for every
declaration received. **If you switched on the family's mail, it sends this receipt for you;
otherwise send it from `withdrawal.received`.**

The event arrives once for every declaration, whether or not its number and email named an Order;
`data.order` names the Order when they did. Send the receipt to the email the shopper typed, and
repeat only what they declared and when it arrived, nothing of the Order: so the mail tells nobody
whether an order exists. Load the declaration with your secret key:

```ts continues
async function confirmWithdrawal(event: EventOf<"withdrawal.received">) {
  const declared = await admin.withdrawals.get(event.data.withdrawal);

  await mail.send({
    idempotencyKey: event.id,
    to: declared.email,
    template: "withdrawal-receipt",
    data: {
      name: declared.name,
      number: declared.number,
      goods: declared.goods.type === "some" ? declared.goods.description : "all",
      receivedAt: declared.receivedAt, // the date and time the receipt must name
      locale: declared.locale, // the language the shopper declared in
    },
  });
}
```

OrbCart keeps every declaration for 180 days, the email in it too, so the read works for as long as
OrbCart retries the event. The same declaration twice within ten minutes, from a double click or a
reload, is received once and tells one event.

This receipt confirms the declaration was received. Recording it on an order is a separate step:
if the order is unavailable, the declaration still receives its receipt and waits in support's
inbox. Raw declarations expire after 180 days even if recording remains unconfirmed; no retry
payload keeps their name, email or goods beyond that deadline.

`order.withdrawn` follows when the withdrawal is recorded on an Order, with `goods` and `timing`
(`before_delivery`, `in_time` or `late`) for your ERP. It sends no mail: the receipt went already.

## Form submissions

OrbPage can notify the form's team and confirm receipt to the visitor through the family's mail
worker too. It sends a signed `form.submitted` event containing only the form and submission IDs,
never names, addresses or answers. Verify it with `verifyEvent` from `@orbpage/client`, against
OrbPage's `/.well-known/jwks.json`, and deduplicate by `event.id`.

Routing is private deployment configuration on OrbPage: `FORM_EVENTS` names the receiver URL,
source URL and environment; `EVENT_SIGNING_KEY` is the ES256 signing secret; and
`FORM_NOTIFICATIONS` maps form IDs to a recipient and optional confirmation email-field ID,
subject and text. These are not fields of the publicly delivered form. The mail worker's
`/page-events` receiver verifies the event and reads the authoritative Inbox over its private
`PAGE_NOTIFICATIONS` service binding to OrbPage's `FormNotifications` entrypoint. `PAGE` supplies
OrbPage's public keys, and `ORBPAGE_URL` identifies their source.

Notification and confirmation retry independently, so a failed confirmation does not resend a
successful team notification. The team receives the submitted answers; the visitor receives
only the configured confirmation copy. Removing or erasing a submission also removes its private
routing snapshot and cancels undelivered work. All private facts expire with the submission after
180 days. Mail already accepted by SMTP or in flight cannot be recalled.

Mail must be enabled in Settings first. The event outbox retries failures for 72 hours; accepting
the same form submission again with its original idempotency key creates neither another event
nor another pair of mails. SMTP acceptance itself is not transactional with local storage, so
a lost SMTP acknowledgement still has the same delivery uncertainty as order mail.

## Your payment did not go through

A payment can end without an Order: the card was declined, 3-D Secure failed, nobody finished a
redirect before the payment window of 30 minutes ended. OrbCart tells it with `payment.failed` or
`payment.canceled`, with a `reason` code and no provider text:

| Event              | `data.reason`                                                                 |
| ------------------ | ----------------------------------------------------------------------------- |
| `payment.failed`   | `declined`, `authentication_failed`, `expired`                                |
| `payment.canceled` | `payment_window_elapsed`, `amount_mismatch`; none if the provider canceled it |

`cart_changed` and `payment_method_changed` also cancel a Payment, but the buyer did that
themselves a moment ago, so mail nobody for them. And a buyer whose card was declined usually sees it on
the page at once and tries again. So wait a little, and mail only the buyer who did not come back:

```ts continues
async function paymentDidNotGoThrough(event: EventOf<"payment.failed" | "payment.canceled">) {
  const { reason } = event.data;
  if (reason === "cart_changed" || reason === "payment_method_changed") return;

  // Hand the job back to your own queue, with `event.id` as its key, to run in 15 minutes.
  await jobs.later({ minutes: 15, key: event.id, job: () => mailUnpaidBuyer(event) });
}

async function mailUnpaidBuyer(event: EventOf<"payment.failed" | "payment.canceled">) {
  const { amount, method } = event.data;
  // After the Order, a Payment that ends later, such as a bank debit, belongs to the Order.
  const to = event.subject.startsWith("ord_")
    ? (await admin.orders.get(event.subject)).contact.email
    : await emailIfStillUnpaid(event.subject);
  if (!to) return;

  await mail.send({
    idempotencyKey: event.id,
    to,
    template: "payment-did-not-go-through",
    data: { amount, method },
  });
}

async function emailIfStillUnpaid(cartId: string) {
  const cart = await admin.carts.get(cartId);

  // The buyer bought after all, or is paying again right now: nothing to say.
  return cart.lifecycle.status === "open" ? cart.contact?.email : undefined;
}
```

Before the Order, `event.subject` is the Cart. A Payment exists only for a Quote, and a Quote needs
the buyer's email, so a Cart that reached its Payment has one. `admin.carts.get` returns it as
`contact.email`, together with the lines and `lifecycle`: `open` after the failure, `locked` while
another attempt runs, `ordered` once it worked.

### What is missing: a way back into the Cart

The mail should bring the buyer back to what they chose. **OrbCart has no return link for a Cart
yet.** The Cart's token is a secret of the buyer's browser and must not travel in a URL, and the
Admin API cannot mint another. What works today is a link to your own cart or checkout page:

- In the buyer's own browser it finds the Cart again, as it always does.
- For a signed-in buyer it finds their active Cart on any device ([identity](/docs/integrate/identity)).
- A guest on another device starts a new Cart: the mail can name the goods, not restore them.

A short-lived return link for the Cart, like the Order's page token, is planned.
Until it exists, do not promise the buyer more than your page can keep.

## You left something in your Cart

`cart.abandoned` arrives once a Cart with lines stood still for 24 hours and has no Order. Set another
period per Channel with [`abandonedAfterHours`](/docs/shop/configuration), from 1 hour to 30 days. The
Cart stays as it is, and a buyer who changes it starts the next spell.

```ts continues
async function cartLeftBehind(event: EventOf<"cart.abandoned">) {
  const cart = await admin.carts.get(event.subject);
  const email = cart.contact?.email;

  // No email yet, the buyer ordered meanwhile, or never agreed to hear from you.
  if (!email || cart.lifecycle.status !== "open" || !(await agreedToMarketing(email))) return;

  await mail.send({
    idempotencyKey: event.id,
    to: email,
    template: "cart-left-behind",
    data: {
      lines: cart.lines.map((line) => ({
        title: line.offer?.title,
        image: line.offer?.image,
        quantity: line.quantity,
      })),
      cartUrl: "https://nordgrat.de/cart",
    },
  });
}
```

Four things to know:

- **Not every Cart has an email.** The checkout asks for it at the contact step, so a Cart that
  was left before has none, and you cannot write to that buyer.
- **A reminder is marketing in most countries.** It needs the buyer's consent, and OrbCart holds
  none for a Cart: check your own list of buyers who agreed (`agreedToMarketing` above).
- **Prices are what the buyer saw.** Reading a Cart as a merchant does not borrow offers again
  and is no change to the Cart, so the lines show the last price they had. Ask your own system
  for current prices if the mail should quote them.
- **The return link** has the same gap as above.

## What is not there yet

- A **return link** into a Cart without its token, see above.
- **Monitoring of the confirmation.** OrbCart will raise an issue when your endpoint has not taken
  `order.created` for 30 minutes. Until then, watch `admin.receivers.list()` for a growing `backlog`.
- A mail when **returned goods** arrive: `order.returned` tells it, but no recipe here sends it yet.