# 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](/integrations/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                                 |

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 three 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"],
    }),
  },
});
```

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;
  }
  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
&#x2A;*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.

## 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. &#x2A;*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](/integrations/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 open in the plan
(Paper 10 §7). 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`](/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`.
* The mails around **withdrawal and returns**: `order.withdrawn` and `order.returned` do not exist yet.