# MealMe SDK

**Browser UI SDKs:** `mountOrdering` handles address search, restaurant/grocery selection, baskets, and checkout. `mountTracking` embeds the signed MealMe tracking page. Both are exported from `@mealme/sdk/browser`. See [the browser SDK integration guide](./EMBEDS.md) and **Playground → Integration code** in your dashboard. Your server client creates scoped ordering sessions and approves the exact quoted basket after your customer-payment step.

Restaurant and grocery discovery, checkout, tracking, and support. Grubhub is supported today; more ordering services are coming. Store availability depends on the address, fulfillment type, and time. Server SDK: Node.js 20+; browser SDK: modern browsers; TypeScript declarations included; no runtime dependencies.

Install the versioned package shown in your MealMe console. Use the production URL for live funding and ordering. The separate development deployment accepts Stripe test payments; test credits and keys cannot spend live funds.

```sh
npm install https://mealmeai.vercel.app/sdk/mealme-sdk-0.3.4.tgz
```

```ts
import { MealMe, MealMeError, trackingLink } from "@mealme/sdk";

const mealme = new MealMe({
  apiKey: process.env.MEALME_API_KEY!,
  baseUrl: "https://mealmeai.vercel.app",
});
const results = await mealme.search({
  address: "233 S Wacker Dr, Chicago, IL 60606",
  query: "burgers",
  fulfillment: "delivery",
});
const store = results.restaurants[0];
if (!store) throw new Error("No matching stores");
const menu = await mealme.menu(store.id, {
  latitude: results.location.latitude,
  longitude: results.location.longitude,
  zipCode: "60606",
  fulfillment: "delivery",
});
```

Use `menu.items` to build your UI. Enforce each option group's `min` and `max`, and submit the selected choice IDs. Prices are integer USD cents. Do not invent item IDs or option IDs. Store availability depends on address, time, and fulfillment. The service is Grubhub; MealMe does not provide comparison quotes from other marketplaces or guaranteed nutrition data.

## Quote and place

```ts
const quote = await mealme.quote({
  externalCustomerId: "your_customer_123",
  restaurantId: store.id,
  restaurantUrl: store.menuUrl,
  fulfillmentType: "delivery",
  deliveryAddress: {
    line1: "233 S Wacker Dr",
    city: "Chicago",
    state: "IL",
    postalCode: "60606",
  },
  recipient: { name: "Customer Name", phone: "3125550100" },
  tipCents: 200,
  items: yourValidatedBasket.map((line) => ({
    id: line.menuItemId,
    quantity: line.quantity,
    optionIds: line.selectedOptionIds,
  })),
});
// A quote creates an unpaid cart. It does not place an order.
// Customer payment authorization goes HERE; see Payments below.
const order = await mealme.place(
  {
    quoteId: quote.quoteId,
    confirmRealOrder: true,
    maxTotalCents: quote.quote.totalCents,
  },
  { idempotencyKey: yourPersistedOrderKey },
);
```

Persist a unique key per purchase **before** submitting it, alongside the quote ID and your customer payment ID. Reuse that exact key and quote on retries. `confirmRealOrder: true` authorizes a real purchase. The API checks the caller's quote ownership, expiration, balance, fulfillment, and authorized maximum before submitting checkout. The SDK never retries a financial operation automatically.

Your backend must authenticate its own customer, derive `externalCustomerId` from that authenticated user, validate the basket, and check quote/order ownership in your application. Do not give a browser your MealMe secret key or allow an unauthenticated proxy to spend it. External customer IDs are scoped to your developer account; your end users do not need MealMe accounts.

## Payments

There are **two separate flows**:

1. Sign in and explore stores, menus and quotes for free until the first provider-confirmed order. No card is needed for discovery and no API fees accrue. Add prepaid credits from $5 to cover the full food total before submitting; the first order API call is free. Buying credits does not start metering. After the first confirmed order, successful billable calls cost $0.10 from credits. Canonical quote reads, order status, support-case status, and address suggestions remain unbilled.
2. The developer's application collects its own customer payment, using its own processor and pricing. MealMe does not charge that card, split the payment, or receive your customer payment token.

For Stripe, create a PaymentIntent on **your server** using a quote you retrieved for the authenticated customer. For manual capture, authorize it with your customer-facing Stripe UI before calling `mealme.place`. Verify the PaymentIntent on your server: correct customer, USD, your expected amount, `requires_capture` status, and a durable mapping to the quote and purchase key. Do not trust a browser-supplied “paid” flag or PaymentIntent ID without checking ownership. Store the mapping in your application's database; metadata alone does not enforce ownership or prevent reuse.

- `confirmed`: capture your customer authorization after checking the confirmed receipt. Use your own idempotency key on Stripe capture.
- Definitively `failed`: void your customer authorization.
- `placing`, `reconciliation_required`, timeout, or an uncertain error: keep the authorization and reconcile. **Do not place another order, capture blindly, or void while the purchase might have succeeded.** Reuse the original MealMe key to retrieve the recorded submission; then use `mealme.order(id)` once you have its ID. Escalate unresolved outcomes to MealMe support.
- If customer payment capture fails after the food order is confirmed, the food purchase still exists and has spent your credits. Reconcile the two systems; don't submit a second food order. Account for this exposure in your app.
- Refunds require provider approval. A support request is not refund confirmation. When a MealMe refund is confirmed and credits returned, apply the matching customer refund in your own payment system exactly once. Stripe/payment processing fees may not be returned.

