# Set up Crave with an agent Source: https://craveup-1493c4c7.mintlify.dev/docs/ai-onboarding Give your coding agent the current Crave docs, connect your account, and prepare your app for Sandbox development. Open your project in Claude Code, Cursor, Codex, or another coding agent. Paste this prompt and let it work through the setup with you: ```text wrap theme={null} Set up Crave using this guide: https://developer.craveup.com/agents.md Start in sandbox. Verify locally. ``` [Read the agent instructions](https://developer.craveup.com/agents.md) You describe what you want to build. Your agent handles the repository, configuration, and checks. You complete your own sign-in when it is needed. You do not need an API key to give an agent access to the public documentation. > [!NOTE] > > This flow prepares an existing app and Crave restaurant for development. New > Cloud workspace provisioning is currently assisted. If you need a new > workspace, [request setup help](mailto:hello@craveup.com) before expecting an > agent to deploy a restaurant. See [Cloud > availability](/docs/guides/crave-cloud-overview). ## What your agent does **1. Understand your project** Detect the framework and package manager, read your repository instructions, and reuse any existing Crave integration. **2. Connect to current guidance** Read the agent guide and the docs for your framework. Check the target API and package versions before choosing an integration. **3. Connect your restaurant** Help you sign in to Sandbox and confirm the intended restaurant. Configure its public API origin, merchant slug, and location ID in your app. **4. Verify the result** Run the app's checks, start it locally, and verify a real published menu when your restaurant and compatible integration are available. Report unfinished steps explicitly; installed tools alone do not mean the app is ready. ## Keep Crave docs available to your agent The **documentation MCP** lets your agent search and read the current docs. It connects over HTTP without a Crave account. It does not sign in to your restaurant, create projects, edit menus, or deploy apps. Your coding agent can run the matching command below. Preserve any existing MCP servers when adding this connection. > [tab] Claude Code > > ```bash theme={null} > claude mcp add --transport http --scope user crave-docs https://developer.craveup.com/docs/mcp > ``` > > Run `/mcp` to check the connection. Reconnect or start a new session if the > tools do not appear. > [tab] Codex > > ```bash theme={null} > codex mcp add crave-docs --url https://developer.craveup.com/docs/mcp > ``` > > Start a new Codex session if its tool list has not refreshed. > [tab] Cursor > > Add this server to your MCP settings, keeping your other entries: > > ```json theme={null} > { > "mcpServers": { > "crave-docs": { > "url": "https://developer.craveup.com/docs/mcp" > } > } > } > ``` > > Reconnect the server in Cursor's MCP settings. > [tab] Other agents > > Add an HTTP MCP server with this URL: > > ```text theme={null} > https://developer.craveup.com/docs/mcp > ``` > > If your client cannot connect to MCP, give it the > [docs index](https://developer.craveup.com/docs/llms.txt) and [agent instructions](https://developer.craveup.com/agents.md). > Each documentation page is also available as Markdown by appending `.md` > to its URL. Ask your agent: **“Use the Crave docs to explain how this app should connect to my restaurant.”** A working connection should return relevant documentation and source links. ## Choose the next task > [card] [Connect an existing app](/docs/guides/build-custom-storefront) > > Add published menus and ordering UI using the contract supported by your > API. > [card] [Build a storefront](/docs/guides/ai/build-storefront-prompt) > > Give your agent an implementation brief after setup and compatibility > checks. > [card] [Work with restaurant tools](/docs/guides/ai/craveup-mcp-server) > > Review the separate platform MCP, authentication, and released-tool limits. > [card] [Understand Crave Cloud](/docs/guides/crave-cloud-overview) > > Check workspace availability, environments, hosting, and payment readiness. ## Know when setup is complete Ask the agent to show the local app URL, selected Sandbox API and restaurant, files changed, checks run, and any blockers. A working menu does not prove checkout or production readiness. Keep checkout unavailable until the selected runtime and SDK support it and the relevant checks pass. # Record an allowlisted Storefront analytics event Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/analytics/record-an-allowlisted-storefront-analytics-event /generated/storefront.openapi.json post /locations/{locationId}/analytics-events # Add an item to a cart Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/cart-items/add-an-item-to-a-cart /generated/storefront.openapi.json post /locations/{locationId}/carts/{cartId}/items # Remove an item from a cart Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/cart-items/remove-an-item-from-a-cart /generated/storefront.openapi.json delete /locations/{locationId}/carts/{cartId}/items/{itemId} # Update a cart item quantity Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/cart-items/update-a-cart-item-quantity /generated/storefront.openapi.json patch /locations/{locationId}/carts/{cartId}/items/{itemId} # Accept the current authoritative cart changes Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/carts/accept-the-current-authoritative-cart-changes /generated/storefront.openapi.json post /locations/{locationId}/carts/{cartId}/catalog-revalidation/accept # Claim a guest cart for the signed-in customer Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/carts/claim-a-guest-cart-for-the-signed-in-customer /generated/storefront.openapi.json post /locations/{locationId}/carts/{cartId}/claim # Expire a cart Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/carts/expire-a-cart /generated/storefront.openapi.json delete /locations/{locationId}/carts/{cartId} # Get an authorized cart Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/carts/get-an-authorized-cart /generated/storefront.openapi.json get /locations/{locationId}/carts/{cartId} # List cart recommendations Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/carts/list-cart-recommendations /generated/storefront.openapi.json get /locations/{locationId}/carts/{cartId}/products # Persist session preferences and recalculate cart food advice Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/carts/persist-session-preferences-and-recalculate-cart-food-advice /generated/storefront.openapi.json put /locations/{locationId}/carts/{cartId}/dietary-preferences # Set cart delivery address Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/carts/set-cart-delivery-address /generated/storefront.openapi.json put /locations/{locationId}/carts/{cartId}/set-delivery # Set room service details Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/carts/set-room-service-details /generated/storefront.openapi.json put /locations/{locationId}/carts/{cartId}/set-room # Set table service details Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/carts/set-table-service-details /generated/storefront.openapi.json put /locations/{locationId}/carts/{cartId}/set-table # Start a cart at another merchant location Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/carts/start-a-cart-at-another-merchant-location /generated/storefront.openapi.json post /locations/{locationId}/carts/{cartId}/location-switches # Stream authorized cart revision events Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/carts/stream-authorized-cart-revision-events /generated/storefront.openapi.json get /locations/{locationId}/carts/{cartId}/events # Update cart fields Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/carts/update-cart-fields /generated/storefront.openapi.json patch /locations/{locationId}/carts/{cartId} # Update cart gratuity Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/carts/update-cart-gratuity /generated/storefront.openapi.json put /locations/{locationId}/carts/{cartId}/gratuity # Update cart order time Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/carts/update-cart-order-time /generated/storefront.openapi.json put /locations/{locationId}/carts/{cartId}/update-order-time # Update the DoorDash courier tip Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/carts/update-the-doordash-courier-tip /generated/storefront.openapi.json put /locations/{locationId}/carts/{cartId}/courier-tip # Accept the current catering offer Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/catering/accept-the-current-catering-offer /generated/storefront.openapi.json post /locations/{locationId}/catering/events/{eventId}/accept # Decline the current catering quote Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/catering/decline-the-current-catering-quote /generated/storefront.openapi.json post /locations/{locationId}/catering/events/{eventId}/decline # Explicitly accept or decline the exact proposed catering version Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/catering/explicitly-accept-or-decline-the-exact-proposed-catering-version /generated/storefront.openapi.json post /locations/{locationId}/catering/events/{eventId}/amendments/decision # Pay the remaining balance of an accepted catering job Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/catering/pay-the-remaining-balance-of-an-accepted-catering-job /generated/storefront.openapi.json post /locations/{locationId}/catering/events/{eventId}/balance-payment # Read a customer's cancellation request without changing the booking Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/catering/read-a-customers-cancellation-request-without-changing-the-booking /generated/storefront.openapi.json get /locations/{locationId}/catering/events/{eventId}/cancellation-request # Read a location's published catering menu Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/catering/read-a-locations-published-catering-menu /generated/storefront.openapi.json get /locations/{locationId}/catering/menu # Read an event-bound catering proposal Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/catering/read-an-event-bound-catering-proposal /generated/storefront.openapi.json get /locations/{locationId}/catering/events/{eventId}/live-cart # Request restaurant review of cancellation; never cancels or refunds Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/catering/request-restaurant-review-of-cancellation;-never-cancels-or-refunds /generated/storefront.openapi.json post /locations/{locationId}/catering/events/{eventId}/cancellation-request # Review immutable proposed changes to an accepted catering booking Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/catering/review-immutable-proposed-changes-to-an-accepted-catering-booking /generated/storefront.openapi.json get /locations/{locationId}/catering/events/{eventId}/amendments # Send a catering inquiry from a website Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/catering/send-a-catering-inquiry-from-a-website /generated/storefront.openapi.json post /locations/{locationId}/catering/inquiries # Show a location's public catering inquiry form Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/catering/show-a-locations-public-catering-inquiry-form /generated/storefront.openapi.json get /locations/{locationId}/catering/inquiry-form # Suggest catering catalog quantities and preferences Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/catering/suggest-catering-catalog-quantities-and-preferences /generated/storefront.openapi.json put /locations/{locationId}/catering/events/{eventId}/live-cart # View a customer catering event Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/catering/view-a-customer-catering-event /generated/storefront.openapi.json get /locations/{locationId}/catering/events/{eventId} # Change immediate location availability using the operational owner Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/change-immediate-location-availability-using-the-operational-owner /generated/catalog-workspace.openapi.json patch /api/v1/locations/{locationId}/catalog/products/{productId}/availability # Create a one-time checkout handoff Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/checkout/create-a-one-time-checkout-handoff /generated/storefront.openapi.json post /locations/{locationId}/carts/{cartId}/checkout-handoffs # Create or replay an order-first checkout submission Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/checkout/create-or-replay-an-order-first-checkout-submission /generated/storefront.openapi.json post /locations/{locationId}/carts/{cartId}/submissions # Exchange a one-time checkout handoff Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/checkout/exchange-a-one-time-checkout-handoff /generated/storefront.openapi.json post /locations/{locationId}/carts/{cartId}/checkout-handoffs/exchange # Get a stable order-first submission outcome Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/checkout/get-a-stable-order-first-submission-outcome /generated/storefront.openapi.json get /locations/{locationId}/carts/{cartId}/submissions/{attemptId} # Get server-evaluated checkout collection choices Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/checkout/get-server-evaluated-checkout-collection-choices /generated/storefront.openapi.json get /locations/{locationId}/carts/{cartId}/collection-options # Prepare hosted checkout with separate read-only return authority Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/checkout/prepare-hosted-checkout-with-separate-read-only-return-authority /generated/storefront.openapi.json post /locations/{locationId}/carts/{cartId}/checkout-observers # Read persisted hosted checkout state without payment reconciliation Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/checkout/read-persisted-hosted-checkout-state-without-payment-reconciliation /generated/storefront.openapi.json get /locations/{locationId}/carts/{cartId}/checkout-result # Resolve a submission by attempt, cart, or payment intent Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/checkout/resolve-a-submission-by-attempt-cart-or-payment-intent /generated/storefront.openapi.json get /locations/{locationId}/carts/{cartId}/submission-lookup # Submit a rating after successful payment Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/checkout/submit-a-rating-after-successful-payment /generated/storefront.openapi.json post /locations/{locationId}/carts/{cartId}/rating # Validate checkout and update customer contact details Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/checkout/validate-checkout-and-update-customer-contact-details /generated/storefront.openapi.json put /locations/{locationId}/carts/{cartId}/validate-and-update # Consume a fresh code proof for a customer session Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/customer-auth/consume-a-fresh-code-proof-for-a-customer-session /generated/storefront.openapi.json post /merchant/{merchantSlug}/auth/challenges/{challengeId}/verify # Prepare a merchant-bound customer code challenge Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/customer-auth/prepare-a-merchant-bound-customer-code-challenge /generated/storefront.openapi.json post /merchant/{merchantSlug}/auth/challenges # Read eligible customer sign-in channels Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/customer-auth/read-eligible-customer-sign-in-channels /generated/storefront.openapi.json get /merchant/{merchantSlug}/auth/config # Read the current customer session identity Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/customer-auth/read-the-current-customer-session-identity /generated/storefront.openapi.json get /merchant/{merchantSlug}/auth/session # Replace an owned code challenge Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/customer-auth/replace-an-owned-code-challenge /generated/storefront.openapi.json post /merchant/{merchantSlug}/auth/challenges/{challengeId}/resend # Revoke the owned local customer session family Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/customer-auth/revoke-the-owned-local-customer-session-family /generated/storefront.openapi.json delete /merchant/{merchantSlug}/auth/session # Rotate one customer session generation Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/customer-auth/rotate-one-customer-session-generation /generated/storefront.openapi.json post /merchant/{merchantSlug}/auth/session/refresh # Create a customer address Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/customers/create-a-customer-address /generated/storefront.openapi.json post /customer/addresses # Create a Stripe saved-card setup session Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/customers/create-a-stripe-saved-card-setup-session /generated/storefront.openapi.json post /customer/locations/{locationId}/saved-payment-setups # Delete a customer address Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/customers/delete-a-customer-address /generated/storefront.openapi.json delete /customer/addresses/{addressId} # Delete a saved payment method Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/customers/delete-a-saved-payment-method /generated/storefront.openapi.json delete /customer/locations/{locationId}/saved-payments/{paymentId} # Export the signed-in customer's organization data Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/customers/export-the-signed-in-customers-organization-data /generated/storefront.openapi.json get /customer/data-export # Get an authoritative Stripe saved-card setup status Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/customers/get-an-authoritative-stripe-saved-card-setup-status /generated/storefront.openapi.json get /customer/locations/{locationId}/saved-payment-setups/{setupIntentId} # Get signed-in customer deletion progress Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/customers/get-signed-in-customer-deletion-progress /generated/storefront.openapi.json get /customer/privacy-operations/{operationId} # Get the signed-in customer profile Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/customers/get-the-signed-in-customer-profile /generated/storefront.openapi.json get /customer # List customer addresses Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/customers/list-customer-addresses /generated/storefront.openapi.json get /customer/addresses # List saved payment methods Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/customers/list-saved-payment-methods /generated/storefront.openapi.json get /customer/locations/{locationId}/saved-payments # Request deletion of the signed-in customer account Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/customers/request-deletion-of-the-signed-in-customer-account /generated/storefront.openapi.json delete /customer # Update a customer address Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/customers/update-a-customer-address /generated/storefront.openapi.json patch /customer/addresses/{addressId} # Apply a discount code Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/discounts/apply-a-discount-code /generated/storefront.openapi.json post /locations/{locationId}/carts/{cartId}/discount # Remove the applied discount Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/discounts/remove-the-applied-discount /generated/storefront.openapi.json delete /locations/{locationId}/carts/{cartId}/discount # Evaluate a configured item's food from the same draft or released source as the menu preview Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/evaluate-a-configured-items-food-from-the-same-draft-or-released-source-as-the-menu-preview /generated/catalog-workspace.openapi.json post /api/v1/catalog/workspace/configuration-preview # List the locations this key can read Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/list-the-locations-this-key-can-read /generated/integration.openapi.json get /locations Requires an organization API key with merchant:read. Lists the live locations the key was granted, in the merchant's own order, with the id to address them by, their name and their formatted address, so an integration can choose one. Archived locations are left out. Carries no order figures: an integration that only needs to pick a location should not pay for the totals the partner dashboard computes. # Calculate distance to a location Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/locations/calculate-distance-to-a-location /generated/storefront.openapi.json post /locations/{locationId}/distance # Get a published location Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/locations/get-a-published-location /generated/storefront.openapi.json get /locations/{locationSlugOrId} # Get available order times Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/locations/get-available-order-times /generated/storefront.openapi.json get /locations/{locationId}/time-intervals # Get gratuity configuration Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/locations/get-gratuity-configuration /generated/storefront.openapi.json get /locations/{locationId}/gratuity # Read a location menu using an expiring merchant-issued preview capability Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/locations/read-a-location-menu-using-an-expiring-merchant-issued-preview-capability /generated/storefront.openapi.json get /locations/{locationId}/preview # Redirect to the hosted location storefront Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/locations/redirect-to-the-hosted-location-storefront /generated/storefront.openapi.json get /locations/{locationId}/redirect # Get customer loyalty balances and ledger Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/loyalty/get-customer-loyalty-balances-and-ledger /generated/storefront.openapi.json get /customer/locations/{locationId}/loyalty/ledger # Get loyalty earning and reward options Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/loyalty/get-loyalty-earning-and-reward-options /generated/storefront.openapi.json get /locations/{locationId}/carts/{cartId}/loyalty/quote # Get the customer loyalty account, tier, membership, and wallet Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/loyalty/get-the-customer-loyalty-account-tier-membership-and-wallet /generated/storefront.openapi.json get /customer/locations/{locationId}/loyalty/account # Join the checkout's authoritative loyalty program Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/loyalty/join-the-checkouts-authoritative-loyalty-program /generated/storefront.openapi.json post /locations/{locationId}/carts/{cartId}/loyalty/enrollment # List customer loyalty claims Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/loyalty/list-customer-loyalty-claims /generated/storefront.openapi.json get /customer/loyalty/claims # Remove the applied loyalty reward Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/loyalty/remove-the-applied-loyalty-reward /generated/storefront.openapi.json delete /locations/{locationId}/carts/{cartId}/loyalty/redeem # Reserve and apply a loyalty reward Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/loyalty/reserve-and-apply-a-loyalty-reward /generated/storefront.openapi.json post /locations/{locationId}/carts/{cartId}/loyalty/redeem # Submit a loyalty claim Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/loyalty/submit-a-loyalty-claim /generated/storefront.openapi.json post /customer/loyalty/claims # List the published menu bundle Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/menus/list-the-published-menu-bundle /generated/storefront.openapi.json get /locations/{locationId}/menus # Get a published merchant and its locations Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/merchants/get-a-published-merchant-and-its-locations /generated/storefront.openapi.json get /merchant/{merchantSlug} # Resolve an exact active custom storefront hostname Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/merchants/resolve-an-exact-active-custom-storefront-hostname /generated/storefront.openapi.json get /domain-bootstrap/{hostname} # Check ordering availability without creating a cart Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/ordering-sessions/check-ordering-availability-without-creating-a-cart /generated/storefront.openapi.json get /locations/{locationId}/ordering-readiness # Create or resume an ordering session Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/ordering-sessions/create-or-resume-an-ordering-session /generated/storefront.openapi.json post /locations/{locationId}/ordering-sessions # Claim an eligible guest order with verified customer contact Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/orders/claim-an-eligible-guest-order-with-verified-customer-contact /generated/storefront.openapi.json post /customer/order-claims # Get an authorized public receipt Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/orders/get-an-authorized-public-receipt /generated/storefront.openapi.json get /receipts/{receiptId} # Get customer order details Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/orders/get-customer-order-details /generated/storefront.openapi.json get /customer/orders/{orderId} # List customer orders Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/orders/list-customer-orders /generated/storefront.openapi.json get /customer/orders # API Overview Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/overview/api-overview Use the direct public Storefront API with capabilities, customer JWTs, and optimistic concurrency. ## Base URLs ```text theme={null} Production: https://api.craveup.com/api/v1/storefront Sandbox: https://sandbox-api.craveup.com/api/v1/storefront ``` ## Authorization The public API does not use a browser API key. | Resource | Authorization | | - | - | | Published merchant, location, menu, product, order-time, gratuity | Anonymous | | Guest cart | Purpose-limited `X-Cart-Token` capability | | Customer profile, orders, addresses, saved payments, loyalty history | Merchant-bound bearer JWT | | Receipt | Customer JWT or purpose-limited `X-Receipt-Token` capability | Private admin and integration credentials belong only in trusted server or CLI environments. ## Start an ordering session ```bash theme={null} curl -X POST "https://api.craveup.com/api/v1/storefront/locations/LOCATION_ID/ordering-sessions" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: session_01JEXAMPLE" \ -d '{"fulfillmentMethod":"takeout"}' ``` The response contains `cart` and, for a newly created guest cart, `cartAccessToken`. Save the token in tab-scoped storage. The response `ETag` contains the cart revision. ## Mutate the cart ```bash theme={null} curl -X POST "https://api.craveup.com/api/v1/storefront/locations/LOCATION_ID/carts/CART_ID/items" \ -H "Content-Type: application/json" \ -H "X-Cart-Token: CART_CAPABILITY" \ -H 'If-Match: "cart-0"' \ -H "Idempotency-Key: item_01JEXAMPLE" \ -d '{"productId":"PRODUCT_ID","quantity":1,"selections":[],"itemUnavailableAction":"remove_item"}' ``` Use the returned `ETag` for the next mutation. A stale revision returns `409 CART_CONFLICT`; reload current cart state before offering a retry. ## Checkout ```text theme={null} POST /locations/{locationId}/carts/{cartId}/orders GET /locations/{locationId}/carts/{cartId}/order-submissions/{attemptId} POST /locations/{locationId}/carts/{cartId}/rating GET /receipts/{receiptId} ``` An order-submission outcome is `PROCESSING`, `CUSTOMER_ACTION_REQUIRED`, `PAID`, `ACCEPTED`, or `ACTION_REQUIRED`. Only `PAID` is online-payment success; `ACCEPTED` is an audited pay-at-store order. ## Customer authentication ```text theme={null} GET /customer GET /customer/orders GET /customer/addresses GET /customer/saved-payments GET /customer/locations/{locationId}/loyalty/ledger ``` Clerk owns customer sign-in, verification, recovery, and token refresh. Customer API requests use a short-lived JWT from the active Clerk session plus `X-Crave-Merchant-Slug`; the SDK supplies these through `getAuthToken` and `getMerchantSlug`. Crave binds that verified subject to a customer inside the selected restaurant organization and exposes no customer login or OTP endpoint. ## Error envelope ```json theme={null} { "code": "CART_CONFLICT", "message": "The cart changed. Refresh it before retrying.", "requestId": "req_123", "details": {} } ``` Common statuses are `400` validation, `401` invalid capability/session, `404` hidden or missing resource, `409` state/revision conflict, `429` rate limit, `503` dependency unavailable, and `500` internal error. ## SDK ```ts theme={null} const crave = createStorefrontClient({ baseUrl: process.env.NEXT_PUBLIC_CRAVEUP_API_URL!, sessionStore, getAuthToken, getMerchantSlug: () => merchantSlug, }); ``` Prefer the SDK for TypeScript storefronts because it owns capability headers, revisions, idempotency defaults, timeouts, and typed errors. # Core Concepts Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/overview/core-concepts Understand the data model behind merchants, locations, menus, carts, and orders. The Storefront API is built around five entities: **merchants**, **locations**, **menus**, **carts**, and **orders**. This page explains how they relate to each other and what data each one carries. ## Merchants A merchant represents a restaurant brand. Each merchant has a name, logo, and one or more locations. ```ts theme={null} const merchant = await storefront.merchant.getBySlug("downtown-pizza"); merchant.id; // "5b2e7f71-62cf-4bd5-b84e-df17f1f18927" merchant.name; // "Downtown Pizza Co." merchant.locations; // MerchantLocation[] ``` Use `merchant.getBySlug()` to resolve a brand slug into its list of locations. Each location in the response includes an `id`, display name, address, logo, and a `methodsStatus` object indicating which fulfillment methods are enabled. ## Locations A location is a single restaurant site. All storefront operations — menus, carts, payments — are scoped to a location. ```ts theme={null} const location = await storefront.locations.getById( "f8af3da4-f70e-4521-a04f-716c0c04fb77", ); location.restaurantDisplayName; // "Downtown Pizza — Market St" location.addressString; // "123 Market St, San Francisco, CA 94105" location.addressData; // { street, city, state, zipCode, country, lat, lng } ``` ### Location identifiers You can reference a location by either its UUID or slug. Both work in storefront location endpoints: ``` /api/v1/storefront/locations/f8af3da4-f70e-4521-a04f-716c0c04fb77/... /api/v1/storefront/locations/downtown-pizza/... ``` ### Fulfillment methods Each location enables a subset of these fulfillment methods: | Method | Value | Description | | - | - | - | | Pickup | `takeout` | Customer picks up at the counter | | Delivery | `delivery` | Delivered to customer's address | | Table-side | `table_side` | Served to a table number | | Room service | `room_service` | Delivered to a hotel room | Check `methodsStatus` on the merchant location response to determine which options to show: ```ts theme={null} const loc = merchant.locations[0]; loc.methodsStatus.pickup; // true loc.methodsStatus.delivery; // true loc.methodsStatus.table; // false loc.methodsStatus.roomService; // false ``` ### Order times Locations define when they accept orders. Fetch the available time slots before showing a schedule picker: ```ts theme={null} const times = await storefront.locations.getOrderTimes( "f8af3da4-f70e-4521-a04f-716c0c04fb77", ); times.scheduleAllowed; // true — scheduled orders accepted times.requireScheduledOrders; // false — ASAP is available times.orderDays; // RegularOrderDay[] or SpecialOrderDay[] ``` ## Menus, categories, and products Each location has one or more **menus**. A menu contains **categories**, and each category links to **products**. The active menu depends on the time of day. ``` Merchant → Location → Menu → Category → Product → Modifier ``` ### Products A product represents a single orderable item: | Field | Type | Description | | - | - | - | | `id` | `string` | Unique product ID | | `name` | `string` | Display name | | `description` | `string` | Short description | | `price` | `string` | Base price as a decimal string (e.g., `"12.99"`) | | `displayPrice` | `string` | Formatted price with currency symbol | | `images` | `string[]` | Product image URLs | | `modifiers` | `Modifier[]` | Available customizations | | `availability` | `string` | Current availability status | | `nutrition` | `object \| undefined` | Calorie count, dietary preferences, ingredients | ### Modifiers Modifiers let customers customize a product (e.g., size, toppings, extras). Each modifier group has selection rules: ```ts theme={null} interface Modifier { id: string; name: string; // "Choose your size" rule: { min: number; // 1 — must select at least one max: number; // 1 — can select at most one }; items: ModifierItem[]; // [{ id, name, price, maxQuantity }] } ``` Modifier items can have nested child groups for multi-level customization (e.g., "Choose your protein" > "Choose your preparation"). ## Carts A cart holds the customer's selections and computes all pricing automatically. You create a cart by starting an **ordering session**: ```ts theme={null} const session = await storefront.orderingSessions.start("loc_123", { marketplaceId: "web", fulfillmentMethod: "takeout", }); const cartId = session.cart.id; ``` `marketplaceId` is optional source attribution, such as `"web"` or `"mobile"`; it is not a location identifier. ### Cart lifecycle | Status | Meaning | | - | - | | `OPEN` | Active — items can be added, removed, or updated | | `LOCKED` | Payment is processing — no modifications allowed | | `COMPLETED` | Payment confirmed — order sent to the restaurant | | `EXPIRED` | Capability is no longer valid; start a new cart | ### Automatic pricing Every time you modify the cart, the API recalculates all totals: | Field | Description | | - | - | | `subTotal` | Sum of item prices before tax and fees | | `taxTotal` | Tax based on the location's tax rates | | `serviceFeeTotal` | Platform service fee | | `fulfillmentMethodFeeTotal` | Delivery or fulfillment fee | | `waiterTipTotal` | Customer gratuity | | `orderTotalWithServiceFee` | Final total the customer pays | Price fields are decimal strings. Format them using the cart currency and the customer's locale. ### Cart items Each item in the cart tracks its product, quantity, modifier selections, special instructions, and computed totals: ```ts theme={null} const cart = await storefront.cart.get("loc_123", cartId); cart.items.forEach((item) => { item.name; // "Margherita Pizza" item.quantity; // 2 item.total; // "25.98" item.selections; // CartModifierGroup[] — chosen modifiers item.specialInstructions; // "Extra crispy" }); ``` ### Fulfillment configuration Before checkout, set the fulfillment method on the cart. Each method requires different data: | Method | API call | Required data | | - | - | - | | Pickup | `cart.update(...)` | `{ fulfillmentMethod: 'takeout' }` | | Delivery | `cart.setDelivery(...)` | Full address with `lat`/`lng` | | Table-side | `cart.setTable(...)` | Numeric table string such as `"12"` | | Room service | `cart.setRoom(...)` | Room number and last name | ## Payments Stripe is the only online processor. Submit the order before collecting payment, then render Stripe Elements only when the outcome requires customer action: ```ts theme={null} const outcome = await storefront.checkout.submitOrder("loc_123", cartId, { acceptedCatalogEvidence, acceptedDiscountEvidence, collectionMode: "ONLINE", customerConfirmationRevision, quoteFingerprint, }); ``` `CUSTOMER_ACTION_REQUIRED` includes the Stripe `clientSecret` and immutable `connectedAccountId`. Square, Clover, and Toast remain provider-native POS integrations and never expose browser checkout credentials. ## Orders The order-first submission persists the canonical order before Stripe collection. Poll `storefront.checkout.getOrderSubmissionOutcome()` with its attempt ID after payment. It distinguishes processing, customer action, paid, accepted pay-at-store, and action-required outcomes. Signed-in customers can list and read only their own orders through `storefront.customer.orders`. ## Analytics events Track key funnel events to measure storefront performance: ```ts theme={null} await storefront.analyticsEvents.track("loc_123", { cartId, eventType: "CHECKOUT_VIEW", // 'SCAN' | 'CART_VIEW' | 'CHECKOUT_VIEW' }); ``` Every public analytics event requires authorization for its cart. `ORDER_PLACED` is recorded by the API during authoritative order creation and is not accepted from clients. ## Currencies and countries The API supports these currencies and countries: | Currency | Code | Countries | | - | - | - | | US Dollar | `usd` | US | | British Pound | `gbp` | GB | | UAE Dirham | `aed` | AE | | Australian Dollar | `aud` | AU | Currency is set at the merchant level and applies to all locations under that merchant. ## Next steps > [card] [Display Menu](/docs/guides/display-menu) > > Fetch menus, categories, and products for a location. > [card] [Manage Cart](/docs/guides/manage-cart) > > Add items, apply modifiers, and manage the cart lifecycle. > [card] [Checkout Flow](/docs/guides/checkout-flow) > > Collect customer details, set order time, and process payment. > [card] [Fulfillment Methods](/docs/guides/fulfillment-methods) > > Configure delivery, table-side, and room service. # Preview one selected menu at one location/channel/time from its draft revision or an active release Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/preview-one-selected-menu-at-one-locationchanneltime-from-its-draft-revision-or-an-active-release /generated/catalog-workspace.openapi.json post /api/v1/catalog/workspace/preview # Get a published product Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/products/get-a-published-product /generated/storefront.openapi.json get /locations/{locationId}/products/{productId} # Preview an accepted configuration within a released menu Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/products/preview-an-accepted-configuration-within-a-released-menu /generated/storefront.openapi.json post /locations/{locationId}/products/{productId}/configuration-preview # Read a location's identity, hours and current open state Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/read-a-locations-identity-hours-and-current-open-state /generated/integration.openapi.json get /locations/{locationId}/profile Requires an organization API key with merchant:read and access to the requested location. Answers what an integration needs to speak for a restaurant in one read: its name, address, timezone, opening hours, whether it is open at the moment of the request, and which fulfillment methods it accepts. isOpenNow is evaluated server-side against the location's own timezone so that callers do not each reimplement the rule and disagree at opening and closing minutes. scheduleSource distinguishes hours nobody has set (unconfirmed) from a restaurant that is closed right now. Carries no fee rates, provider metadata or internal settings. # Read draft commercial facts for a granted location Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/read-draft-commercial-facts-for-a-granted-location /generated/catalog-workspace.openapi.json get /api/v1/locations/{locationId}/catalog/commercial-facts # Read the canonical order and payment projection for a cart Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/read-the-canonical-order-and-payment-projection-for-a-cart /generated/integration.openapi.json get /locations/{locationId}/carts/{cartId}/commerce-projection Requires an organization API key with orders:read and access to the requested location. Guest cart capabilities and merchant sessions do not authorize this operation. Returns the minimal current aggregate, not customer details or provider payment payloads. A successful read does not authorize a checkout retry. # Replace one ordered parent list without deleting library records Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/replace-one-ordered-parent-list-without-deleting-library-records /generated/catalog-workspace.openapi.json put /api/v1/catalog/workspace/relationships # Review all structural and recipe uses of a shared record Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/review-all-structural-and-recipe-uses-of-a-shared-record /generated/catalog-workspace.openapi.json get /api/v1/catalog/workspace/entities/{canonicalId}/usage # Review explicit menu/location/channel targets and retained releases Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/review-explicit-menulocationchannel-targets-and-retained-releases /generated/catalog-workspace.openapi.json post /api/v1/catalog/workspace/publication-review # Save or withdraw existing revisioned catering commercial facts Source: https://craveup-1493c4c7.mintlify.dev/docs/api-reference/save-or-withdraw-existing-revisioned-catering-commercial-facts /generated/catalog-workspace.openapi.json put /api/v1/catalog/workspace/commercial-facts # Changelog Source: https://craveup-1493c4c7.mintlify.dev/docs/changelog Track improvements to the Crave storefront documentation and OpenAPI reference. **November 4, 2026** Docs on developer.craveup.com and agent setup ### New * **Agent setup** – Added "Set up Crave with an agent" as the first page. It shows how to give a coding agent the current Crave docs, connect your account, and prepare your app for Sandbox development. ### Improved * **One docs address** – The documentation now lives at `developer.craveup.com/docs`. Links to `docs.craveup.com` redirect to the same page there. * **MCP version** – The MCP server guide states which `@craveup/mcp` version npm publishes (0.6.0) and marks the tools that exist only in newer repository source. **October 30, 2026** Assisted ordering, integration API, and POS-native payments ### New * **Assisted ordering** – Added a guide to the shared-cart contract: opening a session, `If-Match` and `ETag` concurrency, idempotency, recovering a lost response, the cart event stream, submission, and webhook correlation. * **Server-to-Server Integration API** – Added an API reference for organization-scoped calls that list locations, read a location profile, and read a cart's commerce projection. Keep the organization API key on your server. * **Staff Menu Manager authoring** – Added an API reference for menu library authoring, previews, and publication review. * **Catering catalog configurations** – Added a guide to nested catering choices, explicit quantities, minimum spend, and quote amendments, including menu import through MCP. * **Customer identity** – Added a guide to guest checkout and verified customer accounts, each scoped to one restaurant organization. * **Organization discounts** – Added a guide to creating one promotion for an organization and targeting all or selected locations. ### Improved * **Payments** – Rewrote Accept Payments around one order-first flow that offers Stripe online payment and certified POS-native pay at store, with the available choices read from the server. * **Square** – The Square guide now covers POS-native setup: activation, pay at store, delivery with DoorDash Drive, webhooks, and health and recovery. * **Webhooks** – The `2026-08-27` event catalog adds `catering.event.updated`. `settlement.updated` carries the order, fulfillment, settlement, refund, and reconciliation revisions separately, with the `cartId` the order was submitted from. * **Storefront API reference** – Regenerated from the current API, adding the catering operations. **October 19, 2026** Sandbox, Launch, and package compatibility ### New * **Package compatibility** – The Crave Cloud overview lists the npm `latest` and `development` versions of the Storefront SDK, commerce contracts, and CLI, and what each client did against the managed Sandbox on October 19. * **Development SDK releases** – `@craveup/storefront-sdk` 3.0.0, 3.1.0, and 4.0.0 are published under the npm `development` tag, with `@craveup/commerce-contracts` 2.0.0 to 4.0.0. `latest` is still 2.0.1. These pairs failed menu and cart schema checks against the managed Sandbox, so use the storefront included with your Cloud project for checkout. ### Improved * **Environments** – Explained Sandbox and Production and the Launch plan: Sandbox holds test orders and menu changes, Launch adds a dedicated Production application service per restaurant, and reviewed Sandbox menu changes are copied to Production. * **Storefront SDK guide** – Separated the SDK versions published on npm from the clients tested against Crave Cloud. **August 26, 2026** Durable outbound webhook platform ### New * **Merchant webhooks** – Added encrypted endpoint lifecycle, versioned events, one-time signing secrets, delivery history, test sends, and audited manual redelivery. * **Operations visibility** – Added cross-organization queue health and terminal-failure reconciliation for authorized Crave staff. ### Improved * **Delivery safety** – Added atomic event outboxes, leased workers, timestamped HMAC signatures, DNS-pinned HTTPS delivery, bounded retries, and immutable attempt evidence. * **Webhook correlation** – The `2026-08-27` contract adds canonical `cartId` evidence to order and successful-payment events so assisted-ordering consumers reconcile one cart directly. Provider-native orders carry `null` rather than an inferred cart. ### Superseded * **Previous examples** – Replaced the retired `X-Crave-Signature` body-only example, fixed five-attempt ladder, `order.confirmed` / `order.ready` / `order.completed` names, and `cart.abandoned` promise with the superseded `2026-08-04` contract. **August 11, 2026** Production-ready Storefront SDK documentation ### New * **Dart and Flutter SDK** – Added first-class installation, environment, secure-session, readiness, and typed-error guidance for `crave_storefront_sdk`. * **Flutter quickstart** – Added an end-to-end path for configuring a deployment, checking ordering readiness, loading a menu, and starting an order. ### Improved * **TypeScript SDK** – Updated current installation guidance to the exact `@craveup/storefront-sdk@2.0.1` patch while preserving the durable 1.x migration history. * **Environment safety** – Clarified that sandbox and production use separate deployments, variables, credentials, and session namespaces rather than an in-app production toggle. ### Fixed * **OpenAPI reproducibility** – Pointed Mintlify at the reviewed generated Storefront OpenAPI artifact committed with the documentation. * **Developer portal parity** – Replaced the retired browser-key example and stale documentation domain with the real SDK client and canonical docs links. **July 28, 2026** Scoped CLI package and MCP sign-in ### Improved * **CLI package** – The CLI is published as `@craveup/cli` instead of the unscoped `craveup` package. The installed command is still `craveup`. * **MCP sign-in** – The MCP server guide documents browser sign-in from chat (`start_crave_auth` and `complete_crave_auth`) and the discount tools. The CLI quickstart documents `login`, `whoami`, and `logout`. * **Environment isolation** – The MCP server requires `CRAVEUP_ENVIRONMENT` set to `sandbox` or `production`, and refuses a test or live key that doesn't match that environment before making a request. **July 17, 2026** Documentation overhaul and Crave Cloud guides ### New * **Quickstarts** – Added Next.js, React, vanilla JavaScript, and mobile quickstarts. * **Guides and component reference** – Added guides that include the POS integrations, and a reference page with an embedded preview for each UI component, plus an installation page. * **Crave Cloud** – Added the Crave Cloud overview, which explains how the developer package fits the managed platform. * **MCP server guide** – Added a guide to connecting AI agents to Crave tools through the CraveUp MCP server. ### Improved * **API key setup** – Made Storefront API key and `locationId` setup easier to find from the introduction. **October 19, 2025** Docs parity and post-checkout routing ### New * **Return URL support** – Added configurable return URLs across storefront API, admin API, and the SDK so partners can guide guests to custom destinations after checkout. * **Cart metadata hooks** – Extended cart payloads so loyalty and analytics tools can append metadata without breaking totals. ### Improved * **Mintlify parity** – Regenerated OpenAPI artifacts directly from Express routes and rewrote MDX guides so docs mirror production behaviour. * **SDK alignment** – Synced storefront SDK method names and request signatures with the latest Swagger definitions. ### Fixed * **Spec drift** – Resolved schema mismatches between Swagger and Mintlify by pointing both builds at the same generated artifact. * **Checkout redirects** – Patched edge cases where return URLs were dropped for certain ordering sessions. **September 15, 2025** Orders hub and Tailwind v4 migration ### New * **Orders hub** – Introduced a token-protected orders portal with session creation, revocation, and analytics wiring for operations teams. * **Embeddable pricing** – Shipped a drop-in pricing table, enterprise entity management, and sales-friendly landing pages. * **Responsive UI primitives** – Published responsive dialog and sheet components in the shared UI package for both dashboard and storefront use. ### Improved * **Tailwind v4 + shadcn** – Migrated every app to the Tailwind v4 pipeline, standardized tokens, and removed duplicated component code. * **Onboarding guidance** – Added unsaved-change bars, fulfilment method milestones, and confetti banners so merchants know when setup is complete. ### Fixed * **Checkout ergonomics** – Reworked the cart sidebar, order time picker, and thank-you flow to eliminate crashy states. * **Error consistency** – Normalized API error responses and logging across admin, storefront, and order services. **August 26, 2025** Location onboarding and order manager tooling ### New * **Location wizard** – Added account-setup steps with map pickers, contact info endpoints, and multi-location management inside the dashboard. * **Order manager API** – Expanded admin endpoints for active, scheduled, and historical orders with dashboards and detail drawers. * **Crave Admin shell** – Launched the standalone site for enterprise management alongside embeddable pricing and enterprise profiles. ### Improved * **Discount workflow** – Polished validation, loading states, and edit/delete flows for promotions. * **Ordering session flow** – Hardened session APIs, menu bundles, and redirect handling so storefronts stay in sync. ### Fixed * **Environment + slug bugs** – Resolved slug mismatches, missing env vars, and redirect loops introduced during the restructure. * **Checkout error states** – Tightened error messaging for bundle fetches, checkout validation, and order receipts. **July 16, 2025** Dashboard experience refresh ### New * **Store settings redesign** – Rolled out cohesive layouts for store info, fulfilment, holiday hours, tips, and notifications with mobile-friendly navigation. * **Developer workspace** – Introduced a Resend-inspired developer page with code previews, dark mode, and API contact flows. * **Onboarding wizard** – Delivered a multi-step welcome flow, sample dashboards, and progress trackers for new organizations. ### Improved * **Multi-location support** – Upgraded navigation, location selectors, and analytics to handle complex brands. * **Subscription management** – Updated pricing tiers, added cancellation banners, and clarified plan benefits in product copy. ### Fixed * **Stripe + auth flows** – Hardened payment intent handling, sign-up flows, and logout paths across admin and storefront apps. * **Dark mode polish** – Cleaned up contrast issues across headers, buttons, and schedule components. **April 15, 2025** Error handling and identity alignment ### New * **Menu templates & defaults** – Seeded menu, category, and modifier forms with templates, default schedules, and currency hints to shorten setup. * **Stytch metadata sync** – Synced organization metadata, subscription state, and location identifiers directly with Stytch. ### Improved * **Error boundary middleware** – Wrapped every admin route with a shared `withErrorHandler` helper to centralize logging and responses. * **Store settings** – Upgraded tipping logic, address flows, and onboarding redirects to guide merchants to completion. ### Fixed * **Validation gaps** – Smoothed subscription persistence, rehydrated location IDs, and tightened toast feedback during onboarding. * **Access controls** – Restricted dashboard-only routes and enforced metadata checks before exposing sensitive endpoints. **March 13, 2025** Swagger-first platformization ### New * **Comprehensive Swagger docs** – Authored storefront, admin, menu, analytics, discounts, and team endpoints with generated JSON sources. * **Shared packages** – Promoted env, db, logger, and utils into reusable workspace modules with type-safe exports. ### Improved * **Next.js 15 + modules** – Upgraded partner and storefront apps to Next.js 15, reorganized imports, and aligned modules with ESM standards. * **Repository hygiene** – Removed legacy guest ordering code, normalized naming, and cleaned duplicate utilities. ### Fixed * **Stripe + webhook logging** – Standardized logging hooks and resolved Stripe route regressions uncovered during doc generation. * **Storybook coverage** – Patched component loaders and accessibility props flagged while documenting new flows. **February 21, 2025** Turborepo restructure ### New * **Modular apps** – Split the monorepo into dedicated Express admin/storefront APIs and Next.js ordering/partner surfaces using the latest Turbo scaffolding. * **Admin console prototype** – Bootstrapped the Crave Admin app with data tables, navigation, and shared UI packages. * **UI kit publishing** – Added shadcn-ready components plus shared ESLint and TypeScript configs for every project. ### Improved * **Type safety** – Centralized types, resolved module resolution pitfalls, and aligned packages on strict TypeScript settings. * **Build tooling** – Added pnpm/Turbo scripts to install dependencies, lint, and test reliably across workspaces. ### Fixed * **Legacy imports** – Cleared unused hooks, duplicate components, and inconsistent paths carried over from earlier repos. * **Order endpoints** – Stabilized active/history/scheduled order routes ahead of the new admin console. **January 13, 2025** Checkout guardrails and component cleanup ### New * **Customer card metadata** – Aligned stored card records with customer IDs so repeat guests see the right payment options. * **Form primitives** – Introduced reusable checkbox and wrapper components ahead of the full shadcn migration. ### Improved * **Checkout layout** – Tightened page wrappers, skeleton states, and CTA spacing to reduce friction on mobile. * **Cart experience** – Smoothed quantity controls and tip defaults while preparing the cart sidebar revamp. ### Fixed * **Payment glitches** – Resolved regressions around card selection, validation, and optimistic UI while orders are syncing. * **Styling drift** – Squashed stray pointer-events, HTML entities, and prop casing issues that surfaced after the holiday builds. **December 16, 2024** Order notifications and menu manager polish ### New * **Transactional messaging** – Wired SendGrid email and Twilio SMS sends so guests and teams receive real-time order confirmations. * **Store preview mockup** – Embedded an iPhone live preview within store settings so teams see branding updates instantly. * **Menu manager shortcuts** – Enabled expanding categories by default and adding items/categories directly from the overview screen. ### Improved * **Orders workspace** – Added filtered views, range calendars, and status chips to streamline fulfillment workflows. * **Dashboard navigation** – Introduced dynamic store-settings navigation, refreshed onboarding copy, and persisted trial banners. ### Fixed * **Checkout polish** – Tightened tip defaults, modifier validation, payment button behaviour, and cart totals after shadcn component migration. * **Menu reliability** – Resolved nested button hydration errors, null checks, and pointer-event regressions spotted during QA. **November 19, 2024** Merchant console polish and operational tooling ### New * **Order operations workspace** – Added filtered order lists, export tooling, and richer status insights so operators can reconcile sales without leaving the dashboard. * **Team invitations & roles** – Introduced invite flows with pending/expired states, location scoping, and inline status badges for a clearer view of collaborator access. * **API key lifecycle controls** – Surfaced key creation and deletion inside the developer settings so teams can rotate credentials without engineering help. ### Improved * **Onboarding completion flow** – Refined step guidance, loaders, and success messaging to celebrate completion and nudge merchants toward key setup actions. * **Location metadata** – Polished slugs, SEO metadata, and storefront links for cleaner sharing and cross-linking across partner surfaces. ### Fixed * **Authentication cookies** – Hardened Stytch cookie handling to resolve cross-domain login edge cases and flaky session persistence. * **Address capture** – Patched location onboarding to guard against partially saved address steps and duplicate business details. **October 29, 2024** Store settings and developer tools expansion ### New * **Developer center** – Published an in-app developers page with API key generation, waiter tip configuration, and quick links back to docs. * **Discount builder** – Delivered a guided form for creating percentage and amount-off promos with usage limits, schedules, and summary previews. * **Store settings depth** – Added waiter-tip policies, tax rate cards, and granular fulfillment scheduling to cover operational edge cases. ### Improved * **Onboarding progression** – Synced the universal task checklist with confetti states, loader components, and error handling for a smoother start. * **Performance polish** – Introduced shimmer loaders, refined layout spacing, and reorganized folders to keep the dashboard responsive at scale. ### Fixed * **Endpoint reliability** – Tightened API contracts, types, and environment configuration so admin traffic stops tripping validation errors in production. * **Discount validation** – Addressed edge cases around duplicate codes, date ranges, and negative values before launch. **October 17, 2024** Menu manager GA and guided onboarding ### New * **Guided onboarding** – Rolled out progress badges, celebratory confetti, and contextual upsells so merchants know exactly what unlocks go-live. * **Menu studio** – Enabled create/edit/delete flows for menus, categories, products, and modifier groups directly inside the dashboard. * **Team management** – Connected invite, delete, and list endpoints so admins can manage collaborators without support tickets. ### Improved * **Fulfillment settings** – Added tabbed forms, schedule pickers, and defaults across delivery, pickup, and room service to cut configuration time. * **Store hours tooling** – Synced location hours with validation, auto-fill defaults, and address autocomplete to reduce onboarding friction. ### Fixed * **Authentication & routing** – Resolved stale token handling, ensured location fetches respect organization context, and removed unused codepaths. **October 9, 2024** Stripe subscriptions and discount workflows ### New * **Stripe subscriptions** – Wired subscription plans, free trial entry points, and Connect onboarding so teams can self-serve upgrades. * **Discount workflows** – Completed the promotion builder with date/time scheduling, code generation, and React Hook Form summaries. ### Improved * **Start free trial UX** – Refined copy, country defaults, and toast feedback to boost conversion through the billing funnel. * **Connect experiences** – Iterated on Stripe Connect screens and reusable dropdowns for a consistent payments setup journey. ### Fixed * **Location data hydration** – Hardened location loaders and hook defaults so dashboards stop flashing empty states on refresh. * **Package hygiene** – Raised dependency baselines to clear high-severity security advisories. **September 24, 2024** Identity, analytics, and scheduling platform ### New * **Stytch SSO** – Replaced bespoke auth with Stytch-powered signup, login, and organization switching, unlocking OAuth and email-first flows. * **Subscription plans hub** – Released subscription management with plan selection, add-ons, and plan enforcement inside the dashboard. * **Analytics foundation** – Delivered merchant analytics endpoints, export tooling, and dashboard charts for real-time performance tracking. ### Improved * **Scheduling UI** – Rebuilt fulfillment scheduling with reusable components, validation, and error prompts that mirror the live storefront logic. * **Order operations** – Added order action toasts, filtered lists, and skeleton states to help managers triage tickets faster. ### Fixed * **Security posture** – Cleared outstanding vulnerability alerts by bumping packages and removing unused dependencies. * **Integration wiring** – Consolidated scattered fetchers and unused endpoints to keep telemetry dashboards accurate. **September 5, 2024** Checkout hardening and performance polish ### New * **OTP flows** – Added resend timers, auto-submit, and inline error toasts for a seamless verification experience on checkout. * **Saved payment controls** – Enabled guests to remove saved cards and clear cart state once an order is complete. ### Improved * **Loading states** – Rolled out skeletons, loaders, and disabled states across homepage, cart, and checkout to improve perceived performance. * **Error messaging** – Surfaced precise validation feedback for modifiers, order time selectors, and fulfilment switching. ### Fixed * **UI alignment** – Patched navbar spacing, modal heights, and image ratios so the storefront feels polished on every device. * **Cart consistency** – Squashed duplicate items and race conditions introduced by rapid add/remove actions. **August 27, 2024** Storefront experience polish ### New * **Schedule delivery skeletons** – Added skeleton states, map previews, and order-time selectors that respect location availability. * **Complementary cart** – Recommended add-on items with dedicated sliders and API-backed data. * **Room service fulfillment** – Brought table-side fulfilment parity with delivery and pickup, including modal flows and validations. ### Improved * **Cart logic** – Refactored prepare-cart flows, ensured location IDs propagate, and tightened revalidation. * **Fulfillment designs** – Unified styling and responsiveness for fulfilment tabs, modals, and empty states. ### Fixed * **Add to cart edge cases** – Addressed rounding, skeleton flickers, and missing imagery in popular-product sliders. * **Type hygiene** – Cleaned up lingering TypeScript errors so builds stay green. **August 17, 2024** Business Manager rebuild ### New * **Menu editor** – Added data tables, inline dialogs, and bulk actions for menus, categories, products, and modifiers. * **Operational pages** – Launched dedicated views for discounts, statements, teams, integrations, and account settings. * **Payments setup** – Integrated Stripe Setup Intents, OTP flows, and bank account onboarding for merchants. ### Improved * **Component library** – Expanded Tremor-based components, wrappers, and responsive layouts used across onboarding. * **Cart & checkout UX** – Finished checkout flows with skeletons, promo code modals, and cart formatting parity. ### Fixed * **Product dialogs** – Resolved duplicate renders, scroll traps, and hardcoded imagery that crept into the early rebuild. * **Type coverage** – Swept through new packages to align on shared types and eliminate implicit any usage. **August 3, 2024** Redux storefront and checkout flows ### New * **Redux Toolkit** – Centralized storefront state, unlocking persisted carts, fulfilment toggles, and shared selectors. * **Fulfilment APIs** – Completed place-order, delivery timing, and gratuity endpoints with client integrations. * **Location info surface** – Exposed location details, tips, and announcements directly in the partner UI. ### Improved * **Navigation scaffolding** – Tightened sticky tab borders, section scrolling, and category selection experiences. * **Design tokens** – Extended Tailwind palette, typography, and shared buttons to keep storefront branding consistent. ### Fixed * **Cart formatting** – Normalized currency output and ensured duplicate add-to-cart mutations merge correctly. * **Legacy packages** – Removed unused dependencies before shipping to partners. **July 21, 2024** Partner app data layer ### New * **Data fetcher utilities** – Added SWR fetchers, shared constants, and API connectors for homepage and menu data. * **Homepage integrations** – Wired the Next.js storefront to live product, timing, and location endpoints. ### Improved * **Design system** – Continued Tailwind UI build-out with iconography, modals, and slider polish. * **Notifications** – Adopted react-toast notifications for system feedback. ### Fixed * **Code hygiene** – Deleted legacy scaffolding and unused exports left over from the first prototype. * **API casing** – Corrected header names and auth keys to match production conventions. **July 1, 2024** API keys and merchant locations ### New * **API key management** – Implemented key generation, rotation, and authorization middleware for partner integrations. * **Order manager endpoints** – Delivered status, fulfilment, and export routes for merchants to drive operations from the API. ### Improved * **Location access** – Linked API keys to location scoping and added guardrails for accessing multi-location menus. * **Documentation tooling** – Updated error naming, response shapes, and OpenAPI alignment across new endpoints. ### Fixed * **Endpoint inconsistencies** – Normalized casing (e.g., `X-API-Key`) and fixed authentication leaks discovered during QA. **June 21, 2024** Merchant onboarding and auth foundation ### New * **Onboarding wizard** – Launched multi-step onboarding with business, tax, schedule, and payments configuration. * **Customer auth** – Introduced OTP verification, login/logout flows, and customer session middleware. * **Merchant subscription** – Added plan subscription, plan cancellation guardrails, and Stripe setup intents. ### Improved * **Storybook coverage** – Brought all major dashboard and storefront components into Storybook for team-wide reviews. * **UX consistency** – Harmonized typography, spacing, and color tokens across shared packages. ### Fixed * **Validation gaps** – Patched schema validation for forms, ensuring bad inputs are caught client and server side. * **Session handling** – Closed logout edge cases and stale cookie states in the customer APIs. **June 12, 2024** Component library build-out ### New * **Atoms & molecules** – Shipped buttons, tabs, list tiles, checkout cards, toggles, modifiers, and more as reusable components. * **Storybook integration** – Documented the new component library with stories for every state. ### Improved * **Design tokens** – Expanded custom colors, font sizes, and line heights to match brand guidelines. * **Input ergonomics** – Refined form components, radio buttons, and selectors based on early feedback. ### Fixed * **Naming consistency** – Renamed components and files to align with PascalCase/Kebab-case conventions across the monorepo. * **Lint noise** – Cleaned up duplicate exports and lint warnings caused by rapid scaffolding. **June 3, 2024** Next.js storefront scaffolding ### New * **Next.js partner app** – Bootstrapped the partner storefront with routing, layout primitives, and base styling. * **UI primitives** – Added dialog, button, store cover, and item card components to accelerate vertical slice builds. ### Improved * **Font & theming** – Applied the Crave brand typography stack and color palette across the new app. ### Fixed * **Component duplication** – De-duped early experiments while consolidating on Tremor and internal UI kits. **April 7, 2024** Cart and order services ### New * **Cart lifecycle** – Implemented create, update, remove, and delete cart endpoints with quantity validation. * **Fulfilment prep** – Added cart item routes, gratuity calculations, and groundwork for order placement. ### Improved * **Rate limiting** – Hardened Express middleware to protect storefront APIs from abusive traffic. * **Code style** – Adopted Prettier and repository-wide formatting for the service codebase. ### Fixed * **Naming & structure** – Normalized file names and tightened up utilities to keep endpoints discoverable. **March 19, 2024** Storefront API foundation ### New * **Express storefront** – Shipped the initial Express service with database connectivity, store info, and menu/category endpoints. * **Time utilities** – Added shared utilities for operating hours, laying the groundwork for scheduling logic. ### Improved * **Database wiring** – Iterated on DB connections and data-reading layers to stabilize the new stack. ### Fixed * **Deployment scaffolding** – Cleaned up early config so the v2 API could run locally and in staging. **June 20, 2023** Growth automation suite ### New * **White-label iOS pipeline** – Enabled merchants to generate branded mobile apps straight from the dashboard with live previews. * **Meta Pixel integration** – Brought first-party attribution to both the dashboard and guest storefront for unified campaign tracking. * **Subscription safeguards** – Automated Stripe billing with past-due cancellations, trial countdowns, and customer-initiated plan management. ### Improved * **Onboarding journey** – Smoothed bank setup, delivery toggles, and setup guides so teams can resume exactly where they left off. * **Store settings** – Grouped settings by theme, refreshed analytics, and polished navigation for faster daily workflows. ### Fixed * **Mobile responsiveness** – Tightened guest storefront spacing and padding so menus read cleanly on every device. * **QR exports** – Resolved asset generation issues for print collateral and digital signage. **September 12, 2022** Merchant dashboard 2.1 ### New * **Menu editor revamp** – Delivered click-to-edit menus, real-time hours, and search-driven category expansion for faster merchandising. * **Zendesk + Google sign-in** – Embedded support workflows and SSO so operators stay productive without tab sprawl. * **Statements & QR tooling** – Generated monthly statements and on-demand QR codes for marketing placements. ### Improved * **Onboarding controls** – Added fulfilment-specific scheduling, tipping policies, and order-receiving preferences across SMS, email, and tablet. * **Guest ordering 2.0** – Honoured location time zones, deep-linked table-side orders, and refined tip behaviour across channels. ### Fixed * **DoorDash handoff** – Closed the loop on Drive delivery edge cases discovered during pilot launches. * **Global domain routing** – Hardened custom domain flows while we wrapped up Apple Pay validation. **March 26, 2021** Foundation of guest ordering ### New * **Search-first storefront** – Launched item and modifier search, popular product carousels, and multi-select modifiers. * **Merchant onboarding** – Introduced the first merchant onboarding, settings, and QR generation flows for digital menus. * **PMS ordering** – Enabled property management system ordering to serve hotel and resort partners. ### Improved * **Design system** – Swapped to the Lato typography stack, standardized imagery, and refined touch targets across mobile. * **Brand storytelling** – Debuted the EMC brand page with refreshed photography and Google Maps distance calculations. ### Fixed * **Tip accuracy** – Corrected gratuity calculations for multi-location partners. * **Modal UX** – Eliminated scrolling bugs and duplicate popular items during fast cart edits. *** Need the original Crave v1 timeline? Check the archived 2021–2023 release notes in the internal handbook or reach out at [hello@craveup.com](mailto:hello@craveup.com). # Source: https://craveup-1493c4c7.mintlify.dev/docs/components/cart/cart-item-row Individual cart line item with modifiers, quantity control, and price. # CartItemRow Renders a single line item in the cart, showing the product name, selected modifiers, special instructions, quantity stepper, and line total. ## Preview Desktop Mobile ## Import ```tsx theme={null} import { CartItemRow } from '@/components/CartItemRow' ``` ## Usage ```tsx theme={null} updateItem(cartItem.id, qty)} onRemove={() => removeItem(cartItem.id)} onEdit={() => editItem(cartItem.id)} /> ``` ## Props **item** `CartItem` *required* The cart item object with product details, modifiers, quantity, and price. **onUpdateQuantity** `(quantity: number) =\> void` *required* Callback fired when quantity is changed via the stepper. **onRemove** `() =\> void` *required* Callback fired when the item is removed (quantity reaches 0 or delete is clicked). **onEdit** `() =\> void` Optional callback to re-open the product customization screen. ## Behavior * Displays modifier selections as comma-separated tags * Shows special instructions in italics below modifiers * Swipe-to-delete gesture on mobile * Tap on item opens edit mode via `onEdit` # Source: https://craveup-1493c4c7.mintlify.dev/docs/components/cart/cart-nav-button Floating or header-mounted button showing cart item count and total. # CartNavButton A button that displays the current cart item count as a badge and optionally shows the cart total. Typically placed in the header or as a floating action button on mobile. ## Preview Desktop Mobile ## Import ```tsx theme={null} import { CartNavButton } from '@/components/CartNavButton' ``` ## Usage ```tsx theme={null} setIsCartOpen(true)} /> ``` ## Props **itemCount** `number` *required* Number of items currently in the cart. **total** `number` Cart total to display alongside the button text. **onClick** `() =\> void` *required* Callback fired when the button is clicked — typically opens the CartPanel. ## Behavior * Badge animates with a bounce effect when item count changes * Hides when cart is empty (itemCount === 0) * On mobile, renders as a fixed-position floating button at the bottom * On desktop, renders inline in the header navigation # Source: https://craveup-1493c4c7.mintlify.dev/docs/components/cart/cart-panel Slide-out panel displaying the current cart contents and order summary. # CartPanel A slide-out side panel that shows all items in the customer's cart, order summary with subtotal/tax/total, and a checkout button. ## Preview Desktop Mobile ## Import ```tsx theme={null} import { CartPanel } from '@/components/CartPanel' ``` ## Usage ```tsx theme={null} setIsCartOpen(false)} /> ``` ## Props **cart** `Cart` *required* The cart object containing items, totals, and applied discounts. **onUpdateItem** `(itemId: string, quantity: number) =\> void` *required* Callback to update an item's quantity. **onRemoveItem** `(itemId: string) =\> void` *required* Callback to remove an item from the cart. **onCheckout** `() =\> void` *required* Callback fired when the checkout button is clicked. **isOpen** `boolean` *required* Controls the panel's open/closed state. **onClose** `() =\> void` *required* Callback to close the panel. ## Behavior * Slides in from the right with backdrop overlay * Each item row shows name, modifiers summary, quantity stepper, and line total * Order summary section with subtotal, tax, discounts, and total * Empty state with illustration and "Browse menu" CTA * Traps focus when open for accessibility # Source: https://craveup-1493c4c7.mintlify.dev/docs/components/cart/cart-related-items Upsell carousel shown in the cart suggesting complementary items. # CartRelatedItems A horizontal carousel displayed within or below the cart panel that suggests related or complementary items to encourage upselling. ## Preview Desktop Mobile ## Import ```tsx theme={null} import { CartRelatedItems } from '@/components/CartRelatedItems' ``` ## Usage ```tsx theme={null} ``` ## Props **items** `Product[]` *required* Array of suggested products to display. **onAddItem** `(product: Product) =\> void` *required* Callback fired when a suggested item's add button is clicked. ## Behavior * Shows compact product cards with image, name, price, and quick-add button * Horizontally scrollable with peek effect * Items are determined by the backend based on cart contents * Hidden when no suggestions are available # Source: https://craveup-1493c4c7.mintlify.dev/docs/components/checkout/apply-promo-code Input field for applying discount codes to an order. # ApplyPromoCode A compact input with an apply button that lets customers enter and validate promotional discount codes during checkout. ## Preview Desktop Mobile ## Import ```tsx theme={null} import { ApplyPromoCode } from '@/components/ApplyPromoCode' ``` ## Usage ```tsx theme={null} ``` ## Props **onApply** `(code: string) =\> Promise\` *required* Async callback to validate and apply the promo code. Should return the discount result or throw on invalid codes. **appliedCode** `string` Currently applied promo code, if any. **onRemove** `() =\> void` Callback to remove the currently applied promo code. ## Behavior * Inline validation with loading state during API call * Shows success message with discount amount on valid code * Shows error message for invalid or expired codes * Displays applied code as a removable chip * Collapses to "Have a promo code?" link when no code is applied # Source: https://craveup-1493c4c7.mintlify.dev/docs/components/checkout/checkout-component Top-level checkout orchestrator that manages the multi-step checkout flow. # CheckoutComponent The main checkout container that orchestrates the multi-step checkout flow — customer details, fulfillment selection, payment, and order confirmation. ## Preview Desktop Mobile ## Import ```tsx theme={null} import { CheckoutComponent } from '@/components/CheckoutComponent' ``` ## Usage ```tsx theme={null} ``` ## Props **cart** `Cart` *required* The finalized cart to check out. **locationId** `string` *required* The location ID for this order. **onOrderComplete** `(order: Order) =\> void` *required* Callback fired when the order is successfully placed. ## Behavior * Multi-step flow: Customer Details → Fulfillment → Payment → Confirmation * Progress indicator at the top showing current step * Validates each step before allowing progression * Handles payment processing errors with retry * Displays order summary sidebar on desktop # Source: https://craveup-1493c4c7.mintlify.dev/docs/components/checkout/customer-details-form Form for collecting customer name, email, and phone number during checkout. # CustomerDetailsForm Collects customer contact information (name, email, phone) as the first step of the checkout flow. ## Preview Desktop Mobile ## Import ```tsx theme={null} import { CustomerDetailsForm } from '@/components/CustomerDetailsForm' ``` ## Usage ```tsx theme={null} ``` ## Props **initialValues** `CustomerDetails` Pre-filled values from a returning customer or saved session. **onSubmit** `(details: CustomerDetails) =\> void` *required* Callback fired when the form is submitted with valid data. ## Behavior * Validates email format and phone number * Remembers returning customer info via local storage * Phone input with country code selector * Auto-focuses the first empty field # Source: https://craveup-1493c4c7.mintlify.dev/docs/components/checkout/order-time-picker Date and time selector for scheduling pickup or delivery orders. # OrderTimePicker A picker that allows customers to choose between "ASAP" ordering or scheduling a future pickup/delivery time within the location's operating hours. ## Preview Desktop Mobile ## Import ```tsx theme={null} import { OrderTimePicker } from '@/components/OrderTimePicker' ``` ## Usage ```tsx theme={null} ``` ## Props **locationId** `string` *required* Location ID used to fetch available time slots. **fulfillmentType** `'pickup' | 'delivery'` *required* The fulfillment method — affects available time windows and lead times. **selectedTime** `Date | 'asap'` *required* The currently selected order time. **onTimeChange** `(time: Date | 'asap') =\> void` *required* Callback fired when the time selection changes. ## Behavior * "ASAP" toggle selected by default with estimated ready time * Date picker for future dates (within location's advance ordering window) * Time slots in 15-minute increments within operating hours * Grays out unavailable slots based on kitchen capacity # Source: https://craveup-1493c4c7.mintlify.dev/docs/components/checkout/payment-form Stripe Elements input for Stripe-only online checkout. # PaymentForm Renders Stripe Elements for an `ONLINE` order submission. Crave persists the canonical order before it creates or recovers the connected-account PaymentIntent. ## Preview Desktop Mobile ## Behavior * Read `checkout.getCollectionOptions` for the current cart before rendering. Mount this component only when the server-returned `ONLINE` option is available. * Submit the order with `collectionMode: "ONLINE"`; online responses never select Square, Clover, or Toast. * Mount Stripe Elements with the returned `clientSecret` and immutable `connectedAccountId`. * Poll `getOrderSubmissionOutcome` with the returned `attemptId` after confirmation, redirects, ambiguous responses, or browser restarts. * Reuse the original submission idempotency key. Never create a second order to recover a response. * Handle every online outcome status: `PAID` is settled, `PROCESSING` is still resolving, `CUSTOMER_ACTION_REQUIRED` needs the customer back in Stripe with the returned `clientSecret`, and `ACTION_REQUIRED` carries a `safeErrorCode` and needs a decision. `ACCEPTED` with a `verification` object belongs to pay-at-store collection and is never returned for `ONLINE`. * Raw card data stays in Stripe-hosted fields and is never accepted or logged by Crave application code. > [!WARNING] > > Square, Clover, and Toast are POS-native order and reconciliation > integrations. Do not load their browser payment SDKs or tokenize a POS payment > source in the storefront. Pay-at-store checkout has no payment form. > [!WARNING] > > While the outcome is `PROCESSING`, do not offer a retry that submits again. > The attempt is unresolved rather than failed, and a second submission charges > the customer twice. Re-poll with the same `attemptId` instead. # Source: https://craveup-1493c4c7.mintlify.dev/docs/components/checkout/tip-selector Preset and custom tip amount picker for the checkout flow. # TipSelector Allows customers to select a tip amount from preset percentages or enter a custom amount. Displays the calculated tip based on the order subtotal. ## Preview Desktop Mobile ## Import ```tsx theme={null} import { TipSelector } from '@/components/TipSelector' ``` ## Usage ```tsx theme={null} ``` ## Props **subtotal** `number` *required* Order subtotal used to calculate percentage-based tips. **selectedTip** `number` *required* The currently selected tip amount in cents. **onTipChange** `(amount: number) =\> void` *required* Callback fired when the tip selection changes. **presets** `number[]` (default: \[15, 18, 20, 25]) Array of percentage presets to display as quick-select buttons. ## Behavior * Preset percentage buttons with calculated dollar amounts * "Custom" option reveals a numeric input * "No tip" option to explicitly set tip to \$0 * Active preset is highlighted with primary accent # Source: https://craveup-1493c4c7.mintlify.dev/docs/components/fulfillment/delivery Delivery address form with validation and delivery zone checking. # Delivery Collects and validates a delivery address, checks if the address falls within the merchant's delivery zone, and displays estimated delivery time and fees. ## Preview Desktop Mobile ## Import ```tsx theme={null} import { Delivery } from '@/components/Delivery' ``` ## Usage ```tsx theme={null} ``` ## Props **locationId** `string` *required* The location ID to check delivery zones against. **onAddressConfirmed** `(address: DeliveryAddress) =\> void` *required* Callback fired when a valid delivery address is confirmed. ## Behavior * Google Places autocomplete for address input * Validates address against the location's delivery zones * Shows "Outside delivery area" error for out-of-range addresses * Displays delivery fee and estimated time for valid addresses * Optional delivery instructions text field # Source: https://craveup-1493c4c7.mintlify.dev/docs/components/fulfillment/fulfilment-method-handler Route-level handler that renders the appropriate fulfillment flow based on order type. # FulfilmentMethodHandler A routing component that determines and renders the correct fulfillment flow (delivery, table-side, room service) based on the ordering session's fulfillment method. ## Preview Desktop Mobile ## Import ```tsx theme={null} import { FulfilmentMethodHandler } from '@/components/FulfilmentMethodHandler' ``` ## Usage ```tsx theme={null} ``` ## Props **orderingSession** `OrderingSession` *required* The current ordering session containing the selected fulfillment method. **onFulfillmentComplete** `(details: FulfillmentDetails) =\> void` *required* Callback fired when fulfillment details are confirmed by the customer. ## Behavior * Reads the fulfillment method from the ordering session * Renders `Delivery`, `TableSide`, or `RoomService` sub-component accordingly * Falls back to pickup if no specific method is set * Passes collected details (address, table number, room number) up via callback # Source: https://craveup-1493c4c7.mintlify.dev/docs/components/fulfillment/room-service Room number and guest name input for hotel room service ordering. # RoomService Collects room number and guest name for hotel room service fulfillment. Validates the room number against the property's room directory. ## Preview Desktop Mobile ## Import ```tsx theme={null} import { RoomService } from '@/components/RoomService' ``` ## Usage ```tsx theme={null} ``` ## Props **locationId** `string` *required* The location (property) ID to validate room numbers against. **onRoomConfirmed** `(details: RoomServiceDetails) =\> void` *required* Callback fired when room details are confirmed. ## Behavior * Room number input with validation * Guest name field (required for room charge authorization) * Optional delivery instructions * Auto-populated when accessed via in-room QR code # Source: https://craveup-1493c4c7.mintlify.dev/docs/components/fulfillment/table-side Table number input for dine-in table-side ordering. # TableSide A simple input for customers to enter their table number for dine-in table-side ordering. Validates the table number against the location's configured tables. ## Preview Desktop Mobile ## Import ```tsx theme={null} import { TableSide } from '@/components/TableSide' ``` ## Usage ```tsx theme={null} ``` ## Props **locationId** `string` *required* The location ID to validate table numbers against. **onTableConfirmed** `(tableNumber: string) =\> void` *required* Callback fired when a valid table number is submitted. ## Behavior * Numeric input with large, touch-friendly buttons * Validates table number exists for the location * Shows error for invalid table numbers * Auto-populated when accessed via QR code scan with table parameter # Installation Source: https://craveup-1493c4c7.mintlify.dev/docs/components/installation Install dependencies and structure your app for Crave UI components. Crave UI components are local React components that sit inside your storefront app. They pair with the [Storefront SDK](/docs/getting-started/storefront-sdk), Tailwind CSS, and shadcn/ui conventions so you can own the markup, styling, and ordering flows. Choose the setup that matches your starting point. > [card] [Public API setup](/docs/getting-started/storefront-sdk) > > Configure the API origin, merchant slug, and location ID without a browser > credential. > [card] [Use the CLI](#use-the-cli) > > Inspect one of the current legacy public storefront examples locally. > [card] [Existing app](#existing-app) > > Add the SDK, shared UI dependencies, and component source to an app you > already own. > [card] [Project structure](#project-structure) > > See where components, API helpers, and shared utilities should live. ## Use the CLI The released CLI 1.x can clone one of the current legacy public examples and write its public storefront settings. These examples do not define the current production SDK or component contract and require migration and review before deployment. ```bash theme={null} npx @craveup/cli init ``` Then run the generated app: ```bash theme={null} cd crave-storefront pnpm install pnpm dev ``` For new production work, use the exact-pinned Storefront SDK guide and the component contracts in these docs as the source of truth. Treat the CLI 1.x examples as implementation references only. ## Existing app For an existing React or Next.js app, install the SDK first: ```bash theme={null} pnpm add --save-exact @craveup/storefront-sdk@2.0.1 ``` If your app does not already use shadcn/ui, initialize it before copying component source: ```bash theme={null} pnpm dlx shadcn@latest init ``` Install the shared UI utilities used by the component examples: ```bash theme={null} pnpm add class-variance-authority clsx tailwind-merge lucide-react ``` Then adapt the documented component examples inside your app's `components` directory and keep the SDK transport, ordering state, and presentation boundaries explicit. ## Project structure Use a structure that keeps UI, data access, and ordering state separate: ```txt theme={null} src/ app/ menu/ cart/ checkout/ components/ menu/ cart/ checkout/ fulfillment/ modifiers/ post-order/ ui/ lib/ storefront-client.ts utils.ts types/ storefront.ts ``` ## Configure the SDK Create a shared Storefront SDK client and import it from your data loaders, hooks, or server actions. Get the published location ID and merchant slug from Crave Business Manager. Configure the public API origin explicitly. ```ts filename="src/lib/storefront-client.ts" theme={null} import { createStorefrontClient } from "@craveup/storefront-sdk"; export const storefrontClient = createStorefrontClient({ baseUrl: process.env.NEXT_PUBLIC_CRAVEUP_API_URL!, sessionStore, getAuthToken, getMerchantSlug: () => merchantSlug, }); ``` For customer flows, source `getAuthToken` from the active Clerk session with the `crave-customer` token template. Clerk owns token persistence and refresh; do not store the JWT in application storage. `getMerchantSlug` is required for customer operations so Crave can route the same Clerk diner to the correct restaurant organization. Add the required environment variables: ```env filename=".env.local" theme={null} NEXT_PUBLIC_CRAVEUP_API_URL=https://api.craveup.com NEXT_PUBLIC_CRAVEUP_LOCATION_ID=loc_abc123 NEXT_PUBLIC_CRAVEUP_MERCHANT_SLUG=demo-cafe ``` ## Import components Crave component docs use local imports so you can customize the implementation: ```tsx theme={null} import { CartPanel } from "@/components/cart/cart-panel"; import { Item } from "@/components/menu/item"; import { MenuSwitcher } from "@/components/menu/menu-switcher"; ``` Keep the component source in your app, then pass SDK data and callbacks from your own routes or state layer. ## Next steps > [card] [Components Overview](/docs/components/overview) > > Browse the full component catalog. > [card] [Storefront SDK](/docs/getting-started/storefront-sdk) > > Configure the typed API client used by the components. > [card] [Display Menu](/docs/guides/display-menu) > > Fetch menu data and render categories, products, and modifiers. > [card] [Manage Cart](/docs/guides/manage-cart) > > Wire cart creation, item updates, discounts, and checkout handoff. # Source: https://craveup-1493c4c7.mintlify.dev/docs/components/menu/category-tabs Sticky tab navigation for browsing menu categories. # CategoryTabs A horizontal tab bar that displays menu categories with an active indicator. Sticks to the top of the viewport as the user scrolls through the menu. ## Preview Desktop Mobile ## Import ```tsx theme={null} import { CategoryTabs } from '@/components/CategoryTabs' ``` ## Usage ```tsx theme={null} scrollToCategory(id)} /> ``` ## Props **categories** `Category[]` *required* Array of menu categories to display as tabs. **activeCategory** `string` *required* The ID of the currently active/visible category. **onCategoryChange** `(categoryId: string) =\> void` *required* Callback fired when a tab is clicked — typically scrolls to the category section. ## Behavior * Sticks to the top of the viewport below the header on scroll * Highlights the active category based on scroll position * Horizontally scrollable on mobile for long category lists * Smooth-scrolls the active tab into view automatically # Source: https://craveup-1493c4c7.mintlify.dev/docs/components/menu/item Unified product card that renders vertical or horizontal layouts. # Item A versatile product card component that displays a menu item with image, name, description, price, and a quick-add button. Supports both vertical (grid) and horizontal (list) layouts. ## Preview Desktop Mobile ## Import ```tsx theme={null} import { Item } from '@/components/Item' ``` ## Usage ```tsx theme={null} {/* Vertical layout for grid view */} {/* Horizontal layout for list view */} ``` ## Props **product** `Product` *required* The product object containing name, description, price, images, and modifier groups. **layout** `'vertical' | 'horizontal'` (default: vertical) Controls the card layout direction. **onAdd** `(product: Product) =\> void` *required* Callback fired when the add button is clicked. If the product has modifiers, this should open the `ProductDescriptionScreen`. ## Behavior * Truncates long descriptions with ellipsis * Shows product image with fallback placeholder * Quick-add button bypasses modifier screen when no modifiers exist * Displays "From \$X.XX" when modifier groups affect pricing # Source: https://craveup-1493c4c7.mintlify.dev/docs/components/menu/item-carousel Horizontal carousel for featured or recommended menu items. # ItemCarousel A horizontally scrollable carousel that displays a row of product cards. Used for featured items, recommendations, or category highlights. ## Preview Desktop Mobile ## Import ```tsx theme={null} import { ItemCarousel } from '@/components/ItemCarousel' ``` ## Usage ```tsx theme={null} ``` ## Props **items** `Product[]` *required* Array of products to display in the carousel. **title** `string` Optional heading displayed above the carousel. **onItemClick** `(product: Product) =\> void` *required* Callback fired when a carousel item is clicked. ## Behavior * Touch-friendly horizontal scrolling on mobile * Peek effect showing partial next card to indicate scrollability * Renders each item using the vertical `Item` component # Source: https://craveup-1493c4c7.mintlify.dev/docs/components/menu/menu-switcher Dropdown to switch between multiple menus with availability status. # MenuSwitcher A dropdown selector that allows customers to switch between multiple menus (e.g., Breakfast, Lunch, Dinner). Displays availability status based on operating hours. ## Preview Desktop Mobile ## Import ```tsx theme={null} import { MenuSwitcher } from '@/components/MenuSwitcher' ``` ## Usage ```tsx theme={null} setActiveMenu(menuId)} /> ``` ## Props **menus** `Menu[]` *required* Array of available menus for the location. **activeMenuId** `string` *required* The ID of the currently selected menu. **onMenuChange** `(menuId: string) =\> void` *required* Callback fired when a different menu is selected. ## Behavior * Shows "Available now" or "Available at 11:00 AM" based on daypart logic * Grays out menus outside their operating hours * Auto-selects the first available menu on mount # Source: https://craveup-1493c4c7.mintlify.dev/docs/components/modifiers/item-counter-button Increment/decrement stepper for adjusting item or modifier quantities. # ItemCounterButton A compact stepper control with minus/plus buttons and a quantity display. Used for adjusting item quantities in the cart and modifier option counts. ## Preview Desktop Mobile ## Import ```tsx theme={null} import { ItemCounterButton } from '@/components/ItemCounterButton' ``` ## Usage ```tsx theme={null} setQuantity(q => q + 1)} onDecrement={() => setQuantity(q => q - 1)} min={1} max={99} /> ``` ## Props **count** `number` *required* The current quantity value. **onIncrement** `() =\> void` *required* Callback fired when the plus button is clicked. **onDecrement** `() =\> void` *required* Callback fired when the minus button is clicked. **min** `number` (default: 0) Minimum allowed value. Decrement button is disabled at this value. **max** `number` (default: 99) Maximum allowed value. Increment button is disabled at this value. ## Behavior * Disables minus button when count reaches `min` * Disables plus button when count reaches `max` * Animates the count value on change * Compact variant available for inline use in modifier options # Source: https://craveup-1493c4c7.mintlify.dev/docs/components/modifiers/modifier-group Renders a group of modifier options (radio, checkbox, or counter) for product customization. # ModifierGroup Displays a single modifier group (e.g., "Choose your size", "Add toppings") with its options. Supports radio (single-select), checkbox (multi-select), and counter (quantity) input types. ## Preview Desktop Mobile ## Import ```tsx theme={null} import { ModifierGroup } from '@/components/ModifierGroup' ``` ## Usage ```tsx theme={null} ``` ## Props **group** `ModifierGroup` *required* The modifier group object containing name, options, min/max selections, and input type. **selections** `ModifierSelection[]` *required* Currently selected modifiers for this group. **onSelectionChange** `(selections: ModifierSelection[]) =\> void` *required* Callback fired when modifier selections change. ## Behavior * Enforces min/max selection constraints with visual feedback * Radio groups auto-deselect previous option * Counter inputs respect per-option quantity limits * Displays price adjustments next to each option (e.g., "+\$1.50") # Source: https://craveup-1493c4c7.mintlify.dev/docs/components/modifiers/product-description-screen Full-screen product detail view with modifiers, quantity, and add-to-cart action. # ProductDescriptionScreen A full-screen overlay that shows detailed product information including image, description, modifier groups, quantity selector, and an add-to-cart button with running total. ## Preview Desktop Mobile ## Import ```tsx theme={null} import { ProductDescriptionScreen } from '@/components/ProductDescriptionScreen' ``` ## Usage ```tsx theme={null} ``` ## Props **product** `Product` *required* The product to display, including all modifier groups. **onAddToCart** `(item: CartItem) =\> void` *required* Callback fired when the user confirms selections and adds the item to cart. **onClose** `() =\> void` *required* Callback to dismiss the screen. ## Behavior * Displays product hero image with parallax scroll effect * Renders all modifier groups using `ModifierGroup` components * Shows running price total that updates as modifiers are selected * Validates required modifier groups before enabling the add button * Supports special instructions text input at the bottom # Source: https://craveup-1493c4c7.mintlify.dev/docs/components/modifiers/special-instructions Text input for customer notes and special requests on a menu item. # SpecialInstructions A text area input that allows customers to add special instructions or notes to a menu item (e.g., "no onions", "extra sauce on the side"). ## Preview Desktop Mobile ## Import ```tsx theme={null} import { SpecialInstructions } from '@/components/SpecialInstructions' ``` ## Usage ```tsx theme={null} ``` ## Props **value** `string` *required* The current instructions text. **onChange** `(value: string) =\> void` *required* Callback fired when the text changes. **placeholder** `string` (default: Special instructions...) Placeholder text shown when the input is empty. **maxLength** `number` (default: 250) Maximum character limit for the instructions. ## Behavior * Character counter displayed when approaching the limit * Expandable text area that grows with content * Optional — collapses to a single-line prompt when empty # Components Source: https://craveup-1493c4c7.mintlify.dev/docs/components/overview Pre-built React components for menu browsing, cart management, checkout, and fulfillment. Crave provides restaurant-specific React components that integrate with your [shadcn/ui](https://ui.shadcn.com) design system. Drop them into your storefront to handle menu display, cart logic, checkout, and fulfillment — then style them to match your brand. > [card] [Installation](/docs/components/installation) > > Set up dependencies, project structure, and component source in your storefront. > [card] [Configure the SDK](/docs/getting-started/storefront-sdk) > > Add the public API origin, merchant slug, and location ID without a browser credential. ## Menu & Products Display menus, categories, and product cards. > [card] [CategoryTabs](/docs/components/menu/category-tabs) > > Sticky tab navigation for menu categories with active indicator. > [card] [MenuSwitcher](/docs/components/menu/menu-switcher) > > Dropdown to switch between menus (lunch, dinner) with availability. > [card] [Item](/docs/components/menu/item) > > Product card — renders vertical or horizontal with quick-add. > [card] [ItemCarousel](/docs/components/menu/item-carousel) > > Carousel for featured or recommended menu items. ## Modifiers Product customization — sizes, toppings, special instructions. > [card] [ModifierGroup](/docs/components/modifiers/modifier-group) > > Renders modifier groups (e.g., size, toppings) with selection state. > [card] [ProductDescriptionScreen](/docs/components/modifiers/product-description-screen) > > Full-screen modal for product details, modifiers, and add-to-cart. > [card] [SpecialInstructions](/docs/components/modifiers/special-instructions) > > Textarea for customer special requests and dietary notes. > [card] [ItemCounterButton](/docs/components/modifiers/item-counter-button) > > Quantity selector with increment/decrement buttons. ## Cart Manage the shopping cart. > [card] [CartPanel](/docs/components/cart/cart-panel) > > Side drawer showing cart contents with checkout CTA. > [card] [CartNavButton](/docs/components/cart/cart-nav-button) > > Header button showing item count — opens the cart panel. > [card] [CartItemRow](/docs/components/cart/cart-item-row) > > Individual cart item with modifiers, quantity controls, and price. > [card] [CartRelatedItems](/docs/components/cart/cart-related-items) > > Recommended upsell items shown inside the cart. ## Checkout Customer details, payments, and order submission. > [card] [CheckoutComponent](/docs/components/checkout/checkout-component) > > Main checkout layout orchestrating all checkout sections. > [card] [CustomerDetailsForm](/docs/components/checkout/customer-details-form) > > Form for name, email, and phone with validation. > [card] [PaymentForm](/docs/components/checkout/payment-form) > > Stripe PaymentElement wrapper for card and payment methods. > [card] [TipSelector](/docs/components/checkout/tip-selector) > > Interactive tip selection with presets and custom input. > [card] [OrderTimePicker](/docs/components/checkout/order-time-picker) > > ASAP or scheduled pickup/delivery time selector. > [card] [ApplyPromoCode](/docs/components/checkout/apply-promo-code) > > Promo code input with validation and discount display. ## Fulfillment Order fulfillment method selection — delivery, pickup, table-side, room service. > [card] [FulfilmentMethodHandler](/docs/components/fulfillment/fulfilment-method-handler) > > Routes to the correct fulfillment UI based on method. > [card] [DeliveryFulfillment](/docs/components/fulfillment/delivery) > > Address picker and delivery details. > [card] [TableSideFulfillment](/docs/components/fulfillment/table-side) > > Table number selection for dine-in service. > [card] [SelectRoomNumber](/docs/components/fulfillment/room-service) > > Room number and guest name input for hotel room service. ## Post-Order Order confirmation and feedback. > [card] [OrderConfirmation](/docs/components/post-order/order-confirmation) > > Thank-you screen with order details and next steps. > [card] [ExperienceRating](/docs/components/post-order/experience-rating) > > Star rating component for post-order feedback. # Source: https://craveup-1493c4c7.mintlify.dev/docs/components/post-order/experience-rating Post-order feedback widget for rating the ordering experience. # ExperienceRating A feedback widget shown after order completion that lets customers rate their experience with star ratings and optional text feedback. ## Preview Desktop Mobile ## Import ```tsx theme={null} import { ExperienceRating } from '@/components/ExperienceRating' ``` ## Usage ```tsx theme={null} ``` ## Props **orderId** `string` *required* The order ID to associate the feedback with. **onSubmit** `(rating: FeedbackRating) =\> void` *required* Callback fired when the customer submits their rating. **onDismiss** `() =\> void` *required* Callback fired when the customer dismisses the rating prompt. ## Behavior * 5-star rating with tap/click interaction * Optional text feedback field appears after rating * Category tags for specific feedback (food quality, speed, accuracy) * Submits to the analytics events API * Only shown once per order # Source: https://craveup-1493c4c7.mintlify.dev/docs/components/post-order/order-confirmation Post-checkout screen showing order details, status, and estimated ready time. # OrderConfirmation The confirmation screen displayed after a successful order placement. Shows the order number, item summary, estimated ready/delivery time, and real-time status updates. ## Preview Desktop Mobile ## Import ```tsx theme={null} import { OrderConfirmation } from '@/components/OrderConfirmation' ``` ## Usage ```tsx theme={null} ``` ## Props **order** `Order` *required* The placed order object with items, totals, status, and fulfillment details. **onTrackOrder** `() =\> void` Optional callback to navigate to the order tracking view. ## Behavior * Displays order number with a checkmark success animation * Shows estimated ready time or delivery ETA * Lists ordered items with quantities and prices * Real-time status updates via polling or WebSocket * "Track your order" CTA for delivery orders * "Order again" button to reorder the same items # CLI Quickstart Source: https://craveup-1493c4c7.mintlify.dev/docs/getting-started/cli-quickstart Use Crave CLI 1.x to inspect and configure a pinned legacy storefront example. The Crave CLI 1.x clones a current public storefront example, writes its public environment settings, installs dependencies, and can start the local development server. It is a fast way to inspect the existing integration shape, not a substitute for production review. > [!NOTE] > > The CLI publishes as **`@craveup/cli`**. The older unscoped `craveup` package > on npm is unmaintained and stops at 1.0.3 — install the scoped name. The > installed command is still `craveup`, so `craveup login` and the rest are > unchanged. > [!WARNING] > > The three current CLI 1.x choices are legacy public examples pinned to fixed > Git commits for reproducibility. They predate the production-proven web and > Expo generator releases now being validated. Review and migrate dependencies, > browser security, exact origins, and the complete sandbox ordering flow before > deploying one. For a new implementation, treat the published Storefront API > and SDK guides as the current contract. ## Install & run Run the CLI anywhere you want to create the project directory: ```bash theme={null} npx @craveup/cli init ``` The wizard will guide you through: * Choosing a legacy public example (`storefront-default`, Tomodachi Sushi, or Xichuan Noodles) * Selecting the published organization and location * Naming the project directory * Installing dependencies with your detected package manager * Optionally starting `pnpm dev` so you can preview immediately ## Sign in Sign in before scaffolding so the CLI can discover the organizations and locations your account can manage: ```bash theme={null} npx @craveup/cli login # browser OAuth; sign in or create a free account npx @craveup/cli whoami # confirm the active account npx @craveup/cli logout # remove local credentials ``` The session is stored in the macOS keychain, falling back to `~/.config/craveup/credentials.json`, and is **shared with the [CraveUp MCP server](/docs/guides/ai/craveup-mcp-server)** — signing in through either one satisfies the other. On a headless or remote machine, use `craveup login --device` to pair with a code you open on any other device. ## Non-interactive usage Prefer automation or CI pipelines? Use flags to skip prompts. | Flag | Description | | - | - | | `--template ` | Force a template (`storefront-default`, `tomodachi-sushi`, or `xichuan-noodles`) | | `--dir ` | Set the target directory name | | `--api-key ` | Optional server-only CLI credential for non-interactive private API access | | `--location-id ` | Provide the location ID for single-location templates | | `--org-slug ` | Provide the organization slug for organization templates | | `--skip-install` | Scaffold files without running the package manager | | `--force` | Overwrite an empty directory without confirmation | Example: ```bash theme={null} npx @craveup/cli init \ --template storefront-default \ --dir crave-storefront \ --org-slug my-restaurant-group \ --skip-install ``` ## Environment variables The CLI creates or updates `.env.local` with public storefront settings: ```env theme={null} # Public Storefront API origin. No browser API key is used. NEXT_PUBLIC_CRAVEUP_API_URL=https://api.craveup.com NEXT_PUBLIC_CRAVEUP_LOCATION_ID=loc_abc123 NEXT_PUBLIC_CRAVEUP_MERCHANT_SLUG=my-restaurant-group ``` > Tip: `CRAVEUP_DASHBOARD_URL`, `CRAVEUP_PARTNER_API_URL`, and a private `CRAVEUP_API_KEY` are CLI/server concerns. They are never written to a public storefront environment variable. The merchant and location variables are standalone/local overrides. A hosted `cravejs-storefront-template` resolves the merchant from its controlled host/subdomain and the location from the `[locationId]` route instead of duplicating tenant selection in production environment variables. The CLI does not write `NEXT_PUBLIC_STOREFRONT_URL`; the template derives its canonical metadata origin from the request host. Add that optional override manually only when the deployed metadata origin must differ from the request host. ## Example anatomy and production boundary The current examples do not share one guaranteed framework or dependency baseline. Inspect the generated `package.json` and lockfile before changing the project. Do not assume that a CLI 1.x example already contains Next.js 16.3, `@craveup/storefront-sdk@2.0.1`, the current component structure, or the complete browser-security contract. For new production implementation, start with the exact-pinned [Storefront SDK guide](./storefront-sdk) and the relevant web or mobile quickstart, then validate the sandbox vertical slice before release. Explore the generated repository after the CLI finishes: ```bash theme={null} cd crave-storefront pnpm install # if you skipped installation pnpm dev --port 3000 ``` You now have the selected example running locally. Continue to the [Storefront SDK guide](./storefront-sdk) to build against the current public contract and review the [deployment boundary](/docs/guides/deployment) before accepting traffic. # Dart and Flutter Storefront SDK Source: https://craveup-1493c4c7.mintlify.dev/docs/getting-started/flutter-storefront-sdk Build typed Flutter storefronts against the public Crave Storefront API. `crave_storefront_sdk` is the official Dart client for Flutter mobile, web, and desktop storefronts. It exposes the same reviewed `/api/v1/storefront` contract as [`@craveup/storefront-sdk`](/docs/getting-started/storefront-sdk), with Dart-native models, cancellation, timeouts, and typed exceptions. It contains no UI, Flutter, or native runtime dependency. ## Install the exact release ```yaml pubspec.yaml theme={null} dependencies: crave_storefront_sdk: 0.2.0 ``` Run `flutter pub get`. Dart-only consumers can run `dart pub get` instead. ## Configure one environment and merchant ```dart theme={null} import 'package:crave_storefront_sdk/crave_storefront_sdk.dart'; final client = CraveStorefrontClient( baseUri: Uri.parse('https://api.craveup.com'), merchantSlug: 'downtown-pizza', sessionStore: secureSessionStore, customerTokenProvider: () => clerkSession.getToken( template: 'crave-customer', ), ); ``` Use the exact sandbox API origin provided for your account in sandbox builds. Production and sandbox are separate deployments with separate environment variables, credentials, and data; do not add a runtime environment switch to a production app. The client accepts plain HTTP only for exact loopback hosts during local development. `StorefrontSessionStore` is application-owned. In production, implement it with encrypted platform storage and isolate records by the supplied API-origin, merchant, and location scope. The included `InMemoryStorefrontSessionStore` is only for tests and ephemeral demos. The customer token provider must retrieve a current short-lived token from the active Clerk session. Let Clerk own persistence, refresh, recovery, and logout; do not copy customer JWTs into the cart session store or application storage. ## Check ordering readiness Check availability before presenting an ordering action. This anonymous GET does not create a cart: ```dart theme={null} final readiness = await client.locations.getOrderingReadiness( locationId, fulfillmentMethod: FulfillmentMethod.takeout, ); switch (readiness) { case OrderingReady(): showStartOrder(); case OrderingUnavailable(:final reason): showOrderingUnavailable(reason); } ``` ## Handle typed failures ```dart theme={null} try { final menu = await client.menus.getForLocation(locationId, menuOnly: true); renderMenu(menu); } on StorefrontApiException catch (error) { reportSafeFailure(error.code, error.status, error.requestId); } on StorefrontTimeoutException { showRetryMessage(); } on StorefrontRequestCancelledException { // The owning screen was disposed or the shopper cancelled the action. } ``` The exception contract excludes resolved URLs, headers, request bodies, customer data, and payment values. Cart mutations are never retried implicitly. After `CART_CONFLICT`, re-read the cart, reconcile the new revision, and let the shopper confirm the next mutation. Close the client when its application-level owner is disposed: ```dart theme={null} client.close(); ``` > [card] [Build a Flutter storefront](/docs/quickstarts/flutter) > > Install the package, configure secure session storage, load a menu, and start > an order. # Build with Crave Source: https://craveup-1493c4c7.mintlify.dev/docs/getting-started/introduction Start with your coding agent, then explore Crave storefronts, APIs, and supported integrations. Crave gives food and beverage developers the ordering layer they usually have to stitch together themselves: menu data, modifiers, cart state, checkout, fulfillment, payments, analytics, reusable UI components, and APIs that work across web and mobile apps. Crave.js is the storefront developer surface inside **Crave Cloud**, a managed platform for franchise ordering, identity boundaries, loyalty integrations, payment routing, and multi-location operations. ## Start with your coding agent Give your agent the setup guide and let it inspect your app, connect current Crave documentation, and verify the integration in Sandbox. ```text wrap theme={null} Set up Crave using this guide: https://developer.craveup.com/agents.md Start in sandbox. Verify locally. ``` > [card] [Set up Crave with an agent](/docs/ai-onboarding) > > One prompt, current documentation, and a clear setup checklist for Claude > Code, Cursor, Codex, and other coding agents. Already have a supported API and SDK pair and prefer to work manually? Use the [CLI quickstart](/docs/getting-started/cli-quickstart) or your framework's guide below. For a new managed workspace, check [Cloud availability](/docs/guides/crave-cloud-overview) first; provisioning is currently assisted. ## Explore the platform > [card] [Crave Cloud Overview](/docs/guides/crave-cloud-overview) > > Understand how Crave.js fits into the broader franchise platform. > [card] [Deploy Safely](/docs/guides/deployment) > > Register exact browser origins and keep private credentials out of > storefront bundles. > [card] [Set up with an agent](/docs/ai-onboarding) > > Give your coding agent the current setup instructions and docs connection. > [card] [CLI Quickstart](/docs/getting-started/cli-quickstart) > > Learn the CLI flags, templates, and generated project structure. > [card] [Storefront SDK](/docs/getting-started/storefront-sdk) > > Connect your UI to menus, carts, checkout, and analytics with typed helpers. > [card] [REST API Essentials](/docs/getting-started/rest-api) > > Call Crave endpoints from any platform using standard HTTP requests. ## Where this fits > [card] [Developer Package and Crave Cloud](/docs/guides/open-source-and-cloud) > > Learn what is available to developers and what stays managed by Crave Cloud. > [card] [Build a Custom Storefront](/docs/guides/build-custom-storefront) > > Combine the CLI, Storefront SDK, REST APIs, and UI components for a branded > ordering experience. > [card] [Prebuilt Storefront Prompt](/docs/guides/ai/build-storefront-prompt) > > Give Cursor, Claude, ChatGPT, Codex, or another agent the right Crave > context before it edits your app. ## Quickstarts & Tutorials Explore our end-to-end tutorials and getting started guides for different application stacks. > [card] [Next.js](/docs/quickstarts/nextjs) > > Build a storefront with Next.js 16.3 App Router and the Crave SDK. > [card] [React](/docs/quickstarts/react) > > Get started with React + Vite and the Crave SDK. > [card] [Vanilla JavaScript](/docs/quickstarts/vanilla-js) > > Build a storefront with plain JavaScript and the REST API. > [card] [React Native](/docs/quickstarts/mobile) > > Create a mobile ordering app with Expo and the Crave SDK. ## UI Components Crave's prebuilt UI components give you a fully-functional ordering experience in minutes — menus, carts, checkout, and fulfillment out of the box. > [card] [Component Overview](/docs/components/overview) > > Browse all available components and learn how they work together. > [card] [Storefront SDK](/docs/getting-started/storefront-sdk) > > The TypeScript SDK that powers the components and data fetching. ## SDK & API Reference Dig into our SDK reference documentation and REST API endpoints. Everything you need to integrate Crave into any application. > [card] [SDK Reference](/docs/api-reference/overview/api-overview) > > API overview, authentication, endpoints, and response formats. > [card] [Core Concepts](/docs/api-reference/overview/core-concepts) > > Merchants, locations, menus, carts, and the ordering lifecycle. ## Explore by feature Crave supports the full ordering lifecycle. Pick a feature to dive deep. > [card] [Menu & Products](/docs/guides/display-menu) > > Display categories, products, and modifiers. Support multiple menus with > scheduled availability. > [card] [Cart & Ordering](/docs/guides/manage-cart) > > Manage the cart lifecycle — add items, apply modifiers, handle discounts, > and submit orders. > [card] [Payments](/docs/guides/accept-payments) > > Submit the order first, render Stripe-only online payment UI, and recover > the exact attempt. > [card] [Fulfillment](/docs/guides/fulfillment-methods) > > Configure takeout, delivery, table-side ordering, and room service for your > locations. > [card] [Analytics](/docs/guides/analytics) > > Track funnel events across the ordering flow and measure conversion rates. > [card] [Outbound Webhooks (Planned)](/docs/guides/webhooks) > > Review the current availability boundary before designing an event-driven > integration. ## Explore by framework > [card] [Next.js](/docs/quickstarts/nextjs) > > Server-side rendering with the App Router. Fetch menus on the server, manage > carts on the client. > [card] [React](/docs/quickstarts/react) > > Client-side React with Vite. Build a custom SPA storefront with the SDK. > [card] [Vanilla JavaScript](/docs/quickstarts/vanilla-js) > > No framework required. Call the REST API directly from plain JavaScript. > [card] [React Native / Expo](/docs/quickstarts/mobile) > > Build native mobile ordering apps with Expo and the Crave SDK. ## Beyond the basics > [card] [Theming](/docs/guides/theming) > > Customize colors, fonts, and component styles to match your restaurant's > brand. > [card] [Testing](/docs/guides/testing) > > Use test mode, mock data, and example test suites to validate your > integration. > [card] [Deployment](/docs/guides/deployment) > > Deploy to Vercel, Netlify, Docker, or custom hosting with production best > practices. > [card] [Error Handling](/docs/guides/error-codes) > > Handle every error the API can return with status codes, retry strategies, > and user messages. ## Community > [card] [Slack](https://join.slack.com/t/cravejscommunity/shared_invite/zt-3hfr081io-aYuLC3n6gBFKQuho0HrTng) > > Connect with the Crave community on Slack. > [card] [Support](mailto:hello@craveup.com) > > Reach out to our team directly for help with your integration. # REST API Essentials Source: https://craveup-1493c4c7.mintlify.dev/docs/getting-started/rest-api Call the public Crave Storefront API directly from web, mobile, or server applications. The public Storefront API is rooted at: ```text theme={null} https://api.craveup.com/api/v1/storefront ``` Published merchant, location, menu, and product reads are anonymous. A new ordering session returns a cart capability. Send that capability only in `X-Cart-Token` for the matching cart, use the current ETag in `If-Match` for mutations, and give every write an `Idempotency-Key`. Signed-in customer resources use `Authorization: Bearer `. ## Fetch a published menu ```bash theme={null} curl "https://api.craveup.com/api/v1/storefront/locations/loc_123/menus?orderDate=2026-08-08&orderTime=18:30" ``` ## Start an ordering session ```bash theme={null} curl -X POST "https://api.craveup.com/api/v1/storefront/locations/loc_123/ordering-sessions" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: session_01" \ -d '{"fulfillmentMethod":"takeout"}' ``` The optional `marketplaceId` is a source-attribution label such as `"web"` or `"mobile"`, not a location ID. The route already supplies the location scope. Store `cart.id`, `cartAccessToken`, and `cart.revision` together in tab-scoped browser storage or the mobile platform's secure storage. ## Add an item ```bash theme={null} curl -X POST "https://api.craveup.com/api/v1/storefront/locations/loc_123/carts/cart_456/items" \ -H "Content-Type: application/json" \ -H "X-Cart-Token: $CART_ACCESS_TOKEN" \ -H 'If-Match: "cart-0"' \ -H "Idempotency-Key: add_item_01" \ -d '{"productId":"prod_margherita","quantity":1,"selections":[],"itemUnavailableAction":"remove_item"}' ``` The response includes a new ETag. Use that value for the next mutation. If the API returns `CART_CONFLICT`, fetch the cart with the capability, update local state and revision, and require an explicit user retry. ## Authentication boundaries | Resource | Credential | | - | - | | Published catalog | None | | Cart and checkout | Matching cart capability | | Customer profile, orders, addresses, saved payments, loyalty | Customer JWT | | Public receipt | Receipt capability from the URL fragment or customer JWT | | Admin and partner APIs | Server-only credential; never a storefront client variable | Do not put capabilities, JWTs, receipt tokens, or payment secrets in query strings or logs. Configure the API CORS allowlist with exact production and preview storefront origins. Explore the [Storefront REST reference](/docs/api-reference/overview/api-overview) for endpoint schemas. # Storefront SDK Source: https://craveup-1493c4c7.mintlify.dev/docs/getting-started/storefront-sdk Use the typed direct client for public catalog, cart, customer, checkout, receipt, and loyalty flows. > [!WARNING] > > Managed Cloud projects use their included storefront and pinned runtime. The > published SDK version and this platform source candidate do not establish > compatibility with a Cloud installation. Verify the deployed API and caller > pair using the [Cloud release > results](/docs/guides/crave-cloud-overview#developer-package-compatibility). `@craveup/storefront-sdk@4.0.0` is published under the `development` dist-tag for the scoped public API at `/api/v1/storefront`, with an exact `@craveup/commerce-contracts@4.0.0` dependency. Catalog and cart operations carry explicit menu, channel and release context; configured food comes from the server. This guide describes that published pair, including its frontend Clerk customer integration. > [!WARNING] > > API-owned customer authentication is a separate SDK 5.0.0 / contracts 5.0.0 > source candidate that is not yet published or activated. Do not use its new > authentication methods with the published 4.0.0 pair. Published SDK 2.0.1 > lacks this API's scoped menu/cart context and its customer login/OTP/logout > and direct payment/result methods target retired routes. Keep those consumers > blocked until the matching deployed API, frozen installs and caller adoption > are verified. Development publication does not establish production > compatibility. Do not substitute an unpublished package or private transport. ## Install and configure ```bash theme={null} pnpm add --save-exact @craveup/storefront-sdk@4.0.0 ``` Create separate server and browser clients. A server client has no session or JWT provider; use it only for anonymous published calls: ```ts theme={null} import { createStorefrontClient } from "@craveup/storefront-sdk"; export const storefrontServer = createStorefrontClient({ baseUrl: process.env.NEXT_PUBLIC_CRAVEUP_API_URL!, }); ``` A browser client owns the caller-provided, tab-scoped cart store. Customer tokens come from the active Clerk session and are never persisted by the app: ```ts theme={null} import { createStorefrontClient } from "@craveup/storefront-sdk"; import { sessionStore } from "./storefront-session"; export function createStorefrontBrowser(input: { getAuthToken: () => Promise; merchantSlug: string; }) { return createStorefrontClient({ baseUrl: process.env.NEXT_PUBLIC_CRAVEUP_API_URL!, sessionStore, getAuthToken: input.getAuthToken, getMerchantSlug: () => input.merchantSlug, defaultTimeoutMs: 10_000, }); } ``` Create this client only after Clerk is loaded. Supply `getAuthToken` from the active Clerk session as `() => getToken({ template: "crave-customer" })` and resolve `merchantSlug` from the storefront's trusted host or public configuration. See [Customer identity](/docs/guides/customer-identity) for the framework adapter and activation requirements. | Option | Required | Purpose | | - | - | - | | `baseUrl` | Yes | Exact Crave API origin; remote origins must use HTTPS. | | `sessionStore` | For carts | Caller-owned storage for the cart ID, capability, location, and revision. | | `getAuthToken` | For customer flows | Supplies the merchant-bound customer JWT. | | `getMerchantSlug` | For customer flows | Supplies explicit organization routing for customer requests. | | `fetch` | No | Custom fetch implementation for non-browser runtimes. | | `defaultTimeoutMs` | No | Timeout for auth-token resolution and the network response. | The client ignores caller-supplied authorization credentials and obtains customer auth only from `getAuthToken`. Private API keys are not a Storefront SDK option. The exact typed method surface is the complete public JSON transport API; raw request helpers are not exported, and the navigation-only hosted-storefront redirect is deliberately unwrapped. Do not pass the browser client, its store, or its token provider into a Server Component, server action, or route handler. Every remote `baseUrl` must use HTTPS. Plain HTTP is accepted only for the exact loopback hosts `localhost`, `127.0.0.1`, and `[::1]`; a phone-accessible LAN host such as `192.168.x.x` is not loopback. Redirect responses are rejected rather than followed. Async `getAuthToken` resolution uses the same timeout as the network response. `defaultTimeoutMs` and a per-call `timeoutMs` start before the token lookup, so a provider that does not settle produces a `StorefrontTimeoutError` without sending a request. Scope stored data as follows: | Record | Required scope | Browser persistence | Mobile persistence | | - | - | - | - | | Guest cart session | API environment + merchant + location | Versioned `sessionStorage` | `expo-secure-store` | | Customer identity | Clerk environment + active session | Clerk-managed | Clerk-managed | | Receipt capability | API environment + merchant + receipt ID | Versioned `sessionStorage` | Only when resuming | Reject malformed or unknown stored versions instead of casting unvalidated JSON. The [Next.js](/docs/quickstarts/nextjs), [React](/docs/quickstarts/react), and [Expo](/docs/quickstarts/mobile) quickstarts provide complete adapters. Within one client instance, the SDK serializes session-store mutations per location, including async SecureStore adapters. It persists revisions monotonically, coalesces identical concurrent ordering-session starts, and serializes different starts for the same location. Separate client instances or processes need coordination from the application or storage adapter. ## Authorization model * Published merchant, location, menu, product, distance, order-time, and gratuity calls are anonymous and never receive the customer JWT. * `orderingSessions.start` returns a purpose-limited cart capability and saves it through `sessionStore`. * Cart calls attach the capability, current revision, and an idempotency key where required. * Customer profile, order, address, saved-payment, and loyalty history calls use the customer JWT. * Receipt access uses `receiptToken` and sends it only as `X-Receipt-Token`. Use tab-scoped storage for browser capabilities. Clear the guest capability after claim, deletion, expiry, or terminal checkout handling; after claim, keep only the authoritative cart revision if customer-authenticated access continues. Let Clerk clear its session on logout, and clear a receipt capability after terminal display or expiry. Never copy customer JWTs into application storage or put capabilities or customer JWTs in URLs, public environment variables, logs, source maps, HTML, or analytics. ## Catalog and ordering ```ts theme={null} const merchant = await storefrontServer.merchant.getBySlug("demo-cafe"); const location = await storefrontServer.locations.getById("loc_123"); const menus = await storefrontServer.menus.list(location.id, { menuOnly: true, }); const readiness = await storefrontServer.locations.getOrderingReadiness( location.id, "takeout", ); if (!readiness.ready) throw new Error(readiness.reason); const { cart } = await storefrontBrowser.orderingSessions.start(location.id, { fulfillmentMethod: "takeout", }); const updated = await storefrontBrowser.cart.addItem(location.id, cart.id, { productId: "prod_123", quantity: 1, selections: [], itemUnavailableAction: "remove_item", }); ``` `locations.getOrderingReadiness()` is an anonymous, side-effect-free GET. Use it to check a fulfillment method without creating a cart; omit the second argument to use the `takeout` default. ## Checkout and terminal result ```ts theme={null} const outcome = await storefrontBrowser.checkout.submitOrder( locationId, cartId, { acceptedCatalogEvidence, acceptedDiscountEvidence, collectionMode: "ONLINE", customerConfirmationRevision, quoteFingerprint, }, { idempotencyKey, includeCustomerContext: true, revision: cart.revision }, ); const result = await storefrontBrowser.checkout.getOrderSubmissionOutcome( locationId, cartId, outcome.attemptId, ); switch (result.status) { case "PROCESSING": case "CUSTOMER_ACTION_REQUIRED": break; // poll with bounded backoff case "PAID": console.log(result.orderId); break; case "ACCEPTED": case "ACTION_REQUIRED": console.log(result.status); break; } ``` The Stripe client secret returned with `CUSTOMER_ACTION_REQUIRED` is browser-usable but still sensitive: keep it in memory and do not log it or place it in a URL. Use `includeCustomerContext: true` only when a signed-in shopper still has a guest capability and order submission needs Stripe customer association. Omit it for guest checkout. A claimed cart already uses the customer JWT because its guest capability has been cleared. ## Customer authentication ```tsx theme={null} const { getToken, isLoaded, isSignedIn } = useAuth(); const storefrontBrowser = useMemo(() => { if (!isLoaded || !isSignedIn) return null; return createStorefrontBrowser({ getAuthToken: () => getToken({ template: "crave-customer" }), merchantSlug, }); }, [getToken, isLoaded, isSignedIn, merchantSlug]); ``` Crave does not expose customer login, OTP, or token-storage endpoints. Use the environment-specific Customer Clerk application and make customer requests only after Clerk and the SDK token provider are ready. The SDK obtains the current short-lived token for each customer request and sends `X-Crave-Merchant-Slug` from `getMerchantSlug`. Then use `customer.getProfile`, `customer.orders`, `customer.addresses`, `customer.savedPayments`, `loyalty.ledger`, and `loyalty.claims`. ## Receipts ```ts theme={null} const receipt = await storefrontBrowser.receipts.get(receiptId, { receiptToken, }); ``` Receipt links place the capability in the URL fragment. Capture it, immediately remove the fragment with `history.replaceState`, and keep it only in tab-scoped storage for that receipt. ## Errors and concurrency ```ts theme={null} import { StorefrontApiError, StorefrontClientStateError, StorefrontProtocolError, StorefrontTimeoutError, } from "@craveup/storefront-sdk"; try { await storefrontBrowser.cart.updateGratuity(locationId, cartId, { percentage: "18", }); } catch (error) { if (error instanceof StorefrontApiError) { console.error(error.status, error.code, error.requestId); if (error.retryAfterMs !== undefined) scheduleRetry(error.retryAfterMs); } else if (error instanceof StorefrontClientStateError) { console.error(error.code); } else if (error instanceof StorefrontProtocolError) { console.error(error.reason, error.method, error.routeTemplate); } else if (error instanceof StorefrontTimeoutError) { console.error(error.method, error.routeTemplate); } } ``` `StorefrontClientStateError` is a typed local preflight failure. For example, `CUSTOMER_AUTH_REQUIRED` means a customer-authenticated method was called without an available JWT, so no network request was sent. `StorefrontProtocolError.reason` is `EMPTY_RESPONSE` or `INVALID_JSON` for a successful response that violates the JSON contract. `retryAfterMs` is a bounded millisecond delay parsed from `Retry-After`; it is `undefined` when the API did not provide a usable value. On `CART_CONFLICT`, fetch the cart again before presenting a retry. Reuse an explicit idempotency key when your application deliberately retries the same logical mutation. ## Navigation-only redirect `GET /locations/{locationId}/redirect` is a navigation-only REST operation and is intentionally not part of the typed SDK method surface. Navigate a browser or native in-app browser to it directly when entering Crave's hosted storefront; do not fetch it as JSON with the Storefront client. SDK requests reject redirect responses and never follow them. ## Browser-origin onboarding Register every exact browser origin with Crave before testing from a browser. The origin includes its scheme, hostname, and any non-default port; local, preview, and production origins are separate registrations. Wildcards are not accepted. Native mobile requests normally omit the browser `Origin` header, but an Expo web deployment still needs registration. ### Customer catering quotes Catering links use an event-specific capability. Pass it only through the declared `cateringToken` option; never put it in a query parameter or arbitrary headers. All catering operations return private, non-cacheable responses. ```ts theme={null} const view = await sdk.catering.get(locationId, eventId, { cateringToken }); const result = await sdk.catering.accept( locationId, eventId, { quoteId: view.offer.quoteId, eventRevision: view.offer.eventRevision, offerFingerprint: view.offer.offerFingerprint, }, { cateringToken, idempotencyKey }, ); // Alternatively, decline the current quote using the event revision: await sdk.catering.decline( locationId, eventId, { quoteId: view.quote.id, eventRevision: view.event.revision, message: "No thanks", }, { cateringToken, idempotencyKey: declineKey }, ); ``` Check `view.actions` before showing acceptance or decline. Only accept a non-null offer after the customer reviews its exact total. On `CATERING_OFFER_STALE`, refetch and require a new click; do not automatically accept a different amount. Reuse the same idempotency key only for the same request. The customer response excludes restaurant-only notes and contact data, shows current `refundedTotal` values, and provides receipt links only for paid payments belonging to this event. A refund does not reopen deposit acceptance. The OpenAPI operations are `getCateringEvent`, `acceptCateringQuote`, and `declineCateringQuote`, under `/locations/{locationId}/catering/events/{eventId}` (with `/accept` or `/decline` for POST). Missing `X-Catering-Token` returns 401; invalid, expired, revoked or wrong-location links return the same 404 response. ### Customer catering balance An accepted event returns `balance` with the agreed total, settled captures, outstanding amount, due date, and a nullable payment offer. After the customer reviews a non-null offer, pay the whole balance with: ```ts theme={null} const offer = view.balance?.offer; if (offer) { const result = await sdk.catering.payBalance( locationId, eventId, { quoteId: offer.quoteId, offerFingerprint: offer.offerFingerprint }, { cateringToken, idempotencyKey: balanceKey }, ); if (result.outcome === "checkout") navigate(result.checkoutUrl); } ``` `payCateringBalance` uses `/balance-payment`; send no amount. A successful response is `checkout` with `dueNow` and `remaining`, or `no_balance`. Refetch after checkout to confirm settlement. On a stale offer, refetch and require a new click. Pending payments, refunds, reconciliation and closed events hold online collection. Refunds never increase what is owed; `REFUND_IN_REVIEW` requires staff review. New customer links last until the later of the event's 30-day expiry and 30 local calendar days after the balance-due day. Existing links are never renewed. ### Catering inquiries from your website A restaurant that turned on website inquiries accepts catering requests from its own site. Both calls are anonymous. Show the form only when `inquiryForm` reports `enabled: true`. ```ts theme={null} const form = await sdk.catering.inquiryForm(locationId); if (form.enabled) { const { reference, answerBy } = await sdk.catering.submitInquiry( locationId, submission, { idempotencyKey }, ); } ``` Create one `idempotencyKey` per inquiry and reuse it when retrying that inquiry. A retry then returns the same receipt instead of sending a second request. The receipt holds only the six-digit `reference` and the `answerBy` time. A location that is not accepting inquiries returns 409 `CATERING_INQUIRIES_NOT_ACCEPTED`. Submissions are limited to five a minute per sender. The OpenAPI operations are `getCateringInquiryForm` and `submitCateringInquiry`. ### Published catering menu A restaurant's published catering menu is readable without login, a cart or a catering link. Only the location ID goes in the request. ```ts theme={null} const menu = await sdk.catering.getPublishedMenu(locationId); for (const category of menu.categories) { for (const item of category.items) render(item, menu.policies); } ``` Items, modifier groups and options carry their canonical IDs, the printed price (`exact` cents, a `range`, or `quote_only`), the price basis and servings as the restaurant reviewed them. A missing fact is `null`, never zero. `catalogRevision` names the publication the menu was read from. The response is never cached, so a menu stops being readable as soon as it is unpublished or catering is switched off; both answer 404 `CATERING_MENU_UNAVAILABLE`, and an unknown or archived location answers 404 `NOT_FOUND`. The OpenAPI operation is `storefrontGetPublishedCateringMenu`. ### Requesting catering cancellation `client.catering.requestCancellation(locationId, eventId, { quoteId, eventRevision, reason }, { cateringToken, idempotencyKey })` records a request for restaurant review. It never cancels the service, charges a cancellation fee, or issues a refund. Use the current accepted quote and event revision from the customer response. Read the recorded request with `client.catering.cancellationRequest(locationId, eventId, { cateringToken })`. A revoked, expired or erased link cannot read or replay a request. Keep the same key and payload when retrying; a different key cannot replace an open request. Staff decisions and refunds are separate operations. Their controls remain unavailable until the corresponding backend and dashboard slices are deployed. # Accept Payments Source: https://craveup-1493c4c7.mintlify.dev/docs/guides/accept-payments Offer Stripe online payment and certified POS-native pay at store from one order-first flow. > [!WARNING] > > Managed Cloud projects use their included storefront and pinned runtime. The > published SDK version and this platform source candidate do not establish > compatibility with a Cloud installation. Verify the deployed API and caller > pair using the [Cloud release > results](/docs/guides/crave-cloud-overview#developer-package-compatibility). Stripe is the only online payment processor. Square, Clover, and Toast receive fulfillment orders and provide certified in-person tender evidence; they never expose browser checkout. ## Read the server-owned choices Do not infer payment choices from a connected provider or a location setting. Load the current cart's `collection-options` first: ```ts theme={null} const choices = await storefront.checkout.getCollectionOptions( locationId, cartId, { revision: cart.revision }, ); const online = choices.options.find( ({ collectionMode }) => collectionMode === "ONLINE", ); const payAtStore = choices.options.find( ({ collectionMode }) => collectionMode === "PAY_AT_STORE", ); ``` The response is a read-only preflight. Submission rechecks the current quote, catalog, policy, customer eligibility, unpaid-order exposure, provider binding, and native-payment certification. If an option is unavailable, show its `unavailableReasonCode`; never override it in the browser. ## Pay online with Stripe ```ts theme={null} const outcome = await storefront.checkout.submitOrder( locationId, cartId, { acceptedCatalogEvidence, acceptedDiscountEvidence, collectionMode: "ONLINE", customerConfirmationRevision, quoteFingerprint, }, { idempotencyKey, revision: cart.revision }, ); ``` The SDK sends the cart capability, current revision, and idempotency key. A raw REST request must send the same headers: ```bash theme={null} curl -X POST "https://api.craveup.com/api/v1/storefront/locations/loc_123/carts/cart_456/submissions" \ -H "X-Cart-Token: $CART_ACCESS_TOKEN" \ -H 'If-Match: "cart-4"' \ -H "Idempotency-Key: payment_01" ``` When the outcome is `CUSTOMER_ACTION_REQUIRED`, initialize Stripe.js with its `connectedAccountId` and confirm its `clientSecret`. The server captures and settles the already-persisted order. No provider-selected confirmation endpoint exists. ## Confirm a Stripe session with Stripe Elements ```tsx theme={null} import { Elements, PaymentElement, useElements, useStripe, } from "@stripe/react-stripe-js"; import type { OrderSubmissionOutcome } from "@craveup/storefront-sdk"; import { loadStripe } from "@stripe/stripe-js"; if (outcome.status !== "CUSTOMER_ACTION_REQUIRED") return; const stripePromise = loadStripe( process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY!, { stripeAccount: outcome.connectedAccountId, }, ); ; export function PaymentForm({ outcome }: { outcome: OrderSubmissionOutcome }) { const stripe = useStripe(); const elements = useElements(); async function submit(event: React.FormEvent) { event.preventDefault(); if (!stripe || !elements) return; const { error, paymentIntent } = await stripe.confirmPayment({ elements, confirmParams: { return_url: `${window.location.origin}/checkout/stripe-return`, }, redirect: "if_required", }); if (error) throw new Error(error.message); if ( !paymentIntent || !["requires_capture", "succeeded"].includes(paymentIntent.status) ) { throw new Error("Stripe payment is not ready for capture"); } await storefront.checkout.getOrderSubmissionOutcome( locationId, cartId, outcome.attemptId, ); } return (
); } ``` Cache Stripe.js by the immutable connected-account id and rebuild Elements whenever the payment outcome changes. Stripe secret keys remain on Crave-managed services. Never collect or log raw card numbers. If Stripe redirects for authentication, the return page must recover the same cart session from tab-scoped storage and make the same idempotent server-capture request before showing success. After Stripe returns, poll `storefront.checkout.getOrderSubmissionOutcome(locationId, cartId, attemptId)`. Treat only `PAID` as paid, keep `PROCESSING` retryable, and surface `ACTION_REQUIRED` without creating another order. ## Pay at the store Offer this choice only when the server returns an available `PAY_AT_STORE` option and identifies `SQUARE`, `CLOVER`, or `TOAST` as its settlement adapter. Submit the same order-first contract without a saved payment method: ```ts theme={null} if (!payAtStore?.available || !payAtStore.settlementAdapter) return; const outcome = await storefront.checkout.submitOrder( locationId, cartId, { acceptedCatalogEvidence, acceptedDiscountEvidence, collectionMode: "PAY_AT_STORE", customerConfirmationRevision, quoteFingerprint, }, { idempotencyKey, revision: cart.revision }, ); ``` An accepted pay-at-store order returns `status: "ACCEPTED"` and remains unpaid until the selected POS reports native tender evidence. Tell the customer that payment is due at the store and keep order state separate from payment state. Poll the same `attemptId`; never submit a replacement order and never render a POS card form, saved card, gift-card entry, or provider-hosted checkout. When counter-verification is unresolved, show **Verifying payment — do not charge again**. In `outcome.verification.state`, `PENDING` and `WARNING` continue reconciliation, while `ACTION_REQUIRED` needs staff review. Only the top-level `PAID` outcome proves collection. The POS provider owns the original in-person tender and its refund path. A provider order cancellation is not refund evidence. > [card] [Checkout Flow](/docs/guides/checkout-flow) > > See the complete checkout state machine. > [card] [Order Tracking](/docs/guides/order-tracking) > > Poll the order result and load protected receipts. # Prebuilt Storefront Prompt Source: https://craveup-1493c4c7.mintlify.dev/docs/guides/ai/build-storefront-prompt Give an AI coding agent the direct public Storefront API security and delivery contract. First complete [agent setup](/docs/ai-onboarding) and confirm the supported SDK/API pair for your restaurant. Then give your coding agent the implementation brief below. ```text theme={null} Read https://developer.craveup.com/agents.md first. Confirm that this target API supports the published 2.0.1 SDK contract below; if compatibility is not established, stop and report the missing supported release pair instead of adapting or guessing a transport. Build a release-quality Crave restaurant storefront while keeping checkout visibly unavailable until Crave's Stripe direct-charge activation lock is removed. Use the exact @craveup/storefront-sdk@2.0.1 package with: const crave = createStorefrontClient({ baseUrl: process.env.NEXT_PUBLIC_CRAVEUP_API_URL!, sessionStore, getAuthToken, getMerchantSlug: () => merchantSlug, }); Requirements: - Published catalog reads are anonymous; never add a browser API key. - Use versioned sessionStorage scoped by canonical API environment, merchant, and location for cart capability and revision state. - Keep cart capabilities, customer JWTs, receipt tokens, and PaymentIntent client secrets out of URLs, logs, analytics, and persistent storage. - Start ordering sessions with idempotency, then use SDK cart methods so capability, ETag, If-Match, and idempotency headers remain consistent. - On CART_CONFLICT, reload current cart state before presenting a retry. - Use the environment-specific Customer Clerk application for sign-in, recovery, logout, and token refresh. Crave exposes no customer login or OTP endpoints. - For signed-in customer calls, obtain a short-lived crave-customer JWT from the active Clerk session through getAuthToken, provide getMerchantSlug separately, and never persist the JWT yourself. - Prepare the documented Stripe.js confirmation and all four order-result states for the future activated contract, but do not claim or simulate successful payment admission today. - If checkout returns STRIPE_DIRECT_CHARGE_CUTOVER_INCOMPLETE, show a temporarily unavailable state; do not retry, bypass, or fall back to a different processor. - Capture receipt capabilities from URL fragments, remove the fragment immediately, and keep each capability only in tab-scoped storage scoped by API environment, merchant, and receipt ID. - Keep Stripe secret keys, POS credentials, loyalty credentials, webhook secrets, and private Crave integration keys on the API service. - Use exact CORS origins for each deployed storefront. Before completion, run tests, lint, type checking, a production build, a browser-bundle credential scan, and sandbox menu/cart checks that assert the checkout lock. Report exact commands and remaining deployment requirements; do not report an end-to-end paid order until activation evidence exists. ``` Useful references: * [Storefront SDK](/docs/getting-started/storefront-sdk) * [API overview](/docs/api-reference/overview/api-overview) * [Build a Custom Storefront](/docs/guides/build-custom-storefront) * [Deployment](/docs/guides/deployment) # Use the CraveUp MCP Server Source: https://craveup-1493c4c7.mintlify.dev/docs/guides/ai/craveup-mcp-server Connect AI agents to CraveUp tools for storefront setup, menu import, readiness checks, and go-live onboarding. > [!TIP] > > New to Crave? Start with [Set up Crave with an agent](/docs/ai-onboarding). The > [documentation MCP](https://developer.craveup.com/docs/mcp) gives your agent > current docs without account credentials. The platform MCP described below is > a separate connection for restaurant operations. > [!WARNING] > > npm currently publishes `@craveup/mcp` **0.6.0** (checked November 4, 2026), > while this reference also covers newer repository source. Do not use 0.6.0's > `connect_project`: it writes a private API key into public Expo configuration. > Its bundled onboarding guide and payment probes also predate the current > contract. Follow the [current agent setup > guide](https://developer.craveup.com/agents.md) for development setup. A > source fix is not a published release. > [!WARNING] > > The CraveUp MCP server is an agent-facing developer tool. It can create or > update restaurant setup data when authenticated, so connect it only in > workspaces where the agent is allowed to make those changes. CraveUp provides a Model Context Protocol server through the `@craveup/mcp` package. It lets AI agents use Crave-specific tools instead of guessing API shapes from memory. Use it when you want an agent to: * inspect or import menus * connect a storefront project to a Crave location * check storefront readiness before launch * configure location ordering settings * work through go-live onboarding steps * fetch Crave implementation guidance while building a storefront ## Setup The MCP server runs over stdio. Use the public npm package for normal usage outside this monorepo, or point your client at the local repo build when testing unreleased tools. You do not need a clone of `craveup-turborepo` to use the MCP server — `npx -y @craveup/mcp` fetches everything it needs. Most configurations below set `CRAVEUP_API_KEY` because menu imports and private readiness checks need a trusted server credential. Menu activation and product edits use your CraveUp login session instead, through the same catalog workspace as Business Manager. Public storefront guides, project wiring, and published menu reads do not use that key. If you do not have an organization yet, register the server with no credentials and sign in from chat instead — see [Sign in from chat](#sign-in-from-chat). ### Cursor Add this to your Cursor MCP configuration: ```json theme={null} { "mcpServers": { "craveup": { "command": "npx", "args": ["-y", "@craveup/mcp"], "env": { "CRAVEUP_ENVIRONMENT": "sandbox", "CRAVEUP_API_KEY": "crv_test_...", "CRAVEUP_LOCATION_ID": "loc_..." } } } } ``` Restart Cursor or reload the window after changing the MCP configuration. > [!NOTE] > > Inside `craveup-turborepo`, pnpm workspace resolution can shadow the published > package. If you are working in this repo, use the local repo build > configuration below. ### Codex Add separate sandbox and production servers from the terminal: ```bash theme={null} codex mcp add craveup-sandbox \ --env CRAVEUP_ENVIRONMENT=sandbox \ --env CRAVEUP_API_KEY=crv_test_... \ --env CRAVEUP_LOCATION_ID=loc_... \ -- npx -y @craveup/mcp codex mcp add craveup-production \ --env CRAVEUP_ENVIRONMENT=production \ -- npx -y @craveup/mcp ``` If your Codex configuration uses TOML, add: ```toml theme={null} [mcp_servers.craveup] command = "npx" args = ["-y", "@craveup/mcp"] [mcp_servers.craveup.env] CRAVEUP_ENVIRONMENT = "sandbox" CRAVEUP_API_KEY = "crv_test_..." CRAVEUP_LOCATION_ID = "loc_..." ``` ### Claude Code CraveUp is a local stdio MCP server, not a hosted HTTP endpoint. Register separate sandbox and production processes at user scope: ```bash theme={null} claude mcp add -s user craveup-sandbox \ -e CRAVEUP_ENVIRONMENT=sandbox \ -- npx -y @craveup/mcp claude mcp add -s user craveup-production \ -e CRAVEUP_ENVIRONMENT=production \ -- npx -y @craveup/mcp ``` Run `/mcp` in Claude Code to inspect or reconnect the server. Start a new Claude Code session if the current session does not refresh its tool inventory after registration. Use `-s project` only when you intentionally want to commit a team-wide `.mcp.json`. Never place API keys or access tokens in that file. ### Claude Desktop Add this to `~/Library/Application Support/Claude/claude_desktop_config.json`: ```json theme={null} { "mcpServers": { "craveup": { "command": "npx", "args": ["-y", "@craveup/mcp"], "env": { "CRAVEUP_ENVIRONMENT": "sandbox", "CRAVEUP_API_KEY": "crv_test_...", "CRAVEUP_LOCATION_ID": "loc_..." } } } } ``` Restart Claude Desktop after saving the file. ### Local repo build Use this when you are working inside `craveup-turborepo` and need the newest MCP tools from source: ```bash theme={null} pnpm --filter @craveup/mcp build ``` Then configure your MCP client to run the built CLI: ```json theme={null} { "mcpServers": { "craveup": { "command": "node", "args": ["/absolute/path/to/craveup-turborepo/packages/mcp/dist/cli.js"], "env": { "CRAVEUP_ENVIRONMENT": "sandbox", "CRAVEUP_API_KEY": "crv_test_...", "CRAVEUP_LOCATION_ID": "loc_..." } } } } ``` ## Environment and authentication `CRAVEUP_ENVIRONMENT` is required and must be `sandbox` or `production`. The MCP server resolves the dashboard, public/admin APIs, Clerk issuer/client, expected API-key prefix, and credential namespace from that one value. It refuses a test/live key or endpoint mismatch before making a request. The environment is immutable for the lifetime of an MCP process. Use two named registrations rather than an in-session switch: `craveup-sandbox` for development and `craveup-production` for go-live work. This keeps hosts, credentials, API keys, and browser sessions isolated. | Environment | Dashboard | API key prefix | | - | - | - | | `sandbox` | `sandbox.dashboard.craveup.com` | `crv_test_...` | | `production` | `dashboard.craveup.com` | `crv_live_...` | Sandbox remains isolated from Production data and supports test checkout where its merchant-owned Stripe connection is ready. Production can also use test payments while checkout is being verified: the environment label does not select live processing. Read the installation's payment mode and readiness. If an API returns an activation or readiness error, keep checkout unavailable and resolve the reported condition; do not bypass it. Hosting subscriptions and live merchant payment activation are separate. See [Stripe Payments](/docs/guides/integrations/stripe). The MCP server supports three authentication modes. | Mode | Use it for | Required setup | | - | - | - | | **Crave API key** | Menu import, integration status, and the private part of readiness checks | Set `CRAVEUP_API_KEY`, and usually `CRAVEUP_LOCATION_ID` | | **Public Storefront API** | Published menu reads, direct-integration guides, and project environment wiring | No credential; provide a published `locationId` when the tool needs one | | **CraveUp login session** | Organization setup, project wiring, go-live onboarding, menu activation, and product edits | Ask the agent to sign you in (see below), run `craveup login`, or set `CRAVEUP_ACCESS_TOKEN` | | **Expo robot token** | Dispatch and monitor approved internal mobile release workflows | Set `EXPO_TOKEN` in the MCP server environment; never put it in prompt text | To create an API key, open Business Manager and go to [Dashboard > Developers > API Development > Step 1 - API Keys](/docs/guides/generate-api-key). API keys are tied to an organization and may be restricted to specific locations; each MCP call still needs a target `locationId`. ### Sign in from chat Requires `@craveup/mcp` 0.5.0 or later. An API key is scoped to an organization that already exists, so it cannot unlock organization setup or the go-live tools. For those, the agent can start a browser sign-in for you — no `craveup login` in a terminal, and no API key in the configuration. `CRAVEUP_ENVIRONMENT` is still required, since it selects which dashboard and Clerk issuer the sign-in targets: ```json theme={null} { "mcpServers": { "craveup": { "command": "npx", "args": ["-y", "@craveup/mcp"], "env": { "CRAVEUP_ENVIRONMENT": "sandbox" } } } } ``` Then ask the agent to sign you in. It runs: 1. `start_crave_auth` — returns a hosted Crave Up URL. Open it and sign in, or create a free account. 2. `complete_crave_auth` — finishes the exchange and stores the session. The session is written to the macOS keychain, falling back to `~/.config/craveup/credentials.json`, and is shared with the `craveup` CLI — so signing in through either one satisfies the other. Run `whoami` at any time to confirm which account is active. > [!NOTE] > > On versions before 0.5.0 these tools are absent. Upgrade, or run `craveup > login` from a terminal to produce the same shared session. > [!NOTE] > > Normal MCP requests reuse the persisted CLI/MCP session; they do not open a > browser. Browser authentication happens only when `start_crave_auth` (or > `craveup login`) is explicitly started. Sandbox and production sessions are > stored separately. > [!NOTE] > > Do not put production API keys in shared prompt text, screenshots, recordings, > or public repository files. Pass credentials through the MCP client > environment instead. ## Available tools Exact tool availability depends on the installed package version. The current repository source exposes these tool groups; installed npm versions may differ: | Tool group | Examples | Purpose | | - | - | - | | **Onboarding** | `get_onboarding_flow`, `whoami`, `create_organization`, `connect_project` | Move a restaurant project from first setup to a connected Crave storefront | | **Browser auth** | `start_crave_auth`, `complete_crave_auth`, `cancel_crave_auth` | Sign in or sign up from chat without leaving the conversation (0.5.0 and later) | | **Menu and storefront** | `import_menu`, `set_menu_active`, `review_menu_publication`, `publish_menus`, `list_menus`, `get_product`, `update_product`, `set_product_availability`, `check_storefront_readiness` | Import, publish, inspect, edit, and verify storefront data | | **Location settings** | `get_location_settings`, `update_store_hours`, `set_takeout_enabled`, `set_scheduled_orders_enabled`, `open_location_for_orders` | Fix ordering gates such as closed-store or unavailable pickup states | | **Discounts** | `list_discounts`, `create_order_discount` | Read location promo codes and create order-level discounts idempotently | | **Go-live** | `get_onboarding_status`, `set_location_address`, `set_fulfillment_methods`, `list_subscription_plans`, `start_subscription_checkout` | Continue setup at any time; subscription and Connect are required only for production payments | | **Guidance** | `get_integration_guide` | Ask for Crave-specific implementation guidance while coding | | **Runtime status** | `get_mcp_capabilities` | Inspect versions, policy digest, and fail-closed compatibility blockers without credentials | | **Mobile releases** | `check_mobile_release_readiness`, `start_mobile_release`, `get_mobile_release_status` | Preflight internal releases and dispatch TestFlight with explicit approval | Multi-location and sandbox tools — `create_location`, `delete_location`, `list_locations`, `get_location_orders`, `list_customers`, `set_menu_active`, and `seed_sandbox_analytics` — are available from 0.4.0. From 0.7.0, `set_menu_active`, `get_product`, `update_product`, and `set_product_availability` call the Business Manager catalog workspace with your login session, and writes need an organization admin. Each write saves its change in the organization's catalog draft. In the 0.8.0 source candidate, writes stay in the draft. Review explicit menu/location/channel targets with `review_menu_publication`, then commit the exact revision and targets with `publish_menus`, `reviewedPublicationToken` and a stable `idempotencyKey`. Unselected releases stay unchanged. MCP's governance `confirmationToken` is separate from the API review token. `list_menus` requires an explicit channel. Package publication is a separate release gate. `get_product`, `update_product`, and `set_product_availability` refuse locations whose menu comes from a POS, which sets their prices and availability. `delete_product` was removed in 0.7.0; delete products in Business Manager. Browser auth is available from 0.5.0. The repo source can carry tools ahead of the published package; use the local repo build if you need one before its release. All current tools return one versioned operation envelope in both text and `structuredContent`. Review-required writes preview without side effects and require the exact returned intent digest for apply. Destructive, paid, and release operations require a separate confirmation phrase. Use `get_mcp_capabilities` to inspect the policy digest and current blockers. A ready intent digest does not claim that target pre-state, project registry evidence, bounded background jobs, or opaque cursor pagination exist; those capabilities remain fail-closed until their server/release contracts are published. Policies whose inventory says `idempotencyStrategy: unverified` remain blocked after preview. Today that includes `create_organization`, `create_location`, `start_subscription_checkout`, and `start_mobile_release`. Complete those actions in Business Manager or the provider workflow until the authoritative service provides a durable operation identity and response-loss reconciliation. `check_storefront_readiness` reads the published menu and the side-effect-free `GET /ordering-readiness` endpoint without creating a cart, then reads private integration status for payment configuration. The private step requires `CRAVEUP_API_KEY`. A ready payment check describes configuration only; the tool does not create a PaymentIntent, prove payment admission, or execute a test payment. While the direct-charge lock exists, checkout still returns `STRIPE_DIRECT_CHARGE_CUTOVER_INCOMPLETE`. For mobile releases, first run `craveup apps configure` in the Expo/React Native project and commit the generated `.eas/workflows` files. The MCP release trigger only supports internal TestFlight. It requires the exact confirmation phrase and a scoped Expo robot token because dispatching a workflow consumes EAS build minutes. Android internal publishing stays in the CLI so the local Play submit profile can be verified immediately before submission. Apple password/2FA prompts remain in a visible terminal, and public App Store review remains a separate App Store Connect action. ## Example prompts Once connected, ask your agent for Crave-specific work: ```text theme={null} Use the CraveUp MCP server to sign me in to Crave Up, then tell me which account and organization I am on. ``` ```text theme={null} Use the CraveUp MCP server to inspect my current location, list active menus, and tell me whether this storefront can accept orders. ``` ```text theme={null} Use the CraveUp MCP server and the Crave docs to build a Next.js menu page with category tabs, cart state, and the server-selected checkout payment-session flow. If payment admission returns STRIPE_DIRECT_CHARGE_CUTOVER_INCOMPLETE, show checkout as temporarily unavailable without retrying. ``` ```text theme={null} Import this menu into Crave. Preserve categories, products, prices, modifier groups, availability, and image URLs. After import, verify the active menu with list_menus. ``` ## Faster setup with a prebuilt prompt Use the prebuilt prompt when you want an AI agent to start with Crave Cloud, Crave.js, Storefront API, and MCP context already loaded. > [card] [Use the storefront prompt](/docs/guides/ai/build-storefront-prompt) > > Copy a ready-to-use agent prompt for building a Crave-powered storefront. > [card] [Configure private MCP access](/docs/guides/generate-api-key) > > Create a server-only key only when private MCP tools need it. A storefront > never receives that key. ## Troubleshooting | Problem | Fix | | - | - | | The agent cannot see CraveUp tools | Restart the MCP client after changing configuration. In Cursor, reload the window. | | `CRAVEUP_ENVIRONMENT is required` | Set it to `sandbox` or `production` in the MCP server environment. | | `No Crave session` appears | Call `start_crave_auth` then `complete_crave_auth`, run `craveup login`, or set `CRAVEUP_ACCESS_TOKEN`. | | Storefront tools fail with an auth error | Confirm the key prefix matches the selected environment and can access the target location. | | Stripe checkout reports `STRIPE_DIRECT_CHARGE_CUTOVER_INCOMPLETE` | The direct-charge activation lock is working as designed. Keep setup/catalog/cart work available, show checkout as temporarily unavailable, and do not retry or bypass it. | | Sandbox asks for Stripe Connect setup | Do not bypass the returned setup state. During the cutover, continue non-payment work; after activation, follow the current onboarding status for that location. | | Menu tools use the wrong location | Set `CRAVEUP_LOCATION_ID`, or pass `locationId` explicitly in the tool call. | | New tools do not appear after a repo update | Rebuild `@craveup/mcp`, then restart the MCP client. | # Analytics Source: https://craveup-1493c4c7.mintlify.dev/docs/guides/analytics Track storefront events and measure ordering funnel performance. The Crave SDK includes a built-in analytics module that tracks key events across the ordering funnel. Use it to measure conversion rates, identify drop-off points, and understand customer behavior. ## Event types The public SDK accepts three cart-authorized interaction events. Crave records `ORDER_PLACED` server-side only after payment succeeds and the order is created, so clients cannot forge a conversion. | Event | When to fire | Funnel stage | | - | - | - | | `SCAN` | Customer scans a QR code or visits the storefront URL | Entry | | `CART_VIEW` | Customer opens the cart panel | Consideration | | `CHECKOUT_VIEW` | Customer reaches the checkout page | Intent | | `ORDER_PLACED` | Recorded automatically by Crave after order creation | Conversion | ## Track events with the SDK ```ts SDK theme={null} import { storefront } from '@/lib/storefront'; // Track a storefront visit await storefront.analyticsEvents.track(locationId, { cartId, eventType: 'SCAN', }); // Track cart view with metadata await storefront.analyticsEvents.track(locationId, { cartId, eventType: 'CART_VIEW', metadata: { itemCount: cart.totalQuantity, total: cart.orderTotalWithServiceFee, }, }); // Track checkout view await storefront.analyticsEvents.track(locationId, { cartId, eventType: 'CHECKOUT_VIEW', metadata: { fulfillmentMethod: cart.fulfilmentMethod, }, }); ``` ```bash REST theme={null} curl -X POST "https://api.craveup.com/api/v1/storefront/locations/loc_123/analytics-events" \ -H "Content-Type: application/json" \ -H "X-Cart-Token: CART_CAPABILITY" \ -H "Idempotency-Key: analytics_01" \ -d '{ "cartId": "cart_456", "eventType": "CHECKOUT_VIEW" }' ``` The API returns `{ "status": "accepted" }` after it authorizes the cart and records or deduplicates the event. ## Where to fire events Place analytics calls at these points in your storefront: ```tsx filename="src/app/page.tsx" theme={null} // SCAN — fire after the ordering session creates or restores the cart useEffect(() => { if (cartId) { storefront.analyticsEvents.track(locationId, { cartId, eventType: "SCAN" }); } }, [cartId]); ``` ```tsx filename="src/components/CartPanel.tsx" theme={null} // CART_VIEW — fire when cart panel opens function CartPanel({ isOpen }: { isOpen: boolean }) { useEffect(() => { if (isOpen && cartId) { storefront.analyticsEvents.track(locationId, { cartId, eventType: "CART_VIEW", }); } }, [isOpen]); // ... } ``` ```tsx filename="src/app/checkout/page.tsx" theme={null} // CHECKOUT_VIEW — fire on checkout page mount useEffect(() => { if (cartId) { storefront.analyticsEvents.track(locationId, { cartId, eventType: "CHECKOUT_VIEW", }); } }, [cartId]); ``` Do not send `ORDER_PLACED` from a browser or mobile client. Poll the authoritative order result for the UI; the API writes the conversion event during server-side order creation. ## Custom metadata The `metadata` field accepts any key-value pairs. Use it to attach context to events: ```ts theme={null} await storefront.analyticsEvents.track(locationId, { cartId, eventType: "CART_VIEW", metadata: { source: "qr_code", campaignId: "summer_promo_2025", deviceType: "mobile", itemCount: cart.totalQuantity, total: cart.orderTotalWithServiceFee, }, }); ``` ## Google Analytics integration Forward Crave events to Google Analytics for unified reporting: ```ts filename="src/lib/analytics.ts" theme={null} import { storefront } from "@/lib/storefront"; type PublicFunnelEvent = "SCAN" | "CART_VIEW" | "CHECKOUT_VIEW"; const GA_EVENT_MAP: Record = { SCAN: "storefront_visit", CART_VIEW: "view_cart", CHECKOUT_VIEW: "begin_checkout", }; export async function trackEvent( locationId: string, eventType: PublicFunnelEvent, cartId: string, metadata?: Record, ) { // Send to Crave await storefront.analyticsEvents.track(locationId, { cartId, eventType, metadata, }); // Forward to Google Analytics if (typeof window !== "undefined" && window.gtag) { window.gtag("event", GA_EVENT_MAP[eventType], { currency: metadata?.currency ?? "USD", value: metadata?.total ?? 0, items: metadata?.items ?? [], }); } } ``` If you also send a Google Analytics purchase event, do so only after `checkout.getOrderSubmissionOutcome()` returns `PAID`; do not forward that event to the Crave public analytics endpoint. ## View analytics in the Dashboard Analytics data is available in the Crave Dashboard under **Analytics > Storefront**. The dashboard shows: * **Funnel visualization** — conversion rates between each stage * **Event timeline** — raw event stream with metadata * **Location comparison** — performance across multiple locations * **Time-based trends** — daily, weekly, and monthly patterns ## Best practices * **Fire events once** — deduplicate using a ref or flag to prevent double-counting on re-renders * **Don't block the UI** — fire analytics calls without `await` to keep the interface responsive * **Include metadata** — the more context you attach, the more useful your Dashboard reports * **Test outside production first** — confirm events appear in the intended Dashboard environment ```ts theme={null} // Fire-and-forget pattern (don't await) storefront.analyticsEvents .track(locationId, { cartId, eventType: "CART_VIEW", }) .catch(console.error); ``` ## Next steps > [card] [Order Tracking](/docs/guides/order-tracking) > > Track order status after checkout. > [card] [Deployment](/docs/guides/deployment) > > Prepare and verify a storefront deployment without implying payment > admission. # Assisted Ordering Source: https://craveup-1493c4c7.mintlify.dev/docs/guides/assisted-ordering Drive one cart from a voice assistant and a browser at the same time without either losing a write. Assisted ordering is the contract an AI phone agent and a customer's browser share when they are both editing the same cart. Everything here is the ordinary Storefront API — there is no separate assisted surface, no privileged route and no second base URL. What the contract adds is a set of guarantees about concurrency, retries and recovery that a conversational caller needs and a single browser session mostly does not. Two things make assisted ordering different from a normal storefront session: * **Two writers.** The caller speaks while the customer taps. Every cart mutation is therefore concurrency-checked, and the loser is told rather than silently overwritten. * **An unreliable channel.** A call drops, a socket resets, a response is lost after the write landed. So every mutation is idempotent, and every outcome is readable after the fact. > [!NOTE] > > The contract version is `2026-08-27`. Event payloads and headers are pinned to it; see > [Outbound Webhooks](/docs/guides/webhooks) for the delivery envelope itself. ## Base URL ``` https://api.craveup.com/api/v1/storefront https://sandbox-api.craveup.com/api/v1/storefront ``` Cart, ordering-session, cart-item, cart-event, submission and checkout-handoff routes are all mounted under `/api/v1/storefront`. A base URL that stops at `/api/v1` reaches a different route set entirely and will answer `404` in a way that reads like a missing cart. ## Opening a session ```http theme={null} POST /locations/{locationId}/ordering-sessions Idempotency-Key: 6f1f7f38-4c2a-4d59-9d1e-6c9b0a6f1b21 Content-Type: application/json { "fulfillmentMethod": "takeout", "channel": "nomly_assisted" } ``` `channel` is what marks the order as assisted. It flows to the order record and onward to webhooks and merchant surfaces, so set it at session creation rather than trying to attach it later. > [!WARNING] > > **An assisted channel cannot be self-declared.** `nomly_assisted` and `phone` are claims that > someone other than this browser took the order, so they are granted only to a merchant-issued > API key scoped to the location. Send it as `X-API-Key` alongside the request. > > Without it the session is refused with `403`, **not** silently downgraded to `web`. That is > deliberate: a misconfigured integration recording assisted calls as web traffic would produce a > plausible and wrong pilot conversion rate, and nobody would have a reason to look. An > unassisted channel needs no key — a browser saying it is `web` is only describing itself. The response carries the cart and a `cartAccessToken`. Send that token as `X-Cart-Token` on every subsequent request for the cart. | Field | Meaning | | - | - | | `cart.id` | The cart every later path is scoped to. | | `cart.revision` | Monotonic. The concurrency token, also returned as the `ETag`. | | `cart.quoteFingerprint` | Pins a submission to the prices the caller was quoted. | | `cartAccessToken` | Purpose-limited capability. Not a customer session. | ## Concurrency: `If-Match` and `ETag` Every cart mutation requires `If-Match` carrying the revision the caller last saw. Every cart response returns the current revision in the `ETag`. ```http theme={null} POST /locations/{locationId}/carts/{cartId}/items If-Match: "7" Idempotency-Key: 0f2a1c44-8b57-4f0f-9a4e-1d0b2c3e4f5a Content-Type: application/json { "productId": "prod_123", "quantity": 1, "itemUnavailableAction": "REMOVE_ITEM" } ``` | Status | Meaning | What to do | | - | - | - | | `200` | Applied. New revision in the `ETag`. | Continue. | | `409` | Someone else moved the cart on, or the idempotency key was reused with a different payload. | Re-read the cart, tell the caller what changed, retry against the new revision. | | `428` | `If-Match` was missing. | Read the cart first. Do not retry blind. | A `409` from a revision conflict carries the current revision, so recovery is one read rather than a full resynchronisation. > [!WARNING] > > Never retry a `409` by dropping `If-Match`. That converts a reported conflict into a silent > overwrite, which is the failure the header exists to prevent. ## Idempotency `Idempotency-Key` is required on every mutation. Within its retention window: * **The same key with the same payload** returns the original result. Safe to retry as often as the transport requires. * **The same key with a different payload** is refused with `409`. This is deliberate: the alternative silently discards one of two writes that the caller believed were both applied. Generate one key per logical operation, not per HTTP attempt. A caller that regenerates the key on retry has an at-least-once operation, not an idempotent one. ## When the response is lost The most common assisted failure is not an error — it is a write that succeeded whose response never arrived. The contract's answer is that **you never have to guess, and you never resubmit to find out**: 1. Re-read the cart. If the revision advanced, the write landed. 2. For a submission, look it up by whichever identity you still hold: ```http theme={null} GET /locations/{locationId}/carts/{cartId}/submission-lookup GET /locations/{locationId}/carts/{cartId}/submission-lookup?attemptId=... GET /locations/{locationId}/carts/{cartId}/submission-lookup?paymentIntentId=... ``` A voice caller who never saw the reply still knows the cart. A browser that reached payment knows the intent. A client that read the response before losing it knows the attempt. **All three resolve to the same canonical answer** — submission id, order id, cart revision, lifecycle, settlement state and next action. `nextAction` never tells you to resubmit. A submission that cannot progress on its own is either waiting on someone — the customer, or a merchant tender — or finished, and saying so is what stops a lost response from becoming a second order. Resubmitting to discover the outcome is the one thing that can turn an ambiguous result into a duplicate order. ## The cart event stream ```http theme={null} GET /locations/{locationId}/carts/{cartId}/events Last-Event-ID: 42 ``` Server-sent events, authenticated by the same `X-Cart-Token` header as everything else. The token goes in the header, never in a query parameter. Event frames are `cart.created`, `cart.updated`, `cart.locked`, `cart.completed` and `cart.expired`, each carrying a monotonic `id`, the `cartId`, the resulting `revision` and `occurredAt`. Two control frames matter more than the events: | Frame | Meaning | | - | - | | `resync_required` | History from your `Last-Event-ID` is gone (`reason: history_unavailable`). Re-read the cart at `currentRevision` and continue from there. | | `reconnect` | Reconnect; the stream is being closed deliberately. | A replay gap is always **declared**. If you resume from an id the server cannot replay from, you get `resync_required` rather than silence — so a consumer never has to infer that it missed something. ## Submitting ```http theme={null} POST /locations/{locationId}/carts/{cartId}/submissions If-Match: "9" Idempotency-Key: 3a7c2d19-5e8f-4b6a-9c0d-1e2f3a4b5c6d Content-Type: application/json { "acceptedCatalogEvidence": { "catalogRevision": 31 }, "acceptedDiscountEvidence": { "discountRevision": 4 }, "collectionMode": "PAY_AT_STORE", "customerConfirmationRevision": 9, "quoteFingerprint": "..." } ``` `quoteFingerprint` and the two evidence fields pin the submission to what the caller was actually quoted. If the catalog or a discount moved underneath, the submission is refused and requoted rather than committed at the old price. Read the cart again, tell the caller the new total, and submit against the new fingerprint. `OrderSubmissionOutcome` reports the lifecycle, including `CUSTOMER_ACTION_REQUIRED` when payment needs the customer to act. Read the attempt rather than inferring state from the absence of a response. ## Webhook correlation Assisted callers reconcile against outbound events rather than by polling. The correlation model: | Event | Correlate by | | - | - | | `order.created`, `order.status_changed`, `order.cancelled`, `order.refunded` | `cartId` | | `payment.succeeded`, `payment.failed` | `cartId` | | `settlement.updated` | `orderId`, or `cartId` when it is not `null` | `order.created` is what ties a cart to an order id. `settlement.updated` also carries `cartId`, so a settlement that arrives before `order.created` still resolves to its cart. Delivery semantics, all pinned to `2026-08-27`: * Signed `HMAC-SHA256` over `"{timestamp}.{body}"`, base64url, in `Crave-Webhook-Signature` as `v1=…`. Two comma-separated signatures may appear during secret rotation; accept either. * Timestamps outside a **300 second** tolerance must be rejected. * Retried on `408`, `409`, `425`, `429` and `5xx` only — up to **12 attempts**, full-jitter backoff from **30 seconds** to a **6 hour** cap, honouring `Retry-After` up to **1 hour**. * **Every other 4xx is terminal.** A delivery your endpoint refuses with `400` is never retried. > [!WARNING] > > If you validate payloads with a strict schema, an added field is a **breaking change on your > side**. Crave may add fields within a contract version; a strict validator rejects the unknown > key, answers `400`, and the delivery is dropped permanently rather than retried. Accept unknown > fields, or track the registry and deploy your schema change first. ## Verifying an integration Crave ships a black-box conformance suite that exercises this contract end to end — normal session, simultaneous conflict, identical retry, changed-payload retry, response loss, replay gap, stale evidence, ambiguous lookup, and delivery signing and routing: ```bash theme={null} CRAVE_CONFORMANCE_CREDENTIAL= \ pnpm --filter express-admin-and-storefront-api script:assisted-ordering-conformance \ --base-url https://sandbox-api.craveup.com/api/v1/storefront \ --location \ --product \ --out conformance-report.json ``` The report is redacted before it is written: neither the credential nor the receiver URL appears in it, so it is safe to attach to a review. # Build a Custom Storefront Source: https://craveup-1493c4c7.mintlify.dev/docs/guides/build-custom-storefront Scaffold and extend a direct, capability-safe Crave ordering experience. ## 1. Scaffold with the CLI ```bash theme={null} npx @craveup/cli init ``` The CLI may authenticate you to discover or validate merchant resources, but it does not write a private credential into the generated browser app. ## 2. Configure public values ```env theme={null} NEXT_PUBLIC_CRAVEUP_API_URL=https://api.craveup.com NEXT_PUBLIC_CRAVEUP_LOCATION_ID=loc_456def NEXT_PUBLIC_CRAVEUP_MERCHANT_SLUG=downtown-pizza NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_live_xxx ``` The API origin is configuration, not a credential. Use the sandbox origin and publishable key in non-production environments. These merchant and location variables are standalone/local overrides. The hosted template resolves the merchant from its controlled host/subdomain and the location from the `[locationId]` route. ## 3. Create separate browser and server clients Browser code supplies a tab-scoped cart `sessionStore` and `getAuthToken`. Server Components create a client with the same explicit `baseUrl` and perform anonymous published reads only. ```ts theme={null} import { createStorefrontClient } from "@craveup/storefront-sdk"; export const storefront = createStorefrontClient({ baseUrl: process.env.NEXT_PUBLIC_CRAVEUP_API_URL!, sessionStore, getAuthToken, getMerchantSlug: () => merchantSlug, }); ``` ## 4. Follow the capability lifecycle 1. Load published merchant, location, and menu data anonymously. 2. Start an ordering session with a generated idempotency key. 3. Store the returned cart capability in versioned `sessionStorage`, scoped by canonical API environment, merchant, and location. 4. Let the SDK attach the capability, `If-Match`, and idempotency headers. 5. On `CART_CONFLICT`, reload the cart before asking the shopper to retry. 6. Clear the capability after claim, deletion, expiry, or terminal checkout handling. ## 5. Checkout Ask the server which collection modes the current cart may use. This is a preflight only; submission repeats every authority and exposure check. ```ts theme={null} const collectionOptions = await storefront.checkout.getCollectionOptions( locationId, cartId, { revision: cart.revision }, ); ``` Render `Pay online` only when the `ONLINE` option is available. Render `Pay at store` only when `PAY_AT_STORE` is available, and use its server-returned Square, Clover, or Toast label to explain where payment will be collected. ```ts theme={null} const outcome = await storefront.checkout.submitOrder( locationId, cartId, { acceptedCatalogEvidence, acceptedDiscountEvidence, collectionMode: "ONLINE", customerConfirmationRevision, quoteFingerprint, }, { idempotencyKey, revision: cart.revision, includeCustomerContext: true }, ); ``` Use `includeCustomerContext` only when a signed-in shopper still has a guest capability and the selected provider needs customer association. Omit it for guest checkout; a claimed cart uses customer authentication automatically. Render account-scoped Stripe Elements only when `outcome.status` is `CUSTOMER_ACTION_REQUIRED`, then poll `checkout.getOrderSubmissionOutcome` with the returned attempt id. Treat `PROCESSING` as retryable, render success only for `PAID`, and surface `ACTION_REQUIRED` without creating another order. For pay at store, submit the same payload with `collectionMode: "PAY_AT_STORE"` and omit `savedPaymentMethodId`. An `ACCEPTED` response confirms the order, not payment. Continue polling the same attempt while the selected POS supplies native tender evidence. Never render a POS browser payment form, provider-hosted checkout, saved card, or gift-card input for pay at store. If evidence is delayed, show **Verifying payment — do not charge again** rather than creating a second collection attempt. ## 6. Customer and receipt access Clerk owns customer sign-in and session recovery. After Clerk is ready, supply its active-session `getToken({ template: "crave-customer" })` callback as `getAuthToken`, keep `getMerchantSlug`, and never persist the customer JWT yourself. Receipt links use a purpose-limited fragment capability: remove the fragment immediately, keep the token in tab-scoped storage keyed by API environment, merchant, and receipt ID, and pass it through `receipts.get`. ## 7. Deploy * Configure the exact storefront origin in the API CORS allowlist. * Keep provider and private integration credentials on the API service. * Run tests, lint, type checking, a production build, and a static-bundle secret scan. * Verify a real published catalog read and a sandbox ordering flow before promoting production. See [Deployment](/docs/guides/deployment) and the [Storefront SDK](/docs/getting-started/storefront-sdk) for the full contract. # Checkout Flow Source: https://craveup-1493c4c7.mintlify.dev/docs/guides/checkout-flow Persist an order first, use Stripe online or certified POS-native pay at store, and recover its authoritative outcome. Checkout uses the same cart capability, revision, and idempotency protections as other cart mutations. Submitting an order is a write and is never an anonymous lookup by cart ID. > [!WARNING] > > The published TypeScript SDK is 2.0.1. The order-first methods in this guide > require SDK 3.0.0, which is not yet published. A consumer pinned to 2.0.1 > lacks the current scoped menu/cart context, and its `createPaymentIntent()` > and `getOrderResult()` methods target retired routes. > Keep direct payment and result recovery blocked until a compatible package is > released. Do not infer payment from a browser redirect or app return. > [!WARNING] > > During the direct-charge cutover, ordinary Stripe payment admission is hard > locked in sandbox and production. `submitOrder()` returns > `STRIPE_DIRECT_CHARGE_CUTOVER_INCOMPLETE`; show checkout as temporarily > unavailable and do not retry or bypass this response. Catalog and cart > development can continue while the lock remains. ## 1. Finalize the cart ```ts theme={null} await storefront.cart.update("loc_123", cartId, { fulfillmentMethod: "takeout", }); await storefront.cart.updateOrderTime("loc_123", cartId, { pickupType: "ASAP", }); await storefront.cart.validateAndUpdateCustomer("loc_123", cartId, { customerName: "Alex Johnson", emailAddress: "alex@example.com", phoneNumber: "+1234567890", }); ``` Each call uses the latest cart revision. If a call returns `CART_CONFLICT`, refresh the cart and require an explicit retry. Guest contact requires a customer name and at least one email address or phone number. This associates contact with the cart; it does not authenticate the shopper or claim the guest capability. Sign-in and OTP are not required for guest checkout. ## 2. Read the current collection options ```ts theme={null} const choices = await storefront.checkout.getCollectionOptions( "loc_123", cartId, { revision: cart.revision }, ); ``` Render only available server-returned choices. This preflight is not an admission lease; submission repeats the policy, certification, identity, and unpaid-exposure checks. ## 3. Submit the canonical order ```ts theme={null} const outcome = await storefront.checkout.submitOrder( "loc_123", cartId, { acceptedCatalogEvidence, acceptedDiscountEvidence, collectionMode: "ONLINE", customerConfirmationRevision, quoteFingerprint, }, { idempotencyKey: crypto.randomUUID(), revision: cart.revision }, ); ``` ```bash theme={null} curl -X POST "https://api.craveup.com/api/v1/storefront/locations/loc_123/carts/cart_456/submissions" \ -H "X-Cart-Token: $CART_ACCESS_TOKEN" \ -H 'If-Match: "cart-4"' \ -H "Idempotency-Key: order_01" ``` The server persists one canonical order and submission attempt before it creates the Stripe PaymentIntent. Reusing the same idempotency key recovers the same attempt; it never creates a second order. Square, Clover, and Toast are not online processor choices. ## 4. Confirm Stripe customer action When `outcome.status` is `CUSTOMER_ACTION_REQUIRED`, initialize Stripe.js with the returned `connectedAccountId` and confirm the returned `clientSecret`: ```tsx theme={null} const { error, paymentIntent } = await stripe.confirmPayment({ elements, confirmParams: { return_url: `${window.location.origin}/checkout/stripe-return`, }, redirect: "if_required", }); if (error) throw error; if ( !paymentIntent || !["requires_capture", "succeeded"].includes(paymentIntent.status) ) { throw new Error("Stripe payment is not ready for capture"); } ``` Never add the cart capability to `return_url`. A redirect recovery page may carry non-secret cart, attempt, and PaymentIntent identifiers, but it must recover the capability from tab-scoped storage and poll the same persisted attempt before treating payment as complete. ## 5. Recover the order outcome ```ts theme={null} const result = await storefront.checkout.getOrderSubmissionOutcome( "loc_123", cartId, outcome.attemptId, ); switch (result.status) { case "PROCESSING": case "CUSTOMER_ACTION_REQUIRED": // Poll again with bounded backoff or complete the requested Stripe action. break; case "PAID": // Online payment and canonical settlement are complete. break; case "ACCEPTED": // PAY_AT_STORE only: the order exists, but native POS payment is still due. // Read result.verification?.state for PENDING, WARNING, ACTION_REQUIRED, // VERIFIED, CONCLUSIVE_FAILURE, or CANCELED counter-verification state. break; case "ACTION_REQUIRED": // Show the retry-safe operator/customer action without creating another order. break; } ``` Only `PAID` proves payment. For `ACCEPTED`, explain where the customer will pay and continue polling the same attempt. If provider evidence is delayed, show **Verifying payment — do not charge again**. Never infer success from a redirect, provider response, POS order status, or a settlement row whose submission attempt has not reached its terminal state. > [card] [Accept Payments](/docs/guides/accept-payments) > > Integrate Stripe Elements without exposing server secrets. > [card] [Order Tracking](/docs/guides/order-tracking) > > Implement bounded result polling and receipts. > [card] [Assisted Ordering](/docs/guides/assisted-ordering) > > Drive one cart from a voice assistant and a browser at once. # Crave Cloud Overview Source: https://craveup-1493c4c7.mintlify.dev/docs/guides/crave-cloud-overview Build and test restaurant storefronts with a managed backend, Business Manager, and workspace billing. Crave Cloud hosts the restaurant backend behind Crave.js storefronts. Use the [Developer Console](https://developer.craveup.com/console) to manage your business workspace, projects, hosting subscription and customer-payment connection. Use each project's **Business Manager** to manage its restaurant and menus. > [!NOTE] > > Develop is for development and testing. Onboarding is currently assisted and > subject to available capacity. A working test installation does not activate > live restaurant payments or establish general self-service availability. ## Workspace and projects One workspace represents one merchant business. Its team, hosting billing and customer-payment connection belong to that workspace. A project is the restaurant application. Select its **Sandbox** or **Production** environment to open that environment's installation, Business Manager and storefront. The environments have separate data, URLs and payment bindings; changing the hosting plan must not turn test data into production data. Supported environments inherit the workspace's verified payment connection for the matching merchant and payment mode. An existing different account is not replaced silently. | Surface | Use it for | | - | - | | **Developer Console** | Projects, installation status, recent activity, customer payments, hosting subscription, invoices and workspace team access. | | **Business Manager** | Restaurant administration, menu editing and publication, and supported order operations. Open it from the intended project. | | **Storefront** | Customer-facing menus, cart, checkout and order confirmation for the installation. | | **Crave.js** | Storefront templates, SDKs and developer tooling for building a custom customer experience. Package and API versions must be compatible. | | **Restaurant OS desktop** | A separate staff frontend over the canonical backend, subject to its own installation and staff-auth configuration. | A ready backend, a published menu and payment readiness are separate states. Check each in the selected environment. When an installation includes a clearly labeled sample menu, replace its sample items with your own menu before sharing the storefront. Sample content and test orders are not live merchant activity. ## Sandbox and Production Use Sandbox for test orders and menu changes. Launch's intended package keeps a persistent shared Sandbox alongside a dedicated Production application service. The complete self-service upgrade is still undergoing acceptance; existing workspaces with duplicate hosting subscriptions require billing reconciliation. Do not buy a second base subscription to create a testing environment. Menu publication and code releases are different actions. Where publication is available, review the Sandbox menu changes before copying them to Production. Existing Production items removed from Sandbox are retained. Orders, customers and payment objects are not copied. A new hosting plan does not publish a menu, switch environment roles or activate live customer payments. ## Hosting plans | Plan | Monthly subscription | Application resources | Intended use | | - | - | - | - | | **Develop** | \$29 | Shared application resources with isolated restaurant installations | Development and test checkout; platform-managed upgrades. | | **Launch** | \$99 | A dedicated application service per restaurant | Arranged with Crave; live-payment activation and operational readiness are reviewed separately. | Each installation serves its canonical API, storefront and embedded Business Manager through one application origin. Develop projects share the application service; creating a project does not give it a separate Docker service or an independently selected image. Database and cache resources are separate from the application service. A dedicated application service does not imply dedicated database/cache resources or unlimited capacity. Confirm inclusions and limits with your hosting agreement. See [current pricing](https://developer.craveup.com/pricing). Crave's hosting subscription is separate from restaurant order payments. ## Customer payments Restaurants connect an eligible **merchant-owned Stripe account**. Crave does not take an order application fee under this hosting model. Stripe processing charges are separate from the Crave subscription. Sandbox permits test payments only. Production hosting can retain a test-mode connection while checkout is being verified; the Production label does not mean real money will be charged. Read the payment mode in the selected environment. Test payments do not produce live payouts, and paying for a hosting subscription does not enable live restaurant processing. Account eligibility and the canonical readiness checks determine whether payment is available. Workspace-first connection without an existing project is being completed; do not assume that a visible page or an existing connected workspace proves fresh account authorization is available in every environment. Follow the supported flow shown in your Console and [Stripe payment guidance](/docs/guides/integrations/stripe). ## Staff and customer identity Staff identity authorizes workspace and restaurant administration. Customer identity authorizes storefront customer actions; guest checkout capabilities are separate. Ordering never makes a guest a member of the merchant's staff workspace. Customer-authentication contracts are changing across release lanes. The selected API-owned successor uses server-side provider verification with tenant-scoped opaque application sessions. That source direction is not a claim that every hosted API or public SDK has activated it. Use the exact SDK/API pair approved for your environment; do not combine older token-provider examples with successor session methods or add an authentication fallback. ## Developer package compatibility Registry availability, source implementation and hosted support are separate. As checked on October 19, 2026: | Package | npm `latest` | npm `development` | | - | - | - | | `@craveup/storefront-sdk` | `2.0.1` | `4.0.0` | | `@craveup/commerce-contracts` | `1.0.0` | `4.0.0` | | `@craveup/cli` | `1.4.0` | — | > [!WARNING] > > Use the storefront included with your Cloud project for checkout. We have not > verified a published npm SDK for the current managed Cloud API. Do not connect > the 2.x checkout examples to a Cloud project or assume the `development` tag is > compatible. October 19 checks against the managed Sandbox release found: | Client | Verified result | | - | - | | SDK `2.0.1` | Merchant, location, ordering-readiness and menu reads succeeded. Its payment-intent route differs from the Cloud order-submission route; full checkout is not supported by this result. | | SDK `3.0.0` / contracts `2.0.0` | An empty cart session worked, but published menu and cart schema checks failed. | | SDK `3.1.0` / contracts `3.0.0` | Published menu and cart schema checks failed. | | SDK `4.0.0` / contracts `4.0.0` | An empty cart session worked, but published menu and cart schema checks failed. | | Included Cloud storefront | A TEST order reached customer confirmation and Business Manager Paid/Captured with zero due. This uses the client bundled with that runtime. | For a custom frontend, contact Crave for a release pair validated against your installation before implementing checkout or customer authentication. The [Storefront SDK guide](/docs/getting-started/storefront-sdk) describes the separate published 2.x API contract. A successful catalog request does not establish cart, checkout, authentication or loyalty compatibility. These checks do not promote an npm tag or establish compatibility with every Cloud release. ## Additional capabilities Ordering, identity, payments and loyalty have separate configuration and activation requirements. Loyalty includes implemented admission and lifecycle work, but enabled ordering does not automatically mean loyalty is enabled for a merchant. External loyalty, POS and payment providers require their specific integration and readiness checks; vendor names are not prebuilt connector promises. Workspace automation keys, external-app Connections, Add-ons, true resource metering and automated Launch deployment are not part of the supported Develop self-service promise. Activity describes project events, not resource usage or metered spend. Public demos and template previews are presentation/test content. For package licensing and deployment responsibilities, see [Developer Package and Crave Cloud](/docs/guides/open-source-and-cloud). # Customer identity Source: https://craveup-1493c4c7.mintlify.dev/docs/guides/customer-identity Build guest checkout and verified customer accounts without crossing restaurant organizations. Crave customers belong to one restaurant organization and are shared by that organization's locations. The same diner ordering from an unrelated organization has a separate customer record. ## Guest checkout Guest checkout remains available without an identity-provider session. Crave normalizes the supplied email or phone and creates or reuses only a `guest` customer inside the resolved organization. If the contact already belongs to a verified customer, Crave creates a separate guest shadow record; it never returns the verified profile, addresses, saved payment methods, loyalty membership, or order history. ## Sign-in and tenant binding Crave Customer Identity uses the environment-specific Clerk application. Clerk owns sign-in, verification, session recovery, logout, and token refresh, so an integration built on a published SDK calls no Crave customer login or OTP endpoint. The storefront requests a short-lived JWT from the active Clerk session with the `crave-customer` token template and supplies it to the SDK only through `getAuthToken`. Do not copy the token into `localStorage`, `sessionStorage`, SecureStore, URLs, logs, or analytics. > [!NOTE] > > The Storefront API reference also lists `/merchant/{merchantSlug}/auth/*` routes for code > challenges and customer sessions. They belong to the API-owned authentication candidate for SDK > 5.0.0 and contracts 5.0.0, which is not yet published or activated. Don't call them from an > integration that uses Clerk with a published SDK. Every customer-capable SDK client must also provide `getMerchantSlug`. The SDK sends that value as `X-Crave-Merchant-Slug`, and Crave maps the verified Clerk subject to a customer inside that exact restaurant organization. One Clerk diner can therefore have separate Crave customer records for unrelated merchants without exposing data across organizations. Create customer clients and render customer-only data only after Clerk is loaded and signed in: ```ts theme={null} const storefront = createStorefrontClient({ baseUrl, sessionStore, getAuthToken: () => getToken({ template: "crave-customer" }), getMerchantSlug: () => merchantSlug, }); ``` The Customer Clerk application, token template, allowed origins, and sign-in methods must be activated separately in development/sandbox and production. Use only Crave-provided public Clerk configuration for the matching environment; never place a Clerk secret key in a storefront. Verified customer responses expose `identityState` and verified contact channels. They never expose provider subjects, challenge IDs, Stripe customer IDs, loyalty member IDs, or internal consent evidence. ## Export and deletion An authenticated customer can download their organization-scoped data from `GET /customer/data-export`. `DELETE /customer` requires an `Idempotency-Key` and starts a durable privacy operation. Crave returns `completed` only after local minimization and all provider-owned data has been erased. Automatic provider work returns `processing`; loyalty/manual obligations or a provider failure that needs intervention returns `requires_action`. Crave never reports a partial deletion as complete. Crave automatically processes Stripe platform customers, account-scoped Square customers, and linked Clover customers. Each attempt is durable, reads provider truth before a delete, and reads again after the delete. Network ambiguity remains in `processing`; permission or ownership mismatches require support. Poll `GET /customer/privacy-operations/{operationId}` for safe progress. The response contains provider, state, attempt, retry time, and a safe error code, but never a provider customer or merchant identifier. Support may retry an action-required provider task only after resolving its cause through the workforce-only retry endpoint. The action adds a bounded attempt allowance and writes a support audit; it cannot replay a confirmed or actively processing task. Loyalty membership erasure remains part of the loyalty integration and keeps the customer active until it is proven. ## Recovering a guest order After verification, a customer may call `POST /customer/order-claims` with an `Idempotency-Key` and an order ID. Crave accepts a claim only when: * the order and customer belong to the same organization; * the order is no more than 30 days old and is not cancelled or refunded; * the order still belongs to an active guest customer; * the claimant proved the exact email or phone stored in the immutable order snapshot; and * no other customer has claimed the order. The transfer, cart ownership update, claim audit, and collision resolution are one database transaction. Loyalty reconciliation happens after ownership succeeds and remains visibly pending if the loyalty provider cannot complete it. ## Sensitive customer features Order history, addresses, saved payment methods, gift cards, and loyalty routes require a verified customer session. Caller ID, a submitted contact, a guest record, and an identity-state label by itself are never authorization evidence. Successful first-time Crave linkage of a Clerk-verified customer emits the signed `customer.verified` webhook. See [Webhooks](/docs/guides/webhooks) for delivery and retry behavior. # Deployment Source: https://craveup-1493c4c7.mintlify.dev/docs/guides/deployment Deploy a direct Crave storefront with exact origins and no browser credentials. ## Select the project environment In [Developer Console](https://developer.craveup.com/console), open your project and select **Sandbox** or **Production** before copying its API endpoint or opening Business Manager. Each environment has separate restaurant data and URLs. Launch retains a shared Sandbox alongside its dedicated Production application; upgrading does not convert test orders into Production orders. The environment name and payment mode are separate. A Production installation can use test payments during verification. Confirm the displayed payment mode before testing checkout. Publishing a reviewed Sandbox menu copies only its menu changes; it does not deploy code or transfer orders, customers or payments. ## Storefront environment | Variable | Required | Description | | - | - | - | | `NEXT_PUBLIC_CRAVEUP_API_URL` | Yes | Public Crave API origin. | | `NEXT_PUBLIC_CRAVEUP_LOCATION_ID` | Standalone/local quickstarts | Published location override. | | `NEXT_PUBLIC_CRAVEUP_MERCHANT_SLUG` | Standalone/local quickstarts | Published merchant override. | | `NEXT_PUBLIC_STOREFRONT_URL` | Optional | Canonical metadata override; defaults to the request host. | | `NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY` | For checkout | Browser-safe Stripe publishable key for the same environment. | | `NEXT_PUBLIC_GOOGLE_MAPS_API_KEY` | For delivery maps | Browser key restricted by domain and API. | In the hosted `cravejs-storefront-template`, the controlled host/subdomain selects the merchant and the `[locationId]` route selects the location. Do not duplicate those tenant selectors as production environment variables. The prefixed merchant and location variables above are only for standalone or local quickstart wiring. The canonical storefront origin is host-derived from request headers by default; set `NEXT_PUBLIC_STOREFRONT_URL` only when deployment metadata needs an explicit override. Do not configure private Crave API keys, provider credentials or inbound webhook secrets, cart capabilities, customer JWTs, or receipt capabilities as public variables. ## API service environment Provider credentials remain on the API service. Every browser deployment needs its exact browser origin registered before it sends credentials or capabilities. An origin is the scheme, hostname, and non-default port; paths are not part of an origin. For the Crave-managed API, provide the local-development, stable-preview, and production origins to the Crave integration owner. There is currently no wildcard or arbitrary self-service bypass. Register stable preview origins individually; do not attempt to allow every generated preview hostname. Operators of the API service configure the approved origins as a comma-separated list: ```env theme={null} CORS_ALLOWED_ORIGINS=https://order.example.com,https://preview.example.com ``` First-party `https://*.craveup.com` origins are allowed by default. Localhost is allowed only outside production. The API accepts `Authorization`, `X-Cart-Token`, `X-Checkout-Handoff`, `X-Receipt-Token`, `Idempotency-Key`, `If-Match`, `X-Request-Id`, and `Content-Type`, and exposes `ETag` plus `X-Request-Id`. Restart or redeploy the API after changing its static allowlist, then verify the preflight from the exact deployed origin. Native iOS and Android requests normally omit the browser `Origin` header. Expo web, embedded web views that send an origin, and browser storefronts still require exact registration. ## Vercel or Netlify 1. Import the storefront repository. 2. Add the public variables for the correct environment. 3. Add the deployed origin to the API allowlist before testing cross-origin requests. 4. Build and deploy a preview. 5. Verify anonymous catalog reads, ordering-session creation, cart mutation, payment-session handling, and terminal order polling. 6. Promote the exact verified commit to production. ## Required release gates ```bash theme={null} pnpm test pnpm lint pnpm check-types pnpm build ``` Also scan generated browser assets for credentials and validate that cart/customer/receipt capabilities never appear in URLs or analytics. A healthy page load alone is not an ordering-flow verification. ## Rotation and rollback Rotating private provider credentials does not require rebuilding the storefront. Rotating the cart capability key ring requires the API migration/runbook for active carts. Roll back API and storefront releases together only when their public contract differs; otherwise deploy the failing surface independently. # Display Menu Source: https://craveup-1493c4c7.mintlify.dev/docs/guides/display-menu Fetch menus, categories, and products for a location. This guide covers how to load a restaurant's menu data and display it in your storefront — including multiple menus, category filtering, and product details. ## How menus work Every Crave location has one or more **menus**. Each menu contains **categories**, and each category links to **products**. The active menu depends on the current time and the location's schedule. ``` Merchant → Location → Menu(s) → Categories → Products → Modifiers ``` ## Fetch location data The location response includes basic metadata. Menu and product data comes from the ordering session and API endpoints. ```ts SDK theme={null} import { storefront } from '@/lib/storefront'; const location = await storefront.locations.getById('loc_123'); console.log(location.restaurantDisplayName); ``` ```bash REST theme={null} curl "https://api.craveup.com/api/v1/storefront/locations/loc_123" ``` ## Start a session to get the menu Menus are anonymous published resources. Start an ordering session only when the customer begins a cart; the response includes the cart capability used for later cart operations. ```ts SDK theme={null} const session = await storefront.orderingSessions.start('loc_123', { marketplaceId: 'web', fulfillmentMethod: 'takeout', }); const menu = await storefront.menus.list('loc_123', {}); ``` ```bash REST theme={null} curl -X POST "https://api.craveup.com/api/v1/storefront/locations/loc_123/ordering-sessions" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: session_01" \ -d '{"marketplaceId":"web","fulfillmentMethod":"takeout"}' ``` `marketplaceId` is optional source attribution, such as `"web"`; it is not the location identifier. The route already provides the location scope. ## Display categories Categories are used to group products (e.g., "Appetizers", "Mains", "Drinks"). Render them as tabs or a sidebar. ```tsx filename="components/CategoryTabs.tsx" theme={null} interface Category { id: string; name: string; productIds: string[]; } function CategoryTabs({ categories, activeId, onSelect, }: { categories: Category[]; activeId: string; onSelect: (id: string) => void; }) { return (
{categories.map((cat) => ( ))}
); } ``` ## Display products Each product includes a name, description, price, images, and modifier groups. ```tsx filename="components/ProductCard.tsx" theme={null} interface Product { id: string; name: string; description: string; price: string; displayPrice: string; images: string[]; } function ProductCard({ product, onAdd, }: { product: Product; onAdd: () => void; }) { return (
{product.images[0] && ( {product.name} )}

{product.name}

{product.description}

{product.displayPrice}
); } ``` ## Filter and search Crave menus are returned as structured data. You can implement client-side filtering: ```ts theme={null} // Filter products by category const categoryProducts = products.filter((p) => activeCategory.productIds.includes(p.id) ); // Search by name const searchResults = products.filter((p) => p.name.toLowerCase().includes(query.toLowerCase()) ``` ## Get order times Fetch the available time slots for ASAP or scheduled orders. ```ts SDK theme={null} const orderTimes = await storefront.locations.getOrderTimes('loc_123'); if (orderTimes.requireScheduledOrders) { // Show day/time picker from orderTimes.orderDays } else { // ASAP is available; optionally show schedule option console.log('Schedule allowed:', orderTimes.scheduleAllowed); } ``` ```bash REST theme={null} curl "https://api.craveup.com/api/v1/storefront/locations/loc_123/time-intervals" ``` ## Product types The SDK exports these types for working with menu data: | Type | Description | | - | - | | `Menu` | Top-level menu with `id`, `name`, `isActive`, and `categories` | | `Category` | Grouping with `id`, `name`, and `productIds` | | `Product` | Full product with price, images, modifiers, and nutrition | | `Modifier` | Modifier group with selection rules and items | | `ModifierItem` | Individual modifier option with price and max quantity | ## Next steps > [card] [Manage Cart](/docs/guides/manage-cart) > > Add products to the cart with modifier selections. > [card] [Checkout Flow](/docs/guides/checkout-flow) > > Collect customer details and process payments. # Error Codes Source: https://craveup-1493c4c7.mintlify.dev/docs/guides/error-codes Handle public Storefront API errors without leaking credentials or replaying unsafe writes. Every Storefront API error has a stable machine-readable code and a request ID: ```json theme={null} { "code": "CART_CONFLICT", "message": "The cart changed. Refresh it and try again.", "requestId": "req_123", "details": {} } ``` ## SDK errors ```ts theme={null} import { StorefrontApiError, StorefrontClientStateError, StorefrontProtocolError, StorefrontTimeoutError, } from "@craveup/storefront-sdk"; try { await storefront.cart.addItem(locationId, cartId, payload); } catch (error) { if (error instanceof StorefrontApiError) { console.error(error.code, error.requestId); if (error.retryAfterMs !== undefined) scheduleRetry(error.retryAfterMs); } else if (error instanceof StorefrontClientStateError) { console.error(error.code); } else if (error instanceof StorefrontProtocolError) { console.error(error.reason, error.method, error.routeTemplate); } else if (error instanceof StorefrontTimeoutError) { showRetryMessage(); } } ``` `StorefrontApiError.retryAfterMs` is a bounded millisecond delay parsed from a valid `Retry-After` response header, or `undefined` when no usable delay was provided. `StorefrontClientStateError` is a local preflight failure; for example, `CUSTOMER_AUTH_REQUIRED` means no customer JWT was available and no request was sent. `StorefrontProtocolError.reason` is `EMPTY_RESPONSE` or `INVALID_JSON` when a successful response violates the SDK's JSON contract. Neither error retains response content, credentials, or secrets. Do not log capability, JWT, receipt-token, authorization, or payment-secret values with an error. ## Public error codes | Code | Typical status | Client behavior | | - | - | - | | `VALIDATION_ERROR` | 400 or 422 | Correct the fields described in `details` | | `UNAUTHORIZED` | 401 | Restore the matching cart capability or reauthenticate the customer | | `FORBIDDEN` | 403 | Stop; the authenticated principal does not own the resource | | `NOT_FOUND` | 404 | Treat the resource as unavailable; protected endpoints may conceal existence | | `RATE_LIMITED` | 429 | Honor `Retry-After` and back off | | `CART_CONFLICT` | 409 | Fetch the latest cart and require an explicit retry | | `RESOURCE_CONFLICT` | 409 | Refresh the affected customer resource before retrying | | `CART_IMMUTABLE` | 409 | Stop mutating a locked, completed, or expired cart | | `IDEMPOTENCY_KEY_REQUIRED` | 400 | Retry once with a stable unique key for that logical write | | `IDEMPOTENCY_KEY_REUSED` | 409 | Generate a new key because the old key belongs to different input | | `IDEMPOTENCY_IN_PROGRESS` | 409 | Poll or retry with bounded backoff using the same logical operation | | `DEPENDENCY_UNAVAILABLE` | 503 | Show a temporary failure and retry with backoff | | `INTERNAL_ERROR` | 500 | Show a generic message and retain the request ID for support | ## Retry rules Retry reads and explicitly retryable failures such as `RATE_LIMITED` or `DEPENDENCY_UNAVAILABLE` with exponential backoff. Prefer `retryAfterMs` when the API supplies it. Treat `StorefrontProtocolError` as an upstream contract or edge-transformation failure, retain its method and route template for support, and retry only when the underlying operation is safe. Never automatically replay a cart mutation after `CART_CONFLICT`, and never invent a new idempotency key while the outcome of an earlier write is unknown. ```ts theme={null} if (error instanceof StorefrontApiError && error.code === "CART_CONFLICT") { const cart = await storefront.cart.get(locationId, cartId); replaceCartState(cart); askCustomerToRetry(); } ``` > [card] [Manage Cart](/docs/guides/manage-cart) > > See the revision and idempotency lifecycle. > [card] [REST API](/docs/getting-started/rest-api) > > Review authentication boundaries and required headers. # Fulfillment Methods Source: https://craveup-1493c4c7.mintlify.dev/docs/guides/fulfillment-methods Configure delivery, table-side, and room service for your storefront orders. Crave supports four fulfillment methods. This guide covers how to set each one on a cart and what data each method requires. ## Available methods | Method | Value | Use case | | - | - | - | | **Takeout / Pickup** | `takeout` | Customer picks up at the counter | | **Delivery** | `delivery` | Order delivered to customer's address | | **Table-side** | `table_side` | Dine-in, delivered to a table number | | **Room service** | `room_service` | Hotel/hospitality, delivered to a room | ## Check which methods are enabled Each location has a `methodsStatus` field indicating what's available. ```ts theme={null} const merchant = await storefront.merchant.getBySlug("downtown-pizza"); const location = merchant.locations[0]; console.log(location.methodsStatus); // { pickup: true, table: true, delivery: true, roomService: false } ``` Only show fulfillment options that are enabled for the location. ## Takeout (default) Takeout is the simplest method — just set the fulfillment method on the cart. ```ts SDK theme={null} await storefront.cart.update('loc_123', cartId, { fulfillmentMethod: 'takeout', }); ``` ```bash REST theme={null} curl -X PATCH "https://api.craveup.com/api/v1/storefront/locations/loc_123/carts/{cartId}" \ -H "X-Cart-Token: $CART_ACCESS_TOKEN" \ -H 'If-Match: "cart-2"' \ -H "Idempotency-Key: fulfillment_01" \ -H "Content-Type: application/json" \ -d '{"fulfillmentMethod": "takeout"}' ``` ## Delivery Delivery requires the customer's address with geographic coordinates for distance calculation and fee computation. **1. Check delivery distance** Calculate the distance between the customer and the location to validate the delivery zone. **2. Set delivery address** Save the address to the cart. ### Check delivery distance ```ts SDK theme={null} const distance = await storefront.locations.distance('loc_123', { lat: 37.7749, lng: -122.4194, unit: 'miles', }); console.log(`${distance.distance.miles} miles away`); ``` ```bash REST theme={null} curl -X POST "https://api.craveup.com/api/v1/storefront/locations/loc_123/distance" \ -H "Content-Type: application/json" \ -d '{"lat": 37.7749, "lng": -122.4194, "unit": "miles"}' ``` ### Set delivery address ```ts SDK theme={null} await storefront.cart.setDelivery('loc_123', cartId, { street: '123 Main Street', city: 'San Francisco', state: 'CA', zipCode: '94105', country: 'United States', lat: 37.7749, lng: -122.4194, }); ``` ```bash REST theme={null} curl -X PUT "https://api.craveup.com/api/v1/storefront/locations/loc_123/carts/{cartId}/set-delivery" \ -H "X-Cart-Token: $CART_ACCESS_TOKEN" \ -H 'If-Match: "cart-3"' \ -H "Idempotency-Key: delivery_01" \ -H "Content-Type: application/json" \ -d '{ "street": "123 Main Street", "city": "San Francisco", "state": "CA", "zipCode": "94105", "country": "United States", "lat": 37.7749, "lng": -122.4194 }' ``` The `Address` type requires these fields: | Field | Type | Required | Description | | - | - | - | - | | `street` | `string` | Yes | Street address | | `streetOptional` | `string` | No | Apt/suite/floor | | `city` | `string` | Yes | City | | `state` | `string` | Yes | State/province code | | `zipCode` | `string` | Yes | Postal code | | `country` | `string` | Yes | Full supported country name (for example, `United States`) | | `lat` | `number` | Yes | Latitude | | `lng` | `number` | Yes | Longitude | > [!TIP] > > Use a geocoding service (Google Places, Mapbox) to get `lat`/`lng` from the > customer's address input. ## Table-side Table-side service sends the order to a specific table number within the restaurant. ```ts SDK theme={null} await storefront.cart.setTable('loc_123', cartId, '12'); ``` ```bash REST theme={null} curl -X PUT "https://api.craveup.com/api/v1/storefront/locations/loc_123/carts/{cartId}/set-table" \ -H "X-Cart-Token: $CART_ACCESS_TOKEN" \ -H 'If-Match: "cart-3"' \ -H "Idempotency-Key: table_01" \ -H "Content-Type: application/json" \ -d '{"tableNumber": "12"}' ``` Table numbers are numeric strings, such as `"12"` or `"12.5"`. Do not send labels or prefixes such as `"T-12"` or `"Patio 3"`. ## Room service Room service is designed for hotels and hospitality venues. It requires a room number and the guest's last name for verification. ```ts SDK theme={null} await storefront.cart.setRoom('loc_123', cartId, { roomNumber: '405', lastName: 'Johnson', }); ``` ```bash REST theme={null} curl -X PUT "https://api.craveup.com/api/v1/storefront/locations/loc_123/carts/{cartId}/set-room" \ -H "X-Cart-Token: $CART_ACCESS_TOKEN" \ -H 'If-Match: "cart-3"' \ -H "Idempotency-Key: room_01" \ -H "Content-Type: application/json" \ -d '{"roomNumber": "405", "lastName": "Johnson"}' ``` ## Fulfillment fees Each fulfillment method may have associated fees configured by the restaurant. These are automatically calculated and included in the cart totals: | Cart field | Description | | - | - | | `fulfillmentMethodFeeTotal` | Fulfillment fee amount in cart currency | Always render totals returned by the refreshed cart rather than recalculating fees in the client. ## Next steps > [card] [Checkout Flow](/docs/guides/checkout-flow) > > Complete the order with customer details and payment. > [card] [Accept Payments](/docs/guides/accept-payments) > > Set up Stripe for secure payment processing. # Generate a Private Integration API Key Source: https://craveup-1493c4c7.mintlify.dev/docs/guides/generate-api-key Create and protect a server-only Crave credential for admin or partner integrations. Public storefronts do not use API keys. Browser and mobile apps call `/api/v1/storefront` directly with anonymous published reads, cart capabilities, and customer JWTs. Generate an API key only for a private admin, partner, or CLI integration that runs in a trusted server environment. ## Create the key 1. Open the [Dashboard Developers page](https://dashboard.craveup.com/dashboard/developers). 2. Sign in as an organization admin for the merchant account. 3. Create a key with a clear environment and service name. 4. Select only the permissions the server integration needs. Read and write permissions are independent; selecting write does not grant read. 5. Copy the token when it is shown, verify the displayed granted permissions, and put the token in the server platform's secret manager. ```env theme={null} # Server process only. Never expose this through a public frontend prefix. CRAVEUP_API_KEY=replace_with_secret ``` Send the token only in the private `X-API-Key` request header from your trusted server process. | Permission | Allows | | - | - | | `merchant:read` / `merchant:write` | Merchant and location settings reads or changes | | `catalog:read` / `catalog:write` | Menu, product, modifier, and discount reads or changes | | `orders:read` / `orders:write` | Order reads or lifecycle changes | | `customers:read` | Customer reads and exports | | `integrations:read` / `integrations:write` | Provider/integration status reads or configuration changes | Use separate credentials for development, staging, and production. Test deployments accept only `crv_test_` keys and production accepts only `crv_live_` keys. A wrong-tier, expired, revoked, or under-scoped key fails closed. Keys created before explicit permissions were introduced may show no scopes and can no longer call private scoped routes. Create a least-privilege replacement, update the consumer through its secret manager, verify the replacement, and then revoke the old key. Rotate or revoke any key that is exposed or no longer used. Expired and revoked keys do not count toward the active-key limit. If three active keys already exist, use the fourth slot only for replacement overlap and return to no more than three after cutover. > [!WARNING] > > Never embed a private integration key in browser JavaScript, an Expo bundle, a mobile app, a > public repository, a URL, or client-visible logs. For storefront implementation, continue with the [Storefront SDK guide](/docs/getting-started/storefront-sdk) or [REST API essentials](/docs/getting-started/rest-api). # Glossary Source: https://craveup-1493c4c7.mintlify.dev/docs/guides/glossary Key terms and concepts used across the Crave platform. ## A **API key** `concept` A server-only credential for private admin or partner integrations. Public Storefront API clients do not use an API key. **Analytics event** `concept` A tracked action in the ordering funnel. Clients may fire cart-authorized `SCAN`, `CART_VIEW`, or `CHECKOUT_VIEW`; Crave records `ORDER_PLACED` server-side after authoritative order creation. See [Analytics guide](/docs/guides/analytics). ## C **Cart** `model` A temporary container holding a customer's selected items, modifiers, fulfillment method, and order timing. Created when an ordering session starts. Identified by `cartId`. Carts expire after inactivity. **Cart token** `concept` The secret `cartAccessToken` returned when starting an ordering session. Persist it with the cart ID and revision in tab-scoped browser storage or secure mobile storage, and send it only in `X-Cart-Token`. **Category** `model` A grouping of products within a menu (e.g., "Appetizers", "Mains", "Drinks"). Contains an ordered list of `productIds`. Displayed as tabs or sections in the storefront. **Clerk** `service` Authentication provider used for the Admin API and Dashboard. Clerk manages user sessions, organization memberships, and JWT tokens. Not used for storefront customer-facing flows. ## D **Delivery zone** `concept` The geographic area a location delivers to. Checked via `storefront.locations.distance()` before setting a delivery address on a cart. **Discount code** `concept` A promo code (e.g., `SAVE10`) applied to a cart for a percentage or fixed discount. Applied via `storefront.cart.applyDiscount()`, removed via `storefront.cart.removeDiscount()`. ## F **Fulfillment method** `concept` How a customer receives their order. Four options: `takeout` (counter pickup), `delivery` (address-based), `table_side` (dine-in to a table number), `room_service` (hotel room delivery). Set on the cart before checkout. See [Fulfillment Methods guide](/docs/guides/fulfillment-methods). ## G **Gratuity / Tip** `concept` An optional tip amount added during checkout. Locations configure whether tipping is enabled, suggested percentages, a default percentage, and whether custom amounts are allowed. Set via `storefront.cart.updateGratuity()`. ## L **Location** `model` A physical or virtual restaurant location within a merchant organization. Each location has its own menus, hours, fulfillment methods, and payment settings. Identified by UUID or slug. ## M **Menu** `model` A collection of categories and products for a location. Locations can have multiple menus (e.g., Lunch, Dinner, Weekend Brunch). The active menu depends on the current time and the location's schedule. **Merchant** `model` The top-level business entity. A merchant has one or more locations. Looked up by slug via `storefront.merchant.getBySlug()`. **Modifier group** `model` A set of customization options for a product (e.g., Size, Toppings, Extras). Each group has `min`/`max` selection rules. Contains modifier items. **Modifier item** `model` A single option within a modifier group (e.g., "Large", "Extra Cheese", "Bacon"). Has an optional price and max quantity. ## O **Order status** `concept` The order-submission outcome returned to a customer: `PROCESSING`, `CUSTOMER_ACTION_REQUIRED`, `PAID`, `ACCEPTED`, or `ACTION_REQUIRED`. **Ordering session** `concept` The entry point for a customer interaction. Starting a session returns the cart, its capability, and current revision. Created via `storefront.orderingSessions.start()`. ## P **Order submission** `concept` The order-first aggregate created through `storefront.checkout.submitOrder()`. An online `CUSTOMER_ACTION_REQUIRED` outcome exposes only the Stripe client fields for its immutable connected account. See [Accept Payments guide](/docs/guides/accept-payments). **Product** `model` A menu item with name, description, price, images, and optional modifier groups. Added to carts with quantity and modifier selections. ## R **Rating** `concept` A post-order experience rating (1-5 stars) with optional comment. Submitted via `storefront.ratings.submit()` while the completed cart capability is available. ## S **Sandbox mode** `concept` An isolated project environment for menus and test orders, with its own API, Business Manager and storefront URLs. Launch retains Sandbox alongside Production. Test payments do not charge real money. Selecting an environment does not change the payment mode of another installation. **Slug** `concept` A URL-safe identifier for merchants and locations (e.g., `downtown-pizza`). Used in storefront location paths as a human-readable alternative to UUIDs. **Storefront SDK** `tool` The typed TypeScript client (`@craveup/storefront-sdk`) for the Storefront API. It manages public reads, cart capabilities/revisions, customer JWTs, checkout, receipts, ratings, and loyalty. See [SDK Reference](/docs/getting-started/storefront-sdk). **Stripe Connect** `service` Stripe's platform for marketplace payments. Each restaurant connects their Stripe account to receive payouts. Crave handles the Connect setup; storefronts only need the publishable key for Stripe.js. ## W **Webhook** `concept` A signed, versioned event delivered through an HTTP POST. Outbound merchant webhooks use an immutable event ID, timestamped HMAC signature, durable retry evidence, and at-least-once semantics. They remain separate from private inbound provider callbacks. See [Outbound Webhooks](/docs/guides/webhooks). # Clover POS Source: https://craveup-1493c4c7.mintlify.dev/docs/guides/integrations/clover Understand Clover connection, merchant mapping, catalog discovery, and activation gates. > [!NOTE] > > Clover is available only for locations whose exact merchant, device, tender > matrix, scopes, webhooks, and counter-verification schedule have been > certified. An OAuth connection alone never enables pay at store. Stripe remains the only online payment rail. Clover receives fulfillment orders and supplies native in-person tender and refund evidence; Crave never renders a Clover browser tokenizer, hosted checkout, or saved-card flow. ## Activation flow **1. Authorize Clover** An organization administrator completes Clover OAuth v2. Crave stores access and refresh credentials encrypted on the server and never returns them to Business Manager. **2. Map the exact merchant** Bind one Clover merchant to one Crave location after currency, timezone, scope, and ownership checks. Connecting does not activate collection. **3. Stage and publish the catalog** Sync minimized provider resources into immutable snapshots, resolve mapping conflicts, and explicitly publish a canonical revision. Import never publishes automatically. **4. Activate order routing** Activate the reviewed POS-routed policy after catalog, generic routing, commercial, and compliance readiness pass. This still does not expose pay at store. **5. Certify native collection** On a real Clover device/Register, prove open-order visibility, card and cash tender evidence, split tender, reversal/refund behavior, signed webhook delivery, provider readback, and day-end reconciliation. Persist the proven device, environment, region, active tender-matrix revision, expiry, and timing thresholds. Any mapping, tender, device, or policy change requires recertification and hides pay at store until it passes again. ## Pay at store flow 1. Crave persists one unpaid canonical order and submits an open Clover order with a deterministic external identity. 2. Clover staff collect the real in-person payment in Clover POS. 3. Signed webhooks are durable signals, but Crave hydrates the current Clover order and payments before accepting native tender evidence. 4. Exact card, cash, gift-card, or split-tender legs append to one settlement; tips remain separate. Payment becomes `PAID` only when exact collected base amount equals the order total. 5. Refunds are admitted once against the original tender and dispatched only by the Clover refund authority that captured it. Canceling a Clover order is not refund evidence. While evidence is unresolved, Business Manager shows the certified canonical-refresh, fallback-read, warning, and action-required thresholds and **Verifying payment — do not charge again**. Reconciliation reuses the same collection identity and never silently falls back to Stripe. ## Safety and commercial boundaries * Browser checkout is always Stripe. Pay at store never accepts a Stripe saved payment method or card data in the storefront. * Provider-recorded cash is preferred. A manual cash fallback is available only under an explicitly certified policy, exact amount, narrow permission, staff identity, reason, and immutable audit. * Crave subscription is the launch revenue base. Pay at store does not take a transaction split from the Clover tender. * Prepared-but-uncollected and no-show loss remains merchant risk under the configured identity, per-order, active-count, active-value, and aging limits. ## Availability Production activation remains closed until real-device and provider-backed certification evidence is recorded for the exact location. Contact [hello@craveup.com](mailto:hello@craveup.com) for sandbox pilot requirements. # Square POS-native commerce setup Source: https://craveup-1493c4c7.mintlify.dev/docs/guides/integrations/square Connect Square for provider-native catalog, order, payment-evidence, and reconciliation operations. Square is a POS-native integration. It supplies provider catalog and inventory inputs and can own certified order projection, fulfillment, in-person tender, refund, and reconciliation behavior, but it never becomes a browser payment processor. Crave's organization-owned catalog and typed location overlays stay authoritative for storefront pricing, availability, and schedules. Stripe is the only online processor. For `PAY_AT_STORE`, Square is the settlement adapter and provider-recorded cash is preferred; a certified audited-cash fallback remains merchant authority, not a second adapter. ## Activation flow **1. Connect Square via OAuth** Authorize the requested merchant, customer, catalog, order, payment, refund, card, gift-card, inventory, location, and loyalty scopes. **2. Map one Square location** Bind the Crave location to the exact Square location after currency, timezone, and capability checks. **3. Import, review, and publish the canonical catalog** Stage Square objects against stable Crave identities, resolve mapping conflicts, apply target-location price and availability overlays, and publish a fresh reviewed snapshot. Import and reconciliation never publish automatically or overwrite unrelated location overlays. **4. Activate routing, then certify provider-native readiness** Activate the reviewed POS-routed policy first; this still does not expose pay at store. Pair the exact Terminal with a Devices API pairing code, prove order visibility, native tender, refund, webhook, and reconciliation behavior, then certify the same active policy revision. Delivery additionally requires explicit Square Delivery certification and DoorDash Drive credentials. ## Pay at store flow 1. Crave persists one unpaid canonical order and routes its immutable fulfillment identity to Square. 2. Staff starts collection from Crave Orders Manager on the exact certified, mapped Square Terminal. A Square POS app running only on a phone is not a substitute for a certified Terminal device. 3. Square records the native tender. Signed webhooks and provider readback append immutable tender evidence to the existing Crave settlement. 4. Crave marks payment `PAID` only after exact amount, currency, account, location, order, and tender evidence match. Fulfillment may progress while payment is still `DUE`. If payment evidence is delayed, the operator sees the certified refresh, fallback-read, warning, and action-required thresholds plus **Verifying payment — do not charge again**. Reconciliation retains the same collection identity; it never starts another charge. ## Authority rules * Online checkout always uses the order-first Stripe flow. The storefront does not load Square Web Payments, tokenize Square cards, or create Square checkout sessions. * Square payment and tender identifiers enter Crave only as provider-native order or webhook evidence bound to the exact tenant, connection, location, and order. * Square constructs its provider order from mapped catalog variations, taxes, discounts, service charges, and an optional order-linked Loyalty reward. The resulting provider total must reconcile to Crave's accepted immutable quote; Square never rewrites the canonical catalog or customer-facing total. * Staff tip is recorded on the final Square Payment. DoorDash courier tip and the authoritative Drive fee plus tax are Square Order service charges. * Provider-native split tenders and gift-card evidence remain server-side reconciliation inputs. The storefront cannot create or fund them. * All refunds are admitted through the canonical `Refund`, `RefundAllocation`, and `RefundDispatchOperation` owner before a later provider adapter performs a write. * A refund of the payment that purchased a gift card triggers an idempotent Square `ADJUST_DECREMENT` activity with reason `PURCHASE_WAS_REFUNDED`, because refunding that funding payment does not reverse the loaded gift-card balance. * Square Loyalty replaces LIP for Square-authoritative locations. Enrollment, reward preview, issue, redemption, point accrual, and webhook projection use the Square customer and Loyalty account. * Provider-native loyalty evidence is reconciled independently from Stripe online payment collection; no loyalty action changes the browser processor. * Enrollment requires a phone that is currently verified on the active Clerk session. If the customer has no verified phone, direct them to the Clerk-managed profile or reverification flow, obtain a fresh `crave-customer` token, and retry enrollment. An E.164-shaped profile value or historical Crave timestamp alone is not accepted as proof. Clerk phone verification does not accept Square marketing text terms. * Customer loyalty history is location-scoped at `GET /customer/locations/{locationId}/loyalty/ledger`. A Square-authoritative location reads the current balance with `RetrieveLoyaltyAccount` and the reverse-chronological activity ledger with `SearchLoyaltyEvents` (up to 30 entries per page). It never falls back to LIP when Square is connected. The retained location binding keeps that exclusion in force if Square credentials or runtime health degrade, so Crave cannot mutate a second loyalty ledger through quote, cart, completion, cancellation, refund, or durable retry hooks. A queued LIP mutation rechecks the task location before delivery and terminates without a provider call after Square takes authority. Legacy tasks without location authority fail closed as well. * When an administrator approves a customer loyalty claim, Crave resolves the claim order's location before choosing the provider. A Square-authoritative order writes the approved correction through Square `AdjustLoyaltyPoints` with a stable provider idempotency key and retains the returned Square event ID. Provider errors leave the claim retryable; Crave never posts that adjustment to LIP. Orders at locations without Square authority continue to use the configured LIP program. * Completed Square orders accrue Loyalty points with an order-scoped provider idempotency key. A failed or ambiguous accrual is retained as a durable `LOYALTY_EFFECT` operation; the worker re-proves the completed Square tenders, current tenant and location binding, and returned Loyalty events before it marks the cart projection complete. * Vendor confirmation, ready-for-pickup, and completion actions update the exact Square fulfillment before Crave commits the matching local state. Each update uses the current Square order version, fulfillment UID, and a stable idempotency key. Square-originated fulfillment webhooks apply locally without echoing the same transition back to Square. * Crave subscription is the launch revenue base. Pay at store does not take a transaction split from the Square tender, and prepared-but-uncollected or no-show loss remains merchant risk under configured identity and exposure limits. ## Delivery with DoorDash Drive Delivery is fail-closed until the location has fresh capability evidence whose source is `square_live_pos_delivery_certification`, a selected `DOORDASH_DRIVE` provider, and valid Drive credentials. Crave requests a five-minute Drive quote, fingerprints its address and cart inputs, adds `fee + tax` and courier tip to the Square Order, pays that exact order, then accepts the same Drive quote. Definite dispatch rejection triggers idempotent Square refund compensation. An ambiguous timeout is reconciled using the same external delivery ID and is never auto-refunded while a courier job might exist. DoorDash webhooks update Crave tracking and the Square delivery fulfillment. Active deliveries are also retrieved every 60 seconds when their last reconciliation is more than two minutes old, so a missing webhook does not strand tracking state. Order cancellation reaches a conclusive DoorDash cancel state before Square refund processing begins. ## Webhooks Create the Square subscription against: ```text theme={null} https:///api/v1/webhooks/square ``` Subscribe to the exact events handled by this release: ```text theme={null} catalog.version.updated inventory.count.updated location.created location.updated order.created order.updated order.fulfillment.updated payment.created payment.updated terminal.checkout.created terminal.checkout.updated refund.created refund.updated customer.created customer.updated customer.deleted card.created card.updated card.disabled card.forgotten card.automatically_updated loyalty.account.created loyalty.account.updated loyalty.account.deleted loyalty.event.created loyalty.program.created loyalty.program.updated loyalty.promotion.created loyalty.promotion.updated gift_card.created gift_card.updated gift_card.customer_linked gift_card.customer_unlinked gift_card.activity.created gift_card.activity.updated oauth.authorization.revoked ``` Set `SQUARE_WEBHOOK_SIGNATURE_KEY` only in the sandbox secret manager. Never paste it into tickets, chat, source control, or browser configuration. Crave verifies Square's signature over the untouched body and exact notification URL, then acknowledges only after durable inbox storage. For DoorDash Drive, register: ```text theme={null} https:///api/v1/webhooks/doordash ``` Configure the same Basic or OAuth `Authorization` value in DoorDash and the `DOORDASH_WEBHOOK_AUTHORIZATION` sandbox secret. Crave compares the exact value in constant time, durably stores the event, serializes delivery projections, and retries failures. ## Health and recovery The Square integration page shows authorization and mapping status, capability readiness, last reconciliation, last webhook receipt, and pending or failed events. Use **Reconcile** to refresh locations, catalog, inventory, orders, payments, refunds, customers, cards, Loyalty programs, promotions, accounts, events and rewards, plus gift cards and their location activity. Gift-card account numbers are redacted before reconciliation evidence is stored. Use **Retry events** after repairing a dependency. A webhook HTTP success means the event was stored; projection occurs asynchronously and remains observable. The runtime also enqueues one tenant-scoped full completeness sweep for every mapped Square location in each UTC day. The durable operation pins the exact organization, connection, and binding, runs the same canonical path as the operator action, and records the successful system reconciliation in the health timeline. Provider or network failures use bounded exponential retry; an expired read-only lease is safe to replay, while changed binding evidence fails closed for operator review. Faster catalog, webhook, payment/refund, checkout-abandonment, Loyalty, and DoorDash workers continue to repair their own nonterminal domains between full sweeps. ## Admin endpoints | Method | Path | Purpose | | - | - | - | | `POST` | `/locations/:id/integrations/square/oauth` | Start OAuth | | `GET` | `/locations/:id/integrations/square` | Status, health, capabilities | | `GET` | `/locations/:id/integrations/square/locations` | List Square locations | | `POST` | `/locations/:id/integrations/square/locations` | Preview and confirm mapping | | `POST` | `/locations/:id/integrations/square/catalog/import` | Import the catalog | | `POST` | `/locations/:id/integrations/square/reconcile` | Run full reconciliation | | `POST` | `/locations/:id/integrations/square/events/retry` | Retry failed webhook events | | `DELETE` | `/locations/:id/integrations/square` | Disconnect after deactivation | Disconnecting preserves canonical catalog and historical evidence. Active or degraded commerce modules must be deactivated or rolled back first. ### Confirm a location mapping Use the existing location-binding POST endpoint with `squareLocationId` and `preview: true` first. Show the returned Crave location, Square location, account and blocker reasons to the merchant. After confirmation, POST the same `squareLocationId` with the returned `confirmation` object (`connectionId`, `bindingId`, `revisionToken`). A changed connection, mapping, policy or displayed location requires a new preview. Direct saves without confirmation are rejected. Mapping preparation does not establish menu-sync or routing activation readiness. # Stripe Payments Source: https://craveup-1493c4c7.mintlify.dev/docs/guides/integrations/stripe Understand Crave's per-location Stripe setup and direct-charge storefront flow. Crave's online-payment design uses one Stripe connected account per Crave location. Direct charges and Stripe processing costs belong to that location's Stripe account. Stripe automatically pays out available funds to its confirmed bank account. Crave orchestrates checkout and receives a separate application fee. > [!NOTE] > > Online payments require a verified Stripe account and confirmed bank for each > location. Stripe schedules payouts automatically; merchants do not need Crave > to release each payout. Ordinary orders and catering payments use the same > location readiness checks. Stripe determines country, currency, capability, > settlement timing, and bank availability for each account. ## Separate managed Cloud hosting product The separately deployed managed Cloud hosting product uses a merchant-owned Stripe account. It charges a hosting subscription and takes no order application fee. Its included storefront uses its own pinned runtime; those commercial terms and compatibility observations do not activate the direct-charge platform source candidate described here. See the [Cloud release results](/docs/guides/crave-cloud-overview#developer-package-compatibility) before choosing a client or enabling payments for a Cloud installation. ## Environment model Sandbox and production are separate deployments with separate databases, Clerk applications, Stripe credentials, connected accounts, and API-key namespaces. There is no merchant test/live toggle inside one Crave organization. | Environment | Business Manager | Storefront API | API key prefix | Stripe key family | | - | - | - | - | - | | Sandbox | `https://sandbox.dashboard.craveup.com` | `https://sandbox-api.craveup.com/api/v1/storefront` | `crv_test_...` | `pk_test_...` | | Production | `https://dashboard.craveup.com` | `https://api.craveup.com/api/v1/storefront` | `crv_live_...` | `pk_live_...` | Create and verify the organization and every location independently in the environment you intend to use. Never send a sandbox credential to production or a production credential to sandbox. Each deployment also uses its own Clerk application, so signing in to one environment does not create a session or organization in the other. ## Location payment-account flow Creating an organization or location does not automatically create a Stripe account. An organization administrator starts setup explicitly for each location: **1. Choose the location** In Business Manager, switch to the intended location and open **Settings > Account**. Confirm that the location name and address are correct before starting payment setup. **2. Confirm the payment-account contact** Enter and confirm the email that owns this location's Stripe payment setup. Crave stores this contact with the location payment account; it does not reuse an order-notification email silently. **3. Complete Stripe-hosted onboarding** Continue to Stripe's one-time hosted onboarding flow. Supply the legal, identity, tax, and bank information Stripe requests. A second location may be offered eligible information reuse, but every location must satisfy the requirements Stripe returns for its own account. **4. Resolve requirements in Business Manager** Return to **Settings > Account** for status, notifications, documents, and required account-management actions. Crave does not depend on a separate provider-hosted merchant dashboard for this flow. **5. Confirm the payout destination** An organization administrator confirms the exact current external account. A bank-account change invalidates the prior confirmation and blocks payment and payout readiness until the new destination is confirmed. Stripe readiness is per location. An incomplete second location must not block a different location that has completed its own requirements. A pay-at-store-only location can remain without a Stripe payment account. ## Storefront payment flow The storefront uses a capability-protected Crave cart. Crave selects the location account and creates the PaymentIntent as a direct charge in that account; the browser cannot choose or replace the account. 1. Submit the canonical order with the authorized cart revision and accepted evidence. 2. Read the server-selected `connectedAccountId` and `clientSecret` from a `CUSTOMER_ACTION_REQUIRED` outcome. 3. Initialize Stripe.js with the publishable key for the current deployment and the exact connected account returned by Crave. 4. Confirm through Stripe Elements. Crave finalizes payment and the order only from authoritative Stripe event or reconciliation evidence. ```tsx filename="app/checkout/page.tsx" theme={null} import { loadStripe } from "@stripe/stripe-js"; import { Elements } from "@stripe/react-stripe-js"; const outcome = await storefront.checkout.submitOrder( locationId, cartId, { acceptedCatalogEvidence, acceptedDiscountEvidence, collectionMode: "ONLINE", customerConfirmationRevision, quoteFingerprint, }, { idempotencyKey, revision: cart.revision }, ); if (outcome.status !== "CUSTOMER_ACTION_REQUIRED") return; // connectedAccountId is server-selected and must remain unchanged for // confirmation, redirect recovery, and payment-status lookup. const stripe = loadStripe(process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY!, { stripeAccount: outcome.connectedAccountId, }); ; ``` Only the Stripe publishable key belongs in browser configuration. Stripe secret keys, connected-account credentials, private Crave API keys, saved payment credentials, and webhook secrets remain server-side. For the complete checkout contract, continue to the [Accept Payments guide](/docs/guides/accept-payments). ## Sandbox verification Until the activation lock is removed, a payment-session request must return the documented activation failure rather than creating a charge. That failure is the correct sandbox result; do not bypass it or substitute a platform-only payment. After activation, verify the exact release with the sandbox Business Manager, sandbox Storefront API, and `pk_test_...` publishable key. Cover: * successful card payment; * authentication-required payment and browser recovery; * declined payment; * full and partial refund evidence; * application-fee refund evidence; * dispute evidence and response access; * payout-destination change and readiness invalidation; and * a second location with independent onboarding and payment-account ownership. Use Stripe test cards only in the sandbox deployment. Never use test card data in production. ## Troubleshooting ### "Online payments are not activated" The release-wide direct-charge gate is still closed. Continue testing catalog, cart, pay-at-store, and other non-Stripe behavior; do not retry through another Stripe account or weaken the gate. ### "Payment account needs attention" * Select the exact affected location in Business Manager. * Open **Settings > Account** and continue the Stripe-hosted or embedded action shown there. * Confirm that all required capabilities and documents are complete. * Reconfirm the current payout destination after any external-account change. ### Account or environment mismatch * Confirm the storefront is calling the intended sandbox or production API. * Confirm the publishable key belongs to that same environment. * Discard the payment session and start again when the returned connected account does not match the current location; never override it in the browser. # Toast POS Source: https://craveup-1493c4c7.mintlify.dev/docs/guides/integrations/toast Connect Toast for catalog staging, fulfillment, and certified POS-native pay at store. > [!NOTE] > > Toast production activation remains fail-closed until the exact restaurant, > scopes, dining options, alternate payment type, POS/KDS behavior, webhooks, > refunds, and native tender evidence pass provider-backed certification. Stripe is the only online payment rail. Toast receives fulfillment orders and supplies native in-person tender and refund evidence; it never processes a storefront browser payment. ## Activation flow **1. Add Crave in Toast Web** Open Toast Partner Integrations and add Crave. Business Manager shows the exact organization **Group ID** and location **Location ID** to enter. Crave does not ask a merchant to paste Toast secrets into the browser. **2. Sync the restaurant connection** Return to Business Manager and sync. Crave accepts only the Toast restaurant whose external group and restaurant references exactly match the selected organization and location. **3. Map Toast order behavior** Select only Toast-returned identifiers: one alternate payment type, a pickup dining option, and an optional delivery dining option. Crave stores an immutable configuration revision; it never guesses GUIDs. **4. Stage the provider catalog** Retrieve the current Toast menus, categories, products, and modifiers into an immutable provider snapshot for canonical mapping review. Staging never publishes automatically. **5. Activate order routing, then certify pay at store** Activate the reviewed POS-routed policy first; this does not expose pay at store. Then prove the open check appears on the intended POS/KDS, staff can collect supported tenders, signed webhooks arrive, provider readback reconciles exact payment/refund evidence, and the certified timing schedule holds. Certify only the same active policy revision. ## Pay at store flow 1. Crave persists one unpaid canonical order and creates one deterministic open Toast check using the configured dining option and **no payment**. The alternate payment type is used only to represent an already-collected Stripe payment on online orders. 2. Staff collect the actual card, cash, gift-card, or split tender in Toast POS. Crave does not route or charge money through a Toast browser flow. 3. Toast webhooks trigger hydration of the current order and payments. Crave accepts native tender evidence only when tenant, restaurant, order, amount, currency, and provider identities match. 4. The canonical settlement becomes `PAID` only after exact verified evidence; fulfillment may progress while payment remains `DUE`. 5. Refunds follow the original Toast tender authority. Canceling or voiding the fulfillment order alone never proves a refund. While evidence is unresolved, show **Verifying payment — do not charge again** and keep the same collection identity. Business Manager exposes the certified canonical-refresh, fallback-read, warning, and action-required thresholds. ## Safety and commercial boundaries * Browser checkout always uses Stripe. Toast credentials, webhook secrets, tender identifiers, and provider payloads stay on Crave-managed services. * Crave subscription is the launch revenue base. Pay at store does not create a Crave transaction split from the Toast tender. * Prepared-but-uncollected and no-show loss remains merchant risk under the configured identity and order-exposure limits. * Production stays disabled until real partner credentials, scopes, device behavior, webhooks, payment evidence, and refund evidence are certified for the exact restaurant. Contact [hello@craveup.com](mailto:hello@craveup.com) for sandbox pilot and provider-certification access. # Manage Cart Source: https://craveup-1493c4c7.mintlify.dev/docs/guides/manage-cart Create and mutate a cart with capability, revision, and idempotency protection. Every cart has three values that belong together: `cart.id`, the secret `cartAccessToken`, and the current `cart.revision`. The SDK persists them through the `sessionStore` you provide. ## Start a session ```ts theme={null} const session = await storefront.orderingSessions.start("loc_123", { marketplaceId: "web", fulfillmentMethod: "takeout", }); const cartId = session.cart.id; ``` ```bash theme={null} curl -X POST "https://api.craveup.com/api/v1/storefront/locations/loc_123/ordering-sessions" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: start_01" \ -d '{"marketplaceId":"web","fulfillmentMethod":"takeout"}' ``` `marketplaceId` is optional source attribution, such as `"web"` or `"mobile"`; it is not a location ID. The route already supplies the location scope. Store the response capability in `sessionStorage` for browsers or secure device storage for mobile. Do not use a URL, cookie shared across origins, analytics property, or application log. ## Add an item ```ts theme={null} const cart = await storefront.cart.addItem("loc_123", cartId, { productId: "prod_burger", quantity: 1, itemUnavailableAction: "remove_item", selections: [ { groupId: "mod_size", selectedOptions: [{ optionId: "opt_large", quantity: 1 }], }, ], }); ``` ```bash theme={null} curl -X POST "https://api.craveup.com/api/v1/storefront/locations/loc_123/carts/cart_456/items" \ -H "Content-Type: application/json" \ -H "X-Cart-Token: $CART_ACCESS_TOKEN" \ -H 'If-Match: "cart-0"' \ -H "Idempotency-Key: add_item_01" \ -d '{"productId":"prod_burger","quantity":1,"selections":[],"itemUnavailableAction":"remove_item"}' ``` ## Read and mutate the cart ```ts theme={null} const current = await storefront.cart.get("loc_123", cartId); await storefront.cart.updateItemQuantity("loc_123", cartId, "item_abc", 2); await storefront.cart.removeItem("loc_123", cartId, "item_abc"); await storefront.cart.applyDiscount("loc_123", cartId, "SAVE10", { includeCustomerContext: true, }); await storefront.cart.removeDiscount("loc_123", cartId); ``` The SDK sends the capability automatically. For raw REST calls, send `X-Cart-Token` on every cart read and write. Send `If-Match` and a stable `Idempotency-Key` on every mutation. Pass `includeCustomerContext: true` only when a signed-in shopper still has a guest-capability cart and discount validation needs customer context. Omit it for a guest; a claimed cart uses the customer JWT automatically. ## Handle conflicts safely The API returns `CART_CONFLICT` when `If-Match` is stale. The SDK refreshes the stored revision but deliberately does not repeat the failed mutation. Replace the UI cart with the fresh server state, explain the change, and require the user to retry. ## End the capability lifecycle `cart.delete()` clears the SDK session. `cart.claim()` removes the guest capability while retaining the authoritative revision for customer-authenticated access. After order submission reaches `PAID`, `ACCEPTED`, or `ACTION_REQUIRED`, clear the persisted capability once terminal handling such as a same-page rating is finished. > [card] [Checkout Flow](/docs/guides/checkout-flow) > > Protect order submission and outcome recovery. > [card] [Error Codes](/docs/guides/error-codes) > > Handle authorization and concurrency failures. # Developer Package and Crave Cloud Source: https://craveup-1493c4c7.mintlify.dev/docs/guides/open-source-and-cloud How Crave's developer-facing package fits into the managed Crave Cloud platform. Crave pairs a documented developer surface with a managed cloud product: the integration contract is explicit, while production franchise operations remain in a managed control plane. The Storefront SDK is publicly downloadable from npm but is marked `UNLICENSED`. Its canonical source repository is private, and npm availability or public documentation does not grant permission to copy, modify, or redistribute the package. Contact [hello@craveup.com](mailto:hello@craveup.com) for licensing questions. Crave Cloud is where brands coordinate real locations, roles, integrations, payment routing, customer identity, loyalty, and operational readiness. ## How to think about it | Layer | Use it for | Operational owner | | - | - | - | | **Crave.js packages** | Downloadable Storefront SDK, CLI, examples, components, and local developer workflows under their published licenses | Your engineering team | | **Storefront API** | Customer-facing ordering flows across web, mobile, kiosk, and custom channels | Shared between your app and Crave | | **Crave Cloud** | Business Manager, locations, roles, identity boundaries, integrations, payment routing, observability, and readiness | Crave-managed cloud | | **Bring-your-own systems** | Existing loyalty, ordering, identity, or payment systems that a brand wants to keep | Joint integration ownership | ## Managed cloud is the production default Production restaurant franchise infrastructure is not just a package install. It needs secure roles, location readiness, integration monitoring, audit trails, payment routing, and support for operational edge cases across many stores. Use Crave Cloud when you need: * multiple locations, franchisees, or business entities * staff roles and Business Manager access * payment routing between corporate, franchisee, or location accounts * monitored integrations with ordering, loyalty, payments, or identity providers * supportable production operations ## Public developer surface Use the Crave.js developer surface when you need: * a local storefront you can run and customize * typed SDK calls for menus, carts, checkout, payments, and analytics * React components that can live inside your application * REST examples for non-TypeScript clients * clear contracts for current Storefront API behavior and integration readiness > [card] [Build with Crave.js](/docs/getting-started/introduction) > > Start with the CLI, SDK, API, and UI components. > [card] [Understand Crave Cloud](/docs/guides/crave-cloud-overview) > > See how storefronts connect to identity, ordering, loyalty, payments, and > operations. ## What is not self-hosted The documented Crave.js developer surface does not make the SDK package or every part of Crave Cloud open source or self-hostable. Business Manager, production identity boundaries, managed loyalty, payment routing, integration health, and franchise operations are managed platform capabilities unless your Crave agreement says otherwise. This keeps the developer experience flexible without pushing the operational burden of a franchise platform onto every storefront team. # Order Tracking Source: https://craveup-1493c4c7.mintlify.dev/docs/guides/order-tracking Recover an authoritative order-submission outcome and display a protected receipt. After Stripe redirects back to the storefront, recover the cart session and the original submission attempt ID from tab-scoped storage. Poll that attempt rather than creating another order. ## Outcome states | Status | Meaning | | - | - | | `PROCESSING` | Stripe or durable projection recovery is still in progress | | `CUSTOMER_ACTION_REQUIRED` | The same Stripe attempt still requires customer action | | `PAID` | Stripe capture and canonical order settlement are complete | | `ACCEPTED` | A pay-at-store order was accepted under audited cash authority | | `ACTION_REQUIRED` | The attempt needs an explicit recovery action and must not be replayed | ```ts theme={null} async function waitForOrder( locationId: string, cartId: string, attemptId: string, ) { for (let poll = 0; poll < 40; poll += 1) { const result = await storefront.checkout.getOrderSubmissionOutcome( locationId, cartId, attemptId, ); if (result.status !== "PROCESSING") return result; await new Promise((resolve) => setTimeout(resolve, Math.min(1000 + poll * 250, 3000)), ); } throw new Error("Order confirmation is taking longer than expected."); } ``` Do not treat a redirect, cart lock, timeout, provider response, or paid settlement projection as success by itself. The order-first attempt must report its authoritative outcome. Keep the capability until terminal handling finishes, then clear it from persisted storage. ## Receipt links Guest receipt links place a receipt capability in the URL fragment so browsers do not send it to servers as part of the request URL. Capture it in the browser, immediately remove it with `history.replaceState`, store it in versioned, tab-scoped `sessionStorage` keyed by API environment, merchant, and receipt ID, and send it as `X-Receipt-Token`: ```ts theme={null} const order = await storefront.receipts.get(receiptId, { receiptToken }); ``` A signed-in customer can access their own order through the customer JWT instead. Receipt identifiers alone never authorize access. ## Ratings Submit a rating while the completed cart capability is still available in memory: ```ts theme={null} await storefront.ratings.submit(locationId, cartId, { rating: 5, comment: "Great food and fast service.", }); ``` > [card] [Error Codes](/docs/guides/error-codes) > > Handle terminal and retryable failures. > [card] [SDK Reference](/docs/getting-started/storefront-sdk) > > Review all checkout and receipt methods. # Organization discounts Source: https://craveup-1493c4c7.mintlify.dev/docs/guides/organization-discounts Create one promotion for an organization and target all or selected locations safely. Crave promotions belong to one organization. A definition can apply to every active location or an explicit location set, while product and category rules use canonical organization catalog IDs. Location pricing, availability, publication revision, and timezone are resolved again when the cart is evaluated and immediately before payment. ## Authentication and scopes Private management calls use an authenticated Business Manager session or a server-only `X-API-Key`. API-key reads require `catalog:read`; API-key creates, updates, and archives require `catalog:write`. Business Manager mutations require an organization administrator. A location-limited key cannot create an all-location definition, target a location outside its grants, or read/mutate a definition whose complete selected-location set is not contained by those grants. Storefront cart calls use the cart capability and `Idempotency-Key`, never a private API key. ## Create a definition Call `POST /api/v1/discounts`. Codes are trimmed and normalized to uppercase, and are unique within the organization. Use `locationScope: "all"` with an empty `locationIds` array, or `locationScope: "selected"` with at least one organization-owned location ID. ```json theme={null} { "code": "LUNCH10", "description": "Weekday lunch promotion", "state": "active", "locationScope": "selected", "locationIds": ["11111111-1111-4111-8111-111111111111"], "currency": "USD", "value": { "type": "percentage", "basisPoints": 1000, "maximumAmountMinor": 1500 }, "target": { "type": "categories", "ids": ["22222222-2222-4222-8222-222222222222"] }, "application": "each_eligible_item", "minimumSubtotalMinor": 2000, "totalLimit": 500, "perCustomerLimit": 1, "weeklySchedule": [ { "dayOfWeek": 1, "startsAt": "11:00", "endsAt": "14:00" }, { "dayOfWeek": 2, "startsAt": "11:00", "endsAt": "14:00" } ] } ``` Money uses integer minor units and percentages use basis points (`1000` = 10%). Weekly windows use the location timezone and half-open intervals: the start is included and the end is excluded. `dayOfWeek` is `0` for Sunday through `6` for Saturday. A per-customer limit requires a verified organization customer; guests fail closed for that code. Use `GET /api/v1/discounts/catalog-targets` to discover active canonical products and categories and the locations where each target is currently published. ## Preview, update, and archive * `GET /api/v1/discounts` lists definitions with organization and per-location ledger metrics. * `GET /api/v1/discounts/{discountId}` reads one definition. * `POST /api/v1/discounts/{discountId}/preview` evaluates supplied cart lines without reserving or consuming usage. * `PUT /api/v1/discounts/{discountId}` requires the current positive `revision` in the request body. * `DELETE /api/v1/discounts/{discountId}` archives the definition and requires `{ "revision": N }`. Disabling or archiving an active definition with reserved or committed usage fails closed unless the request also includes `"confirmActiveUsage": true`. Business Manager asks for this confirmation and then sends the same explicit API evidence; integrations must do likewise. A stale revision or normalized duplicate returns a conflict. Foreign locations and targets are not disclosed. Archiving prevents new evaluation but does not rewrite historical order or redemption evidence. ## Storefront use Apply a code with `POST /api/v1/storefront/locations/{locationId}/carts/{cartId}/discount` and `{ "code": "LUNCH10" }`. Remove it with the corresponding `DELETE`. Both mutations require the cart capability, an `Idempotency-Key`, and the current cart precondition used by the Storefront contract. Crave supports one public promotion or one loyalty reward on a cart, not both. Applying a public code while loyalty is reserved fails without silently releasing the reward. The response is the authoritative cart, including the exact adjustment and current revision. At payment creation Crave evaluates the definition again, reserves capacity atomically, and stores the definition, cart, and catalog revisions. Payment cancellation releases the reservation; order materialization commits it; a full provider-confirmed refund reverses it. Partial refunds retain the usage and record cumulative proportional evidence. > [!WARNING] > > Do not calculate discount eligibility or usage limits in a client. Never retry > checkout with a new idempotency key after an ambiguous response; read the cart > or order and reconcile the canonical state first. # Testing Source: https://craveup-1493c4c7.mintlify.dev/docs/guides/testing Test storefront capability, concurrency, checkout, and secret-handling behavior. > [!WARNING] > > Managed Cloud installations use their own pinned runtime contract. Managed > Cloud installations can run a different, pinned checkout contract; an npm tag > alone does not establish compatibility. Confirm the SDK/API pair for your > installation before using payment-session or customer-auth methods. The hosted > storefront and checkout use their bundled client. See [release > compatibility](/docs/guides/crave-cloud-overview#developer-package-compatibility). Select **Sandbox** in your Console project and copy that installation's API origin. Launch keeps Sandbox available for testing; you do not need a second hosting subscription. Its menu, orders and customers remain separate from Production. Use test payment configuration for local and CI runs: ```env theme={null} NEXT_PUBLIC_CRAVEUP_API_URL=https://sandbox-api.craveup.com NEXT_PUBLIC_CRAVEUP_LOCATION_ID=loc_test NEXT_PUBLIC_CRAVEUP_MERCHANT_SLUG=test-cafe NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_test_xxx ``` ## Unit tests Test the caller-owned session adapter independently: * versioned `sessionStorage` keys include the canonical API environment, merchant, and location; * the cart capability and customer JWT never enter URLs, analytics, or `localStorage`; * ETag revisions are retained; * claim, delete, expiry, and terminal checkout handling clear persisted capability state; * malformed or old-version records fail closed. Mock `fetch` when testing the SDK: ```ts theme={null} const fetchMock = vi.fn( async () => new Response(JSON.stringify(cart), { status: 200, headers: { "Content-Type": "application/json", ETag: '"cart-4"' }, }), ); const storefront = createStorefrontClient({ baseUrl: "https://api.example.test", fetch: fetchMock, sessionStore, }); ``` Assert cart calls send the capability, current `If-Match`, and an idempotency key. For `CART_CONFLICT`, assert the mutation is not replayed automatically and the current cart revision is refreshed. ## Checkout tests Cover every authoritative result: * `PROCESSING` continues bounded polling; * `CUSTOMER_ACTION_REQUIRED` renders only the returned Stripe action; * `PAID` renders the stable order identity and clears persisted cart state after terminal handling; * `ACCEPTED` renders the audited pay-at-store order without claiming online settlement; * `ACTION_REQUIRED` renders the exact recovery action and never falls back to success; * authorization, timeout, and stale-revision errors remain visible. ## Receipt tests Start with a URL containing `#receiptToken=...`. Assert the app calls `history.replaceState` immediately, stores the token only for that API environment, merchant, and receipt ID in `sessionStorage`, and sends it in the receipt header—not in the request URL. ## End-to-end sandbox flow 1. Fetch published merchant, location, menu, product, distance, order-time, and gratuity data anonymously and verify no customer JWT is attached. 2. Create a cart and verify the capability is returned only once for a new cart. 3. Mutate the cart and verify revision changes. 4. Submit the canonical order and handle its Stripe customer action or activation-lock error. 5. Observe nonterminal polling followed by exactly one terminal result. 6. Verify rating and receipt access. 7. Confirm no secret or capability appears in browser URLs, logs, analytics, or static assets. Run the same build artifact you intend to promote. ## Outbound webhook tests Create an endpoint in the sandbox Business Manager and use **Send test**. Test events have `"test": true` in the exact body and `Crave-Webhook-Test: true`; they are never real orders. Your receiver test suite should prove that it: * verifies the timestamped `Crave-Webhook-Signature` against raw bytes before parsing JSON; * rejects tampered bodies and timestamps outside the 300-second replay window; * accepts either valid signature during bounded secret rotation; * commits each `Crave-Webhook-Id` only once and returns `2xx` for duplicates; * returns quickly, then processes asynchronously; * looks up current Crave state after an ambiguous timeout instead of blindly resubmitting; * keeps secrets, signatures, customer data, and full response bodies out of logs. Use Business Manager's delivery timeline to inspect attempts. A manual redelivery must retain the same event ID and exact body; it tests idempotency, not a new business transition. # Theming Source: https://craveup-1493c4c7.mintlify.dev/docs/guides/theming Customize your storefront's colors, fonts, and component styles. Crave storefront templates are built with [Tailwind CSS](https://tailwindcss.com) and [shadcn/ui](https://ui.shadcn.com). You customize the look by editing CSS variables and Tailwind config — no proprietary theming API to learn. ## How theming works Every template ships with a `globals.css` file that defines CSS custom properties. Tailwind maps these variables to utility classes, and all Crave components use those classes. Change a variable, and every component updates. ```css filename="src/app/globals.css" theme={null} @layer base { :root { --background: 0 0% 100%; --foreground: 240 10% 3.9%; --primary: 160 50% 22%; /* your brand color */ --primary-foreground: 0 0% 98%; --accent: 160 30% 96%; --radius: 0.5rem; } .dark { --background: 240 10% 3.9%; --foreground: 0 0% 98%; --primary: 160 50% 40%; --primary-foreground: 0 0% 98%; } } ``` ## Change brand colors Update the `--primary` variable to match your brand. Use HSL values (hue, saturation, lightness): ```css filename="src/app/globals.css" theme={null} :root { --primary: 210 100% 50%; /* blue brand */ --primary-foreground: 0 0% 100%; /* white text on primary */ } ``` All buttons, links, active states, and accent elements update automatically. > [!TIP] > > Use the [shadcn/ui theme generator](https://ui.shadcn.com/themes) to preview color combinations and copy the CSS variables. ## Customize fonts Templates use `next/font` for self-hosted fonts with zero layout shift. Update the font in `layout.tsx`: ```tsx filename="src/app/layout.tsx" theme={null} import { Inter } from 'next/font/google'; // or use a local font: // import localFont from 'next/font/local'; const font = Inter({ subsets: ['latin'] }); export default function RootLayout({ children }: { children: React.ReactNode }) { return ( {children} ); } ``` For local font files (`.woff`, `.woff2`): ```tsx filename="src/app/layout.tsx" theme={null} import localFont from 'next/font/local'; const brandFont = localFont({ src: './fonts/BrandFont-Regular.woff2', variable: '--font-brand', }); export default function RootLayout({ children }: { children: React.ReactNode }) { return ( {children} ); } ``` Then reference the variable in your Tailwind config: ```ts filename="tailwind.config.ts" theme={null} export default { theme: { extend: { fontFamily: { sans: ['var(--font-brand)', 'system-ui', 'sans-serif'], }, }, }, }; ``` ## Customize component styles Crave components use Tailwind utility classes with shadcn/ui's `cn()` helper. Override styles by passing `className`: ```tsx theme={null} ``` For deeper customization, edit the component source directly. All components live in your project's `src/components/` directory — they are not locked in a package. ## Border radius Control the roundness of all components with the `--radius` variable: ```css filename="src/app/globals.css" theme={null} :root { --radius: 0.75rem; /* more rounded */ /* --radius: 0rem; /* sharp corners */ } ``` ## Dark mode Templates support dark mode out of the box using Tailwind's `dark:` variant. Toggle dark mode by adding the `dark` class to the `` element: ```tsx theme={null} // Toggle dark mode document.documentElement.classList.toggle('dark'); ``` For Next.js apps, use [next-themes](https://github.com/pacocoursey/next-themes) for automatic system preference detection: ```tsx filename="src/app/providers.tsx" theme={null} 'use client'; import { ThemeProvider } from 'next-themes'; export function Providers({ children }: { children: React.ReactNode }) { return ( {children} ); } ``` ## Restaurant branding Load the restaurant's branding dynamically from the API: ```tsx theme={null} const merchant = await storefront.merchant.getBySlug('downtown-pizza'); // Use merchant data for dynamic theming {merchant.name}
``` Each merchant location also exposes `restaurantLogo` and `coverPhoto` for location-specific branding. ## Next steps > [card] [Components](/docs/components/overview) > > See all available storefront components and their props. > [card] [Build a Storefront](/docs/guides/build-custom-storefront) > > End-to-end guide for building a custom storefront. # Troubleshooting Source: https://craveup-1493c4c7.mintlify.dev/docs/guides/troubleshooting Diagnose direct Storefront API configuration, capability, concurrency, and checkout failures. ## The SDK says an explicit base URL is required Set `NEXT_PUBLIC_CRAVEUP_API_URL` to the API origin and rebuild. Do not append `/api/v1/storefront`; the SDK owns that path. ## Browser requests fail CORS Add the exact storefront origin, including scheme and host, to the API service's `CORS_ALLOWED_ORIGINS`. Avoid wildcard origins. Confirm the preflight allows the headers used by the failed request. ## Published data returns 404 Public catalog routes deliberately hide unpublished, inactive, or cross-tenant resources as not found. Verify the merchant/location is published and that the location belongs to the requested merchant. ## Cart request returns 401 The cart capability is absent, invalid, or belongs to another cart/location. Start a new ordering session if the saved capability is stale. Never substitute a private API key. ## Cart request returns `CART_CONFLICT` Another mutation changed the cart revision. Fetch the cart, update the saved revision from `ETag`, present the current state, and let the shopper retry. Do not silently replay the mutation. ## Cart request returns `CART_IMMUTABLE` The cart is locked, completed, or expired. Preserve terminal checkout handling when applicable; otherwise clear the stale session and create a new cart. ## Customer request returns 401 Confirm Clerk is loaded and signed in, `getAuthToken` requests the current `crave-customer` token from the active session, and `getMerchantSlug` returns the merchant selected by the storefront. If the session is expired or revoked, use Clerk's recovery or sign-in flow. Never substitute a cached JWT or private API key. ## Checkout appears stuck Poll `checkout.getOrderSubmissionOutcome` with the original attempt ID and bounded backoff. `PROCESSING` is neither failure nor success. Render online success only for `PAID`, preserve `ACCEPTED` as pay-at-store authority, and surface `ACTION_REQUIRED` without manufacturing another order. ## Receipt is unavailable Receipt access requires either the authorized customer JWT or the receipt capability. For email/SMS links, capture `receiptToken` from the fragment, remove the fragment immediately, and send the token through the SDK. A missing, wrong, or expired token intentionally looks like not found. ## Order submission errors Check the cart revision and accepted evidence first, then confirm the API service has matching Stripe credentials for the selected environment. The browser receives Stripe client fields only for a `CUSTOMER_ACTION_REQUIRED` outcome. `STRIPE_DIRECT_CHARGE_CUTOVER_INCOMPLETE` means the current direct-charge activation lock rejected ordinary Stripe payment admission. Show checkout as temporarily unavailable and do not retry or attempt to bypass the lock; catalog, menu, and cart work can continue. ## Useful error fields `StorefrontApiError` provides `status`, `code`, `message`, `requestId`, `details`, `method`, and `routeTemplate` without retaining URLs, bodies, or credentials. Include `requestId` in support reports. ## Share a request with merchant support Open **Business Manager → API activity** and search by the response `requestId` or the `X-Request-ID` you supplied. The page shows the organization-scoped route, status, duration, API-key scopes, safe error code, and a sanitized request/response summary. Credentials, authentication data, payment details, and sensitive route bodies are omitted before storage. Exact route, source, API application, location, and time filters are shareable in the page URL. New events stream while the first page is open and visibly fall back to polling if the connection drops. **Export CSV** downloads a rate-limited, bounded copy of the currently filtered sanitized result set. Do not paste API keys, JWTs, Stripe client secrets, card data, or complete customer details into a support ticket. Share the request ID, timestamp, route, location, and visible safe error code. # Upgrade Guide Source: https://craveup-1493c4c7.mintlify.dev/docs/guides/upgrade-guide Migrate a Storefront SDK 1.x integration to the direct, capability-safe 2.0.0 contract. Storefront SDK `2.0.0` is a major version. It replaces the published 1.x browser API-key client with the direct public `/api/v1/storefront` contract. Treat the upgrade as an application migration: use a branch, update all callers together, and verify a sandbox order before production. Published 1.x artifacts remain a durable npm history. Do not unpublish them or silently replace their contents. They may be deprecated after `2.0.0` is verified, but 2.x does not include an API-key shim, a dual transport, or duplicate names for the same operation. Use the canonical `cart.applyDiscount()`, `cart.removeDiscount()`, and location-scoped `loyalty.ledger(locationId)` methods. ## Install the exact major ```bash theme={null} pnpm remove @craveup/storefront-sdk pnpm add --save-exact @craveup/storefront-sdk@2.0.0 ``` Commit the updated lockfile. Do not use `latest`, a semver range, a Git URL, or a workspace build in a released storefront. ## Replace configuration Remove the 1.x browser configuration: ```ts theme={null} // 1.x — remove this configuration. createStorefrontClient({ apiKey: process.env.NEXT_PUBLIC_CRAVEUP_API_KEY!, }); ``` Create a 2.x browser client with public configuration and caller-owned stores: ```ts theme={null} const storefront = createStorefrontClient({ baseUrl: process.env.NEXT_PUBLIC_CRAVEUP_API_URL!, sessionStore, getAuthToken: () => getToken({ template: "crave-customer" }), getMerchantSlug: () => merchantSlug, }); ``` Create a separate server client with only `baseUrl`; use it for anonymous published reads. Remove browser/mobile API keys, mint endpoints, BFF proxies added only for the old SDK, and hand-built authorization headers. Customer authentication is Clerk-managed. Remove Crave login/OTP calls and application-owned JWT storage. Create the customer-capable browser or mobile client only after Clerk is ready, retrieve a short-lived token from the active session on demand, and keep merchant routing explicit with `getMerchantSlug`. Never copy that JWT into application storage. ## Update methods, arguments, and types | 1.x surface | 2.0.0 surface | | - | - | | `locations.getDistance(locationId, input)` | `locations.distance(locationId, input)` | | `locations.submitRating(locationId, { cartId, rating, comment })` | `ratings.submit(locationId, cartId, { rating, comment })` | | `payments.createIntent(locationId, cartId)` | `checkout.submitOrder(locationId, cartId, evidence, options)` | | `cart.getRecommendations(locationId, cartId)` | `cart.recommendations(locationId, cartId)` | | `discounts.apply(locationId, { cartId, code })` | `cart.applyDiscount(locationId, cartId, code)` | | `discounts.remove(locationId, cartId)` | `cart.removeDiscount(locationId, cartId)` | | `client.http.*` and `RequestOptions.skipAuth` | Removed; use the typed namespaces and SDK-owned authorization boundaries | | `StorefrontAnalyticsEventType` enum | `StorefrontAnalyticsEvents` constant plus `StorefrontAnalyticsEvent` union | | Client-supplied `ORDER_PLACED` | Removed; Crave records it after authoritative order creation | | `StorefrontRecommendedProduct` / `RecommendedProductsResponse` | `RecommendationProduct` / `RecommendationProduct[]` | | `SubmitRatingPayload` / `SubmitRatingResponse` | `RatingRequest` / `RatingResponse` | | `GetLocationViaSlugType` | `StorefrontLocation` | | `LocationAddressDTO` | `DeliveryAddress` | | `ApiError` | `StorefrontApiError`, `StorefrontProtocolError`, `StorefrontTimeoutError`, or `StorefrontClientStateError` | Only `SCAN`, `CART_VIEW`, and `CHECKOUT_VIEW` remain valid client analytics events. `StorefrontClientStateError` provides a typed local preflight failure, including `CUSTOMER_AUTH_REQUIRED`, before a request is sent without required customer authentication. ## Update response handling | Operation | 1.x response | 2.0.0 response | | - | - | - | | `orderingSessions.start` | `{ cartId }` or `{ errorMessage }` | `{ cart, cartAccessToken? }`; the SDK persists the capability and revision through `sessionStore` | | `cart.addItem` | `{ cartId, cart }` | `StorefrontCart` | | `cart.update` | Partial cart object | Authoritative `StorefrontCart` | | `cart.updateOrderTime`, `cart.validateAndUpdateCustomer`, `cart.setDelivery`, `cart.setTable`, `cart.setRoom`, `cart.delete` | `{ success: true }` | Authoritative `StorefrontCart` | | Apply or remove discount | `{ success: true }` | Authoritative `StorefrontCart` | | Create PaymentIntent | `{ clientSecret, stripeAccountId }` | Order-first outcome; Stripe account routing is server-owned | Do not rely on structural casts to bridge these response changes. Remove wrapper access such as `result.cart`, replace success-only branches with the returned authoritative cart, and recompile every caller against 2.0.0. Product fixtures and adapters must now provide the required `Product.locationId`. `OrderTimesResponse` exposes labeled `orderDays`; replace the legacy regular-day `{ from, to }` interval branch and render only the days and intervals returned by the API. ## Update request validation * Use only `takeout`, `table_side`, `room_service`, or `delivery` for fulfillment. Set table and room identifiers through `cart.setTable()` and `cart.setRoom()` rather than a generic cart patch. * Use `cart.updateOrderTime()` for scheduling. `cart.update()` accepts fulfillment and/or a note, not order-date or order-time fields. * Send exactly one of `amount` or `percentage` to `cart.updateGratuity()`. * Send a full supported country name such as `United States`, not `US`. * Send table numbers as numeric strings such as `"12"`, not `"T-12"` or `"Patio 3"`. * Treat `marketplaceId` as optional source attribution such as `"web"` or `"mobile"`; it is not a location ID. * For a signed-in shopper who still has a guest-capability cart, use the named `{ includeCustomerContext: true }` request option only when customer-aware discount validation or Stripe customer association is needed. Omit it for a guest; claimed carts use the customer JWT automatically. ## Required migration 1. Configure the explicit public API origin for the correct environment. 2. Provide a `StorefrontSessionStore` for `{ locationId, cartId, accessToken, revision }`, scoped by canonical API environment, merchant, and location. 3. Create carts through `orderingSessions.start()`. Let the SDK persist the returned capability and authoritative revision; do not copy the token into application state or UI props. 4. Let cart methods attach `X-Cart-Token`, `If-Match`, and `Idempotency-Key`. On `CART_CONFLICT`, refresh and ask the customer to retry; never silently replay intent. 5. Integrate the environment-specific Customer Clerk application. Supply `getToken({ template: "crave-customer" })` through `getAuthToken`, supply `getMerchantSlug`, and let Clerk own token storage, refresh, recovery, and logout. 6. Replace legacy payment calls with `checkout.submitOrder(locationId, cartId, evidence, options)`. Stripe is the only online processor: initialize Stripe.js with the `connectedAccountId` from `CUSTOMER_ACTION_REQUIRED`, confirm its client secret, and use bounded `checkout.getOrderSubmissionOutcome()` polling. Stop reading the removed `stripeAccountId` field and remove all provider-selection branches. 7. Capture a receipt capability from the URL fragment, remove the fragment immediately, and scope storage by environment, merchant, and receipt ID. 8. Register each exact deployed browser origin with Crave. Native apps normally need no CORS registration; Expo web does. 9. Delete the obsolete 1.x client, API-key configuration, wrapper types, adapters, tests, and documentation in the same application change. ## Verification checklist * Public bundles contain no private Crave or payment-provider secrets. * Published merchant, location, menu, product, distance, order-time, and gratuity requests carry no customer JWT. * Wrong, expired, cross-location, and cross-merchant capabilities are denied. * Stale revisions return `CART_CONFLICT` and are not automatically replayed. * Only `PAID` is treated as online-payment success; `ACCEPTED` is an audited pay-at-store order. * CORS is restricted to the exact deployed storefront origins. * A clean install, typecheck, production web build or Expo export, and sandbox vertical slice use the exact registry artifact. If a production 1.x storefront cannot move atomically, keep its pinned 1.x artifact and deployed API path unchanged while a separate 2.0.0 release candidate is verified. Do not make one bundle switch between the two contracts at runtime. # Outbound Webhooks Source: https://craveup-1493c4c7.mintlify.dev/docs/guides/webhooks Receive signed, versioned Crave commerce events with durable delivery evidence. Crave sends merchant events to server-side HTTPS endpoints configured in **Business Manager → Developers → Webhooks**. Sandbox and production are separate deployments: create and verify an endpoint in each environment that you use. ## Delivery contract Every request is an HTTP `POST` whose exact UTF-8 body is a versioned event envelope: ```json theme={null} { "id": "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb", "type": "order.created", "version": "2026-08-27", "deployment": "sandbox", "organizationId": "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", "occurredAt": "2026-08-26T12:00:00.000Z", "test": false, "data": { "amount": "42.50", "cartId": "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee", "currency": "USD", "locationId": "dddddddd-dddd-4ddd-8ddd-dddddddddddd", "orderId": "cccccccc-cccc-4ccc-8ccc-cccccccccccc", "status": "pending" } } ``` Crave includes these headers: | Header | Meaning | | - | - | | `Crave-Webhook-Id` | Immutable event ID; use it as your deduplication key. | | `Crave-Webhook-Timestamp` | Unix seconds used in the signature. | | `Crave-Webhook-Signature` | One or more comma-separated `v1=` HMAC signatures. | | `Crave-Webhook-Event` | Event type. | | `Crave-Webhook-Version` | Payload schema version. | | `Crave-Webhook-Test` | `true` only for an explicit dashboard test event. | ## Verify signatures Store the endpoint secret only in your server-side secret manager. Verify the signature against the **raw request body before JSON parsing**. The signed input is `.`, using HMAC-SHA256 and unpadded base64url output. ```ts theme={null} import { createHmac, timingSafeEqual } from "node:crypto"; function verifyCraveWebhook({ rawBody, signatureHeader, timestampHeader, secret, }: { rawBody: Buffer; signatureHeader: string; timestampHeader: string; secret: string; }) { const timestamp = Number(timestampHeader); const now = Math.floor(Date.now() / 1000); if (!Number.isSafeInteger(timestamp) || Math.abs(now - timestamp) > 300) { return false; } const expected = createHmac("sha256", secret) .update(`${timestamp}.`) .update(rawBody) .digest("base64url"); return signatureHeader.split(",").some((candidate) => { const [version, encoded] = candidate.trim().split("=", 2); if (version !== "v1" || !encoded) return false; const left = Buffer.from(encoded); const right = Buffer.from(expected); return left.length === right.length && timingSafeEqual(left, right); }); } ``` Reject timestamps outside the 300-second tolerance. During a bounded secret-rotation overlap, Crave signs with both the current and previous secret, so a receiver deploying either valid secret continues to verify requests. After the new secret is deployed, remove the previous secret from the receiver. ## Event catalog The `2026-08-27` registry defines: * `order.created` * `order.status_changed` * `order.cancelled` * `order.refunded` * `settlement.updated` * `payment.succeeded` * `payment.failed` * `catalog.published` * `catalog.availability_changed` * `location.updated` * `customer.verified` * `catering.event.updated` `catering.event.updated` carries only `eventId`, `locationId`, the six-digit display `reference`, `change`, and `status`. It never carries customer contact details, quote lines or prices, dietary/access notes, or customer-link credentials. Quote negotiation emits `quote_sent`, restaurant `declined`, and `expired`; the shared contract also reserves `accepted` and `payment_received` for the customer acceptance/payment lane. The display reference is not an authentication credential. Duplicate deliveries retain the same event ID. `settlement.updated` carries the order, fulfillment, settlement, refund, and reconciliation revisions side by side under `revisions`, alongside the `orderId` and the `cartId` the order was submitted from. Each revision advances independently, so reconcile the concern you care about against its own revision rather than inferring one from another. A pay-at-store order emits it while the settlement is still `due`, again as tender evidence arrives, and again for post-close recovery. Order lifecycle states are carried by `order.status_changed`; there are no separate `order.confirmed`, `order.ready`, or `order.completed` event types. `cart.abandoned` is not part of the outbound catalog. High-frequency shared-cart updates use the assisted-ordering realtime contract, not merchant webhooks. Order, payment, and settlement envelopes carry `cartId` so an assisted-ordering consumer can reconcile the exact canonical cart without scanning active sessions. It is `null` only when the order originated outside a Crave storefront cart, such as a provider-native POS order; consumers must not infer a cart in that case. For a cart-correlated event, use the signed `locationId` and `cartId` only as lookup coordinates, then read the canonical machine projection from `GET /api/v1/locations/:locationId/carts/:cartId/commerce-projection`. This server-to-server route requires an API key with `orders:read` and access to that location. It remains available after the guest cart capability expires, also covers `payment.failed` events that do not carry an order ID, and returns only the correlated cart ID, checkout attempt state, settlement state, reconciliation state, and order status: The generated [Integration OpenAPI specification](/docs/generated/integration.openapi.json) is also served by each API deployment at `/integration-swagger.json`. Its base is `/api/v1`, **not** `/api/v1/storefront`. Keep the organization API key on your server; a diner capability or merchant session is not a replacement. Private API errors use `success`, `message`, and an optional `code`/`data`, not the Storefront error envelope. Treat the projection as a reconciliation read, never permission to retry an uncertain checkout. Baseline middleware can reject before the handler: `429` returns `{status, message}` and a limiter-store outage returns `503` with `{status, code, message}` and `Retry-After: 1`. These responses do not carry `success`; the generated specification documents them separately from private handler errors. ```json theme={null} { "cartId": "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee", "checkout": { "attemptId": "ffffffff-ffff-4fff-8fff-ffffffffffff", "collectionMode": "ONLINE", "status": "SUCCEEDED" }, "payment": { "status": "PAID", "reconciliationStatus": "CURRENT" }, "order": { "id": "cccccccc-cccc-4ccc-8ccc-cccccccccccc", "status": "ACCEPTED" } } ``` Treat the webhook body as a hint. Confirm that the response `cartId` matches the event before updating local projections. The route is `private, no-store`; it never returns customer data, line items, raw provider evidence, or reusable cart credentials. > [!NOTE] > > Every event in the registry is emitted except `catalog.availability_changed` > and `location.updated`, which remain registry-reserved. `order.created` is > emitted in the same transaction that submits a storefront cart as an order, > `payment.succeeded` when that order's online payment is captured, and > `settlement.updated` for every settlement transition in every deployment. > Subscribing to a reserved type is safe, but do not build a flow that assumes > an event whose producer has not shipped. ## Acknowledge and deduplicate 1. Preserve the raw body and verify the timestamp and signature. 2. Atomically record `Crave-Webhook-Id` in your database. 3. If that ID already exists, return `2xx` without repeating the business action. 4. Queue your own processing and return `2xx` promptly. Delivery is **at least once**. Requests for different events may arrive out of order, and a timeout can occur after your server commits. Use the event ID for deduplication and use the Crave REST API to reconcile current resource state when the final outcome is ambiguous. ## Retries and terminal failures Crave retries network errors, `408`, `409`, `425`, `429`, and `5xx` responses. Each automatic cycle allows up to 12 attempts, starts with a 30-second exponential-backoff window, applies full jitter, and caps the window at 6 hours. A valid `Retry-After` is honored up to 1 hour. Connections and responses each have a 10-second timeout. Other `4xx` responses are terminal. Business Manager records each attempt's status, duration, safe error code, allowlisted response headers, and at most 4 KB of response text. An organization administrator or authorized Crave support operator can manually redeliver a delivered or terminal request. Manual redelivery keeps the original event ID and exact body, records an audit reason, and opens one fresh bounded attempt cycle; it never creates a new business event. ## Endpoint security * Endpoints must use public HTTPS on port 443. * Credentials in URLs, fragments, redirects, private/loopback/link-local destinations, and empty DNS answers are rejected. * DNS is revalidated immediately before every connection, and the connection is pinned to the validated address set to prevent DNS rebinding. * Signing secrets are encrypted at rest and shown only when an endpoint is created or rotated. * Disabling an endpoint terminalizes its queued deliveries; re-enable it before requesting a redelivery. See the delivery timeline in Business Manager when troubleshooting. Crave staff use an audited cross-organization health view for queue age, failing endpoints, and terminal deliveries. ## Validating payloads Crave may add fields to an event payload within a contract version. If your handler validates with a strict schema — one that rejects unknown keys — an added field makes your endpoint answer `400`, and a `400` is terminal: the delivery is dropped rather than retried, and no alert fires on our side because the request completed normally. Accept unknown fields, or track the registry and deploy your schema change before ours lands. If you correlate order and settlement events, [Assisted Ordering](/docs/guides/assisted-ordering) documents which identifier each event is correlated by. # Flutter quickstart Source: https://craveup-1493c4c7.mintlify.dev/docs/quickstarts/flutter Connect a Flutter application to the Crave Storefront API with typed, capability-safe ordering. This quickstart configures the official Dart SDK, checks whether takeout ordering is available, and loads a published menu without a browser API key or BFF. ## 1. Install ```yaml pubspec.yaml theme={null} dependencies: flutter: sdk: flutter crave_storefront_sdk: 0.2.0 ``` Run `flutter pub get`. ## 2. Configure deployment values Pass deployment-specific values with `--dart-define`: ```bash theme={null} flutter run \ --dart-define=CRAVEUP_API_URL=https://api.craveup.com \ --dart-define=CRAVEUP_MERCHANT_SLUG=downtown-pizza \ --dart-define=CRAVEUP_LOCATION_ID=loc_123 ``` For sandbox testing, replace the origin and identifiers with the exact sandbox deployment values provided for your account. Sandbox and production have separate environment variables and data; never reuse a `StorefrontSessionStore` record or customer token across those origins. ## 3. Create the client ```dart theme={null} import 'package:crave_storefront_sdk/crave_storefront_sdk.dart'; const apiUrl = String.fromEnvironment('CRAVEUP_API_URL'); const merchantSlug = String.fromEnvironment('CRAVEUP_MERCHANT_SLUG'); final sessionStore = InMemoryStorefrontSessionStore(); final client = CraveStorefrontClient( baseUri: Uri.parse(apiUrl), merchantSlug: merchantSlug, sessionStore: sessionStore, ); ``` This anonymous guest quickstart needs no customer-token provider. The in-memory store makes the sample runnable, but it loses the cart when the process exits. Before shipping, replace it with a `StorefrontSessionStore` backed by encrypted platform storage. ## 4. Check availability and load the menu ```dart theme={null} const locationId = String.fromEnvironment('CRAVEUP_LOCATION_ID'); Future loadTakeoutMenu() async { final readiness = await client.locations.getOrderingReadiness( locationId, fulfillmentMethod: FulfillmentMethod.takeout, ); if (readiness case OrderingUnavailable(:final reason)) { throw StateError(reason); } return client.menus.getForLocation(locationId, menuOnly: true); } ``` `getOrderingReadiness` is anonymous and side-effect free. Starting an ordering session is the point where the SDK receives and stores the guest cart capability and revision. ## 5. Start an order ```dart theme={null} final result = await client.orderingSessions.start( locationId, StartOrderingSessionRequest.fresh( fulfillmentMethod: FulfillmentMethod.takeout.wireValue, channel: OrderChannel.app, ), ); final cart = result.cart; ``` Keep one client per application session so its serialized cart lifecycle protects monotonic revisions. Dispose it with `client.close()` when the application-level owner is torn down. ## 6. Surface safe failures ```dart theme={null} try { await loadTakeoutMenu(); } on StorefrontApiException catch (error) { showApiMessage(error.code, error.requestId); } on StorefrontTimeoutException { showRetryMessage(); } ``` See the [Dart and Flutter Storefront SDK guide](/docs/getting-started/flutter-storefront-sdk) for session storage, cancellation, conflict recovery, and security guidance. # React Native / Expo Quickstart Source: https://craveup-1493c4c7.mintlify.dev/docs/quickstarts/mobile Build a mobile storefront that calls the public Crave API directly. The Storefront API is safe to call directly from an Expo app. Published catalog reads are anonymous, cart access is scoped by a short-lived capability, and signed-in customer resources use a customer JWT. No API key or mobile BFF is required. ## 1. Create the app ```bash theme={null} npx create-expo-app my-storefront --template blank-typescript cd my-storefront npx expo install expo-secure-store npm install --save-exact @craveup/storefront-sdk@2.0.1 ``` ## 2. Configure public values ```env filename=".env" theme={null} EXPO_PUBLIC_CRAVEUP_API_URL=https://api.craveup.com EXPO_PUBLIC_CRAVEUP_LOCATION_ID=loc_your_location_id EXPO_PUBLIC_CRAVEUP_MERCHANT_SLUG=your-restaurant-slug ``` Never put Crave admin, partner, or payment-provider secrets in an `EXPO_PUBLIC_` variable. ## 3. Create the client ```ts filename="src/lib/storefront.ts" theme={null} import * as SecureStore from "expo-secure-store"; import { createStorefrontClient, type StorefrontCartSession, type StorefrontSessionStore, } from "@craveup/storefront-sdk"; const apiUrl = process.env.EXPO_PUBLIC_CRAVEUP_API_URL; const merchantSlug = process.env.EXPO_PUBLIC_CRAVEUP_MERCHANT_SLUG; if (!apiUrl || !merchantSlug) throw new Error("Missing Storefront configuration"); const apiOrigin = new URL(apiUrl).origin; const secureKeyPart = (value: string) => Array.from(value, (character) => character.codePointAt(0)!.toString(16).padStart(6, "0"), ).join(""); const environmentNamespace = secureKeyPart(apiOrigin); const merchantNamespace = secureKeyPart(merchantSlug); const key = (kind: "cart" | "receipt", resourceId: string) => [ "storefront", kind, "v1", environmentNamespace, merchantNamespace, secureKeyPart(resourceId), ].join("."); const cartKey = (locationId: string) => key("cart", locationId); const receiptKey = (receiptId: string) => key("receipt", receiptId); async function readCartSession( locationId: string, ): Promise { const storageKey = cartKey(locationId); const raw = await SecureStore.getItemAsync(storageKey); if (!raw) return null; try { const value = JSON.parse(raw) as Partial; if ( value.locationId !== locationId || typeof value.cartId !== "string" || typeof value.revision !== "number" || !Number.isInteger(value.revision) || value.revision < 0 || (value.accessToken !== undefined && typeof value.accessToken !== "string") ) { throw new Error("Invalid cart session"); } return value as StorefrontCartSession; } catch { await SecureStore.deleteItemAsync(storageKey); return null; } } export const sessionStore: StorefrontSessionStore = { async get(locationId) { return readCartSession(locationId); }, async set(session) { await SecureStore.setItemAsync( cartKey(session.locationId), JSON.stringify(session), ); }, async clear(locationId) { await SecureStore.deleteItemAsync(cartKey(locationId)); }, }; export const receiptTokenStore = { get: (receiptId: string) => SecureStore.getItemAsync(receiptKey(receiptId)), set: (receiptId: string, token: string) => SecureStore.setItemAsync(receiptKey(receiptId), token), clear: (receiptId: string) => SecureStore.deleteItemAsync(receiptKey(receiptId)), }; export const storefront = createStorefrontClient({ baseUrl: apiOrigin, sessionStore, getMerchantSlug: () => merchantSlug, }); ``` For signed-in customer flows, create the client after Clerk is ready. Supply an auth-token callback that requests the `crave-customer` template from the active Clerk Expo session. Clerk owns the session and token refresh; do not copy the JWT into SecureStore. ## 4. Load the merchant and create a cart ```ts theme={null} const merchant = await storefront.merchant.getBySlug( process.env.EXPO_PUBLIC_CRAVEUP_MERCHANT_SLUG!, ); const locationId = process.env.EXPO_PUBLIC_CRAVEUP_LOCATION_ID!; const session = await storefront.orderingSessions.start(locationId, { marketplaceId: "mobile", fulfillmentMethod: "takeout", }); await storefront.cart.addItem(locationId, session.cart.id, { productId: "prod_margherita", quantity: 1, selections: [], itemUnavailableAction: "remove_item", }); ``` SecureStore keys accept only alphanumeric characters, `.`, `-`, and `_`; the example encodes every dynamic component before composing dot-delimited keys. The environment, merchant, and location scopes prevent capabilities from crossing applications or deployment tiers. Store only the small cart session and receipt capability there—not customer JWTs, cart contents, or API caches. Clear the guest cart capability after claim, deletion, expiry, or terminal checkout handling; retain only the returned revision when a claimed cart remains customer-authenticated. Let Clerk clear the customer session on logout. Store a deep-link receipt capability with `receiptTokenStore.set(receiptId, token)` only when resume support requires it, and remove it after terminal display or expiry. If the API returns `CART_CONFLICT`, fetch the latest cart before asking the customer to retry. Native requests normally send no browser `Origin` header, so they do not require CORS registration. If you also ship an Expo web build, register that exact browser origin with Crave; never use a wildcard workaround. `marketplaceId` is optional attribution for the app source, such as `"mobile"`; it is not a location ID. The route already scopes the cart to `locationId`. For a signed-in shopper who still has a guest-capability cart, set the named `includeCustomerContext` option to `true` on discount or payment-session calls that need customer-aware validation or provider customer association. Omit it for guest checkout; a claimed cart uses the customer JWT automatically. ## Next steps > [card] [Manage Cart](/docs/guides/manage-cart) > > Learn the capability and revision lifecycle. > [card] [Checkout Flow](/docs/guides/checkout-flow) > > Integrate payment and authoritative order-result polling. # Next.js Quickstart Source: https://craveup-1493c4c7.mintlify.dev/docs/quickstarts/nextjs Build a direct, capability-safe storefront with Next.js and the Crave Storefront SDK. This quickstart connects a Next.js App Router project directly to the public Storefront API. No BFF or browser API key is required. ## Prerequisites * Node.js 20+ * A published merchant slug and location ID * The exact browser origin for local, preview, and production deployments registered with Crave * A Stripe publishable key when you add checkout ## 1. Create the app and install the SDK ```bash theme={null} npx create-next-app@latest my-storefront --typescript --app --tailwind cd my-storefront pnpm add --save-exact @craveup/storefront-sdk@2.0.1 ``` ## 2. Configure the public origin The SDK requires an explicit `baseUrl`; it never derives an origin from a credential. ## 3. Create the browser client and scoped stores ```ts filename="src/lib/storefront-browser.ts" theme={null} "use client"; import type { StorefrontCartSession, StorefrontSessionStore, } from "@craveup/storefront-sdk"; import { createStorefrontClient } from "@craveup/storefront-sdk"; const apiUrl = process.env.NEXT_PUBLIC_CRAVEUP_API_URL; const merchantSlug = process.env.NEXT_PUBLIC_CRAVEUP_MERCHANT_SLUG; if (!apiUrl || !merchantSlug) throw new Error("Missing Storefront configuration"); const apiOrigin = new URL(apiUrl).origin; const storageKeyPart = (value: string) => encodeURIComponent(value).replaceAll(".", "%2E"); const environmentNamespace = storageKeyPart(apiOrigin); const scope = `${environmentNamespace}.${storageKeyPart(merchantSlug)}`; const key = (kind: "cart" | "receipt", resourceId: string) => `storefront.${kind}.v1.${scope}.${storageKeyPart(resourceId)}`; const cartKey = (locationId: string) => key("cart", locationId); const receiptKey = (receiptId: string) => key("receipt", receiptId); function readCartSession(locationId: string): StorefrontCartSession | null { const storageKey = cartKey(locationId); const raw = sessionStorage.getItem(storageKey); if (!raw) return null; try { const value = JSON.parse(raw) as Partial; if ( value.locationId !== locationId || typeof value.cartId !== "string" || typeof value.revision !== "number" || !Number.isInteger(value.revision) || value.revision < 0 || (value.accessToken !== undefined && typeof value.accessToken !== "string") ) { throw new Error("Invalid cart session"); } return value as StorefrontCartSession; } catch { sessionStorage.removeItem(storageKey); return null; } } export const sessionStore: StorefrontSessionStore = { get(locationId) { return readCartSession(locationId); }, set(session) { sessionStorage.setItem( cartKey(session.locationId), JSON.stringify(session), ); }, clear(locationId) { sessionStorage.removeItem(cartKey(locationId)); }, }; export const receiptTokenStore = { get: (receiptId: string) => sessionStorage.getItem(receiptKey(receiptId)), set: (receiptId: string, token: string) => sessionStorage.setItem(receiptKey(receiptId), token), clear: (receiptId: string) => sessionStorage.removeItem(receiptKey(receiptId)), }; export const storefront = createStorefrontClient({ baseUrl: apiOrigin, sessionStore, getMerchantSlug: () => merchantSlug, }); ``` The environment, merchant, and location scopes prevent one storefront's capabilities from being reused by another. For signed-in customer flows, create the browser client only after Clerk is ready and add `getAuthToken: () => getToken({ template: "crave-customer" })`; keep `getMerchantSlug` so the SDK can send explicit tenant routing. Clerk owns the session and token refresh—do not copy the JWT into application storage. Capture a receipt capability from the URL fragment, remove the fragment immediately, and keep it with `receiptTokenStore.set(receiptId, token)` only while the receipt is needed. ## 4. Create a separate server client ```ts filename="src/lib/storefront-server.ts" theme={null} import { createStorefrontClient } from "@craveup/storefront-sdk"; export const storefrontServer = createStorefrontClient({ baseUrl: process.env.NEXT_PUBLIC_CRAVEUP_API_URL!, }); ``` Use the server client only for anonymous published merchant, location, menu, product, distance, order-time, and gratuity calls. It deliberately has no `sessionStore` or `getAuthToken`. Never import the browser client into a Server Component, Route Handler, or Server Action. ## 5. Start a cart and mutate it ```tsx filename="src/app/order/page.tsx" theme={null} "use client"; import { useEffect, useState } from "react"; import type { StorefrontCart } from "@craveup/storefront-sdk"; import { storefront } from "@/lib/storefront-browser"; const locationId = process.env.NEXT_PUBLIC_CRAVEUP_LOCATION_ID!; export default function OrderPage() { const [cart, setCart] = useState(null); useEffect(() => { void storefront.orderingSessions .start(locationId, { fulfillmentMethod: "takeout" }) .then(({ cart }) => setCart(cart)); }, []); async function addItem(productId: string) { if (!cart) return; setCart( await storefront.cart.addItem(locationId, cart.id, { productId, quantity: 1, selections: [], itemUnavailableAction: "remove_item", }), ); } return (

