# Ordering UI and tracking SDKs

The dashboard **Playground** contains the live **Experience**, **Integration code**, and **Tracking**. The experience uses the same customer ordering UI that the SDK embeds. Install `@mealme/sdk` using the versioned HTTPS package shown there. It includes the server client and the dependency-free `@mealme/sdk/browser` entry point.

## Ordering UI

Your backend authenticates the customer, then calls:

```ts
const session = await mealme.createOrderingSession({
  externalCustomerId: yourAuthenticatedCustomer.id,
  allowedOrigin: "https://your-app.com",
});
```

Return that short-lived session descriptor to your browser. Never return your MealMe secret API key.

```ts
import { mountOrdering } from "@mealme/sdk/browser";
const ordering = mountOrdering({
  element: "#ordering",
  session,
  async onCheckout(quote) {
    // Authorize your customer's payment in your app here.
    // Your own backend verifies the PaymentIntent/authorization and stored quote.
    const response = await fetch("/api/approve-food-order", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ sessionUrl: session.url, quoteId: quote.quoteId }),
    });
    if (!response.ok) throw new Error("Payment was not approved");
    return response.json(); // { checkoutToken, idempotencyKey }
  },
  onOrder(order) {
    showTracking(order.trackingUrl);
  },
});
// Remove listeners and iframe when leaving your screen:
ordering.destroy();
```

The hosted flow covers recommended addresses, restaurant/grocery store discovery, pickup/delivery, live menus, required modifiers, basket editing, recipient details, quoting, explicit confirmation, order submission, and hosted tracking/receipt after confirmation. Customers remain within the embedded flow. Options depend on Grubhub availability at the selected address.

After verifying your customer's payment, your backend issues authorization for the exact stored quote:

```ts
return mealme.authorizeCheckout({
  sessionUrl: session.url,
  quoteId: storedCustomerQuote.id,
  maxTotalCents: storedCustomerQuote.totalCents,
});
```

Do not trust the browser's claimed customer ID, “paid” flag, amount, or quote ownership. Map the original session, authenticated customer, quote, and payment in your own database. A browsing session cannot submit orders. A checkout token is locked to the original workspace, customer, quote, and maximum food total, and expires within five minutes or with the quote. The customer must still confirm the final order. The existing durable idempotency and spending checks remain enforced.

Browsing sessions expire within 30 minutes and are bounded to 60 requests with a per-session rate limit. Reopen a session from your backend after expiry. Tokens are private bearer credentials: don't log them, publish session URLs, or include them in analytics. Message delivery checks the expected iframe window, origin, and session ID. API requests also carry the signed session's parent origin. Tokens authorize only the named customer, not dashboard administration, API-key management, funding, or other customers' orders.

Handle uncertain purchase outcomes by reconciling the original order. An app timeout does not cancel a food order. Capture your customer payment after confirmation; void only after a definitive failure. The API spends the developer's MealMe credits, while customer payments remain in your app. The dashboard live preview intentionally has an explicit authorization button and makes no end-customer Stripe charge; do not substitute that demo approval for a production payment integration.

## Tracking embed or link

```ts
import { mountTracking } from "@mealme/sdk/browser";
const tracking = mountTracking({
  element: "#tracking",
  trackingUrl: order.trackingUrl,
  baseUrl: "https://mealmeai.vercel.app",
});
// On unmount: tracking.destroy();
```

Or open/share `order.trackingUrl` directly. Customers need no MealMe or retailer account. The page contains progress, available ETA, and a MealMe receipt. It pauses polling in hidden tabs, backs off on errors, and stops on terminal status. Provider refreshes remain shared by order rather than per viewer. Signed links expire after seven days. No provider-account credentials, session controls, or provider-account receipt links are returned to customers.

## React

The ordering loader stays visible until the embedded UI confirms readiness. If it cannot load within 30 seconds, the embed shows a readable error even without an onError callback. Use onReady to update your own app state and onError to display payment or loading errors. Reopening an expired session requires a fresh descriptor from your backend.

Both mounts work with React, Vue, Svelte, or vanilla JavaScript. In React, call the mount in an effect after your ref exists, and return `handle.destroy` as the effect cleanup. Keep `session` and callbacks stable so re-renders don't recreate an in-progress basket. Use the server SDK when you want a completely custom interface instead of the hosted flow.