If you use crypto or another processor, use the same durable purchase mapping and explicitly handle irreversible payments and order failure. No payment processor or crypto integration is bundled into this SDK.

## Tracking

```ts
const order = await mealme.order(yourOrderId);
const url = trackingLink(order);
// Return the URL to your customer. No customer login, API key, or SDK required.
```

Confirmed orders return signed MealMe `trackingUrl` and `receiptUrl` links. Both are customer-facing MealMe pages, with no retailer-account login. Links expire 7 days after the order is created; treat them as private bearer links. Do not put them in analytics or public logs.

If building your own tracking UI, poll `mealme.order(id)` from your backend no faster than once per minute, share cached status among viewers, and stop after completion/cancellation. Hosted tracking pauses polling in hidden tabs, backs off on errors, and stops on terminal status. Provider status refresh is shared per order rather than per viewer. Delivery estimates are estimates, not guarantees.

## Support and refunds

```ts
const result = await mealme.requestSupport(
  order.id,
  {
    kind: "delivery_issue",
    message: "The customer reports that their delivery has not arrived.",
  },
  { idempotencyKey: yourPersistedSupportKey },
);
const current = await mealme.support(order.id);
```

Kinds: `cancellation`, `refund`, `delivery_issue`, `other`. Describe the actual issue accurately. Requests are deduplicated and queued for review. The response includes `providerActionSubmitted: false` when the request has only been recorded. Use `mealme.requestSupport` from your backend for in-app support intake, and show the returned case status. The Grubhub phone number and provider order number in `order.support` and hosted tracking are a fallback; Grubhub may require the ordering account owner to act. Intake does not itself cancel or refund an order. Grubhub decides eligibility, and unresolved cases require MealMe operator escalation.

Confirmed provider payment adjustments are reconciled into developer credits. `order.refundedCents` is the cumulative food-order amount returned to the workspace; API charges remain spent. The signed `order.refund_credited` event contains `orderId`, `quoteId`, `amountCents` (this credit only), `totalRefundedCents`, and `currency`. Map the order/quote to your customer payment, then refund `amountCents` through your own payment provider. Use `event.id` as that provider’s refund idempotency key. Returning developer credits does not automatically refund your customer’s card.

Refund requests are reviewed for eligibility. Credits are returned only after a confirmed provider refund, and never simply because a request was submitted.

### Your app and customer payments

Optionally add an app name and support link in Settings, or use `mealme.configureApp({appName, supportUrl})`. They appear on hosted tracking.

Use your own accounts and payment flow for your customers. Prefill `mountOrdering` with a customer's delivery address and contact details. Before approving payment, read the canonical quote with `mealme.getQuote(quoteId)`, verify `externalCustomerId`, `expired`, `orderId` and the total, and check your MealMe balance. Keep the session, customer payment, quote and order-key mapping in your backend. Capture after a confirmed order, void after a definitive failure, and reconcile any unknown outcome before trying again. Signed events support recovery if the browser closes.

### Getting started and billing

API calls are free until your first order is confirmed, including the first order submission. Pre-order calls never accrue fees. Choose credits starting at $5 when ready to fund the full food total. Buying credits does not end free exploration. After the first confirmed order, successful billable calls cost $0.10 from prepaid credits; later order submissions need the food total plus the $0.10 API fee. Credits are 1:1 with dollars. Status and account reads stay free. `mealme.account().billing` reports `apiCallsFree`, `apiCallPriceCents`, `orderApiFeeCents`, and `firstOrderAt`. Your customer payment integration remains separate from your developer billing.

## Errors and retries

`MealMeError` includes `status`, `code`, `outcomeUncertain`, and optional `retryAfterSeconds`. Respect 429 backoff; don't loop on account verification or authentication errors. There are no automatic retries. Pass `{ signal }` to cancel discovery/quote calls; cancellation of an order request does not cancel an order. A network failure on submission means the outcome is unknown. A fresh basket or new key is not a safe retry.

Keep secrets in environment variables. Set `baseUrl` explicitly to the deployment you use. Production access and real funding are separate from the development environment. Existing API endpoints retain their existing billing agreements; new /api/v2 ordering uses the card-and-credit flow. No request is charged to both systems. Future ChatGPT/Claude authorization will bind to the same developer workspace through delegated OAuth; this version does not issue MCP OAuth credentials.

## Signed server events

```js
const { signingSecret } = await mealme.configureWebhook({
  url: "https://your-app.com/api/mealme-events",
});
// Save signingSecret in your server secret store. It is returned once.

import { verifyWebhook } from "@mealme/sdk";
const body = await request.text();
const valid = await verifyWebhook({
  body,
  signature: request.headers.get("MealMe-Signature") ?? "",
  secret: process.env.MEALME_WEBHOOK_SECRET,
});
if (!valid) return new Response("Invalid signature", { status: 400 });
const event = JSON.parse(body);
// Deduplicate by event.id, persist, return 2xx, then process asynchronously.
```

Events include order submission, confirmation/failure, tracking changes, and support case transitions. Delivery retries up to eight times; event ordering is not guaranteed. Use `mealme.webhooks()` to inspect recent delivery attempts. Re-saving a destination rotates its secret and affects queued deliveries. Tracking updates contain an order ID; read the current order or use its hosted tracking link. No provider account details are included. Hosted tracking and webhook settings are unmetered.