{cart ? `${cart.totalQuantity} items` : "Starting cart…"}

); } ``` The SDK stores the returned cart capability, sends it only in a header, updates the saved revision from `ETag`, and generates idempotency keys. A `CART_CONFLICT` is surfaced to your UI; reload the cart before asking the shopper to retry. Clear the guest capability after claim, deletion, expiry, or terminal checkout handling, let Clerk clear its session on logout, and clear receipt capabilities after terminal display. ## 6. Complete checkout safely For a signed-in shopper who still has a guest-capability cart, opt into the customer context when discount validation or provider customer association needs it: ```ts theme={null} const outcome = await storefront.checkout.submitOrder( locationId, cart.id, { acceptedCatalogEvidence, acceptedDiscountEvidence, collectionMode: "ONLINE", customerConfirmationRevision, quoteFingerprint, }, { idempotencyKey, includeCustomerContext: true, revision: cart.revision }, ); ``` Omit `includeCustomerContext` for a guest checkout. A claimed cart already uses the customer JWT because its guest capability has been cleared. If the outcome is `CUSTOMER_ACTION_REQUIRED`, confirm its Stripe client secret using the exact returned connected account, then poll `storefront.checkout.getOrderSubmissionOutcome(locationId, cart.id, outcome.attemptId)`. Treat only `PAID` as an online-payment success. Clear the cart session only after terminal handling. ## 7. Register every browser origin Register the exact origin for local development, each stable preview, and production before testing browser calls. An origin includes the scheme, hostname, and any non-default port. Do not request a wildcard and do not send a cart capability or customer JWT while working around a CORS failure. See [Deployment](/docs/guides/deployment). ## Next steps > [card] [Manage Cart](/docs/guides/manage-cart) > > Add fulfillment, discounts, gratuity, and conflict handling. > [card] [Checkout Flow](/docs/guides/checkout-flow) > > Confirm payment and poll the authoritative order result. > [card] [Storefront SDK](/docs/getting-started/storefront-sdk) > > Review the complete typed client surface. > [card] [Deployment](/docs/guides/deployment) > > Configure exact origins and production environment variables. # React Quickstart Source: https://craveup-1493c4c7.mintlify.dev/docs/quickstarts/react Build a direct-to-Crave storefront with React, Vite, and the Storefront SDK. Build a browser storefront with React and `@craveup/storefront-sdk`. Public catalog reads are anonymous. Cart mutations use the short-lived capability returned when the cart is created; no API key or BFF is required. ## Prerequisites * Node.js 20+ and a package manager * A published Crave merchant and location * The public Crave API origin for your environment * The exact deployed browser origin registered with Crave ## 1. Create the app and install the SDK ```bash theme={null} npm create vite@latest my-storefront -- --template react-ts cd my-storefront npm install --save-exact @craveup/storefront-sdk@2.0.1 ``` ## 2. Configure public identifiers ```env filename=".env" theme={null} VITE_CRAVEUP_API_URL=https://api.craveup.com VITE_LOCATION_ID=loc_your_location_id VITE_MERCHANT_SLUG=your-restaurant-slug ``` These values identify a public API and published resources. Do not put Crave admin, partner, payment-provider, or integration secrets in a `VITE_` variable. ## 3. Create a tab-scoped session store ```ts filename="src/lib/storefront.ts" theme={null} import { createStorefrontClient, type StorefrontCartSession, type StorefrontSessionStore, } from "@craveup/storefront-sdk"; const apiUrl = import.meta.env.VITE_CRAVEUP_API_URL; const merchantSlug = import.meta.env.VITE_MERCHANT_SLUG; if (!apiUrl || !merchantSlug) throw new Error("Missing Storefront configuration"); const apiOrigin = new URL(apiUrl).origin; const storageKeyPart = (value: string) => encodeURIComponent(value).replaceAll(".", "%2E"); const environmentNamespace = storageKeyPart(apiOrigin); const scope = `${environmentNamespace}.${storageKeyPart(merchantSlug)}`; const storageKey = (kind: "cart" | "receipt", resourceId: string) => `storefront.${kind}.v1.${scope}.${storageKeyPart(resourceId)}`; const cartKey = (locationId: string) => storageKey("cart", locationId); const receiptKey = (receiptId: string) => storageKey("receipt", receiptId); function readCartSession(locationId: string): StorefrontCartSession | null { const key = cartKey(locationId); const raw = sessionStorage.getItem(key); if (!raw) return null; try { const value = JSON.parse(raw) as Partial; if ( value.locationId !== locationId || typeof value.cartId !== "string" || typeof value.revision !== "number" || !Number.isInteger(value.revision) || value.revision < 0 || (value.accessToken !== undefined && typeof value.accessToken !== "string") ) { throw new Error("Invalid cart session"); } return value as StorefrontCartSession; } catch { sessionStorage.removeItem(key); return null; } } export const sessionStore: StorefrontSessionStore = { get(locationId) { return readCartSession(locationId); }, set(session) { sessionStorage.setItem( cartKey(session.locationId), JSON.stringify(session), ); }, clear(locationId) { sessionStorage.removeItem(cartKey(locationId)); }, }; export const receiptTokenStore = { get: (receiptId: string) => sessionStorage.getItem(receiptKey(receiptId)), set: (receiptId: string, token: string) => sessionStorage.setItem(receiptKey(receiptId), token), clear: (receiptId: string) => sessionStorage.removeItem(receiptKey(receiptId)), }; export const storefront = createStorefrontClient({ baseUrl: apiOrigin, sessionStore, getMerchantSlug: () => merchantSlug, }); ``` The SDK attaches `X-Cart-Token`, `If-Match`, and `Idempotency-Key` where required and updates the stored cart revision from response ETags. The canonical API environment, merchant, and resource scopes prevent capabilities from crossing storefronts. For signed-in customer flows, create the client after Clerk is ready and add `getAuthToken: () => getToken({ template: "crave-customer" })`; never persist that JWT yourself. Save a fragment-delivered receipt capability only with `receiptTokenStore.set(receiptId, token)` and remove it after terminal display. ## 4. Fetch the published merchant ```tsx filename="src/App.tsx" theme={null} import { useEffect, useState } from "react"; import type { MerchantApiResponse } from "@craveup/storefront-sdk"; import { storefront } from "./lib/storefront"; export default function App() { const [merchant, setMerchant] = useState(null); useEffect(() => { storefront.merchant .getBySlug(import.meta.env.VITE_MERCHANT_SLUG) .then(setMerchant); }, []); if (!merchant) return

Loading...

; return

{merchant.name}

; } ``` ## 5. Start a cart and add an item ```ts theme={null} const locationId = import.meta.env.VITE_LOCATION_ID; const session = await storefront.orderingSessions.start(locationId, { marketplaceId: "web", fulfillmentMethod: "takeout", }); const cart = await storefront.cart.addItem(locationId, session.cart.id, { productId: "prod_margherita", quantity: 1, selections: [], itemUnavailableAction: "remove_item", }); ``` Keep the cart capability in tab-scoped storage. On `CART_CONFLICT`, refresh the cart and ask the user to retry; do not replay the mutation automatically. Clear the cart capability after claim, deletion, expiry, or terminal checkout handling. Clerk owns logout and customer-session cleanup. `marketplaceId` is an optional source-attribution label, such as `"web"`; it is not a location ID. The route already scopes the cart to `locationId`. ## 6. Register the browser origin Register the exact deployed origin—including scheme, hostname, and any non-default port—with Crave before testing. Register stable preview origins separately; wildcard origins are not accepted. ## Next steps > [card] [Display Menu](/docs/guides/display-menu) > > Fetch the published menu and product data. > [card] [Manage Cart](/docs/guides/manage-cart) > > Handle capabilities, revisions, and idempotent mutations. > [card] [Checkout Flow](/docs/guides/checkout-flow) > > Submit the canonical order and poll its authoritative order-first outcome. > [card] [SDK Reference](/docs/getting-started/storefront-sdk) > > See the complete direct API client. # Vanilla JavaScript Quickstart Source: https://craveup-1493c4c7.mintlify.dev/docs/quickstarts/vanilla-js Use the public Crave Storefront API directly from a browser without a framework. This example uses `fetch` against the public Storefront API. Catalog reads are anonymous; cart operations are protected by the capability returned with the ordering session. ## 1. Create a small client ```js filename="storefront.js" theme={null} const API_ORIGIN = "https://api.craveup.com"; const API = `${API_ORIGIN}/api/v1/storefront`; const merchantSlug = "your-restaurant-slug"; const locationId = "loc_your_location_id"; const storageKeyPart = (value) => encodeURIComponent(value).replaceAll(".", "%2E"); const environmentNamespace = storageKeyPart(new URL(API_ORIGIN).origin); const cartStorageKey = [ "crave", "storefront", "cart", "v1", environmentNamespace, storageKeyPart(merchantSlug), storageKeyPart(locationId), ].join("."); function readCartSession() { const raw = sessionStorage.getItem(cartStorageKey); if (!raw) return null; try { const value = JSON.parse(raw); if ( !value || typeof value !== "object" || typeof value.cartId !== "string" || typeof value.accessToken !== "string" || !Number.isInteger(value.revision) || value.revision < 0 ) { throw new Error("Invalid cart session"); } return value; } catch { sessionStorage.removeItem(cartStorageKey); return null; } } let cartSession = readCartSession(); function mutationHeaders() { if (!cartSession) throw new Error("Start an ordering session first."); return { "Content-Type": "application/json", "X-Cart-Token": cartSession.accessToken, "If-Match": `"cart-${cartSession.revision}"`, "Idempotency-Key": crypto.randomUUID(), }; } async function parse(response) { const body = await response.json(); if (!response.ok) throw body; const match = response.headers.get("ETag")?.match(/^(?:W\/)?"cart-(\d+)"$/); if (match && cartSession) { const nextRevision = Number(match[1]); if (nextRevision > cartSession.revision) { cartSession.revision = nextRevision; sessionStorage.setItem(cartStorageKey, JSON.stringify(cartSession)); } } return body; } ``` Before running this in a browser, register its exact origin with Crave. Scheme, hostname, and non-default port are part of the origin, so local, preview, and production deployments need separate registrations; wildcards are not accepted. ## 2. Read the published catalog ```js theme={null} const merchant = await fetch(`${API}/merchant/${merchantSlug}`).then(parse); const menu = await fetch(`${API}/locations/${locationId}/menus`).then(parse); ``` ## 3. Start an ordering session ```js theme={null} const response = await fetch( `${API}/locations/${locationId}/ordering-sessions`, { method: "POST", headers: { "Content-Type": "application/json", "Idempotency-Key": crypto.randomUUID(), }, body: JSON.stringify({ marketplaceId: "web", fulfillmentMethod: "takeout", }), }, ); const session = await parse(response); cartSession = { cartId: session.cart.id, accessToken: session.cartAccessToken, revision: session.cart.revision, }; sessionStorage.setItem(cartStorageKey, JSON.stringify(cartSession)); ``` `marketplaceId` is optional source attribution, such as `"web"`; it is not a location ID. The route already scopes the cart to `locationId`. ## 4. Add an item ```js theme={null} const cart = await fetch( `${API}/locations/${locationId}/carts/${cartSession.cartId}/items`, { method: "POST", headers: mutationHeaders(), body: JSON.stringify({ productId: "prod_margherita", quantity: 1, selections: [], itemUnavailableAction: "remove_item", }), }, ).then(parse); ``` Do not place the cart ID or capability in a query string. Clear the guest record after claim, cart deletion, expiry, or terminal checkout handling. If customer-authenticated access continues after claim, retain only the authoritative revision in a separate authenticated-cart record. On `CART_CONFLICT`, fetch the cart using `X-Cart-Token`, accept the latest ETag, and ask the user to retry instead of replaying the write. ## Next steps > [card] [REST API Essentials](/docs/getting-started/rest-api) > > Understand every authentication boundary. > [card] [Checkout Flow](/docs/guides/checkout-flow) > > Complete payment and poll the authoritative order result.