Skip to main content

Set up AI ordering

This guide gets your shop taking orders from ChatGPT and Claude through SharePay. You don't need it for assistants to buy from you: an assistant can already browse your website and pay at your SharePay checkout. Setting this up adds the fast way: the assistant searches your products and orders in seconds.

SharePay never works out prices. Your shop prices every order exactly as its own checkout does, including your sales, delivery rules and discount codes.

What you need​

  • A SharePay business with your website domain set (Settings, Developers, Allowed return domain).
  • A shop built on Node 18.17 or later: Next.js, Express or any framework that handles standard Request and Response. For anything else, follow By hand.

This guide is for @sharepay/cli 0.1.0 and @sharepay/node 0.1.0.

The quick way: one command​

In your shop's code folder, run:

npx @sharepay/cli connect
  1. The command shows a short code, like KMRT-4Q7X, and opens SharePay in your browser. Sign in, check the business name, type the code, and press Allow. If you didn't run the command yourself, just now, you won't have a code: cancel.

  2. The command writes two secrets to your environment file (.env.local for Next.js, .env otherwise), readable by you only, and adds that file to .gitignore:

    • SHAREPAY_SECRET_KEY: a new test API key named "SharePay command". Revoke it any time under Developers.
    • SHAREPAY_SIGNING_SECRET: proves a request came from SharePay.
  3. It creates four files (Next.js) or two (Express). It never overwrites a file that's already there:

    FileWhat it does
    lib/sharepay-setup.tsYour two functions, listProducts and priceOrder. Fill these in.
    app/api/sharepay/products/route.tsYour product list address. Nothing to change.
    app/api/sharepay/checkout/route.tsYour checkout address. Nothing to change.
    public/.well-known/sharepay.txtProves the website is yours. Nothing to change.

    On Express or anything else, the command prints the domain-proof line instead. Serve it as plain text at https://yourshop.com/.well-known/sharepay.txt.

You can run connect again at any time. It keeps the key you have and refreshes the signing secret and the domain proof (useful after you replace the signing secret, or set your domain). Add --force for a new key. It won't swap a live key for a test one unless you add --force.

Then:

npm install @sharepay/node

Fill in the two functions (see Writing the two functions), add both secrets to your host's environment settings, deploy, and run:

npx @sharepay/cli check https://yourshop.com

The check first looks for your domain-proof file, so SharePay never sends anything to a website its owner hasn't approved. It then reads your product list with a signed request, and makes sure both addresses refuse a request with no signature and one signed with the wrong secret. If your shop accepted an unsigned request, anyone could create orders as if they came from SharePay, so the check stops and tells you what to fix.

With a test key, the check stops there and tells you it passed. AI ordering is one setting for your whole business, real payments included, so switching it on takes a live key or the dashboard. When you're ready:

  1. Run npx @sharepay/cli connect --live (your business must be verified). It replaces the test key in your environment file with a live one. Your signing secret stays the same. (There is one signing secret for test and live, so keep test machines as safe as live ones.)
  2. Put the new secret key on your host and deploy.
  3. Run npx @sharepay/cli check https://yourshop.com again. This time it saves the addresses and switches AI ordering on.

Or save the two addresses and tick Take orders from AI assistants in the dashboard, under Developers, AI ordering.

Writing the two functions​

import { createSharePay, OrderRefused } from "@sharepay/node";
import { db } from "./db"; // your own database

export const ai = createSharePay().agentOrdering({
async listProducts() {
const rows = await db.product.findMany({ where: { active: true } });
return {
products: rows.map((p) => ({
id: p.id,
name: p.name,
description: p.description,
pricePence: p.pricePence,
inStock: p.stock > 0,
images: p.imageUrl ? [p.imageUrl] : [],
})),
delivery_options: [
{ id: "standard", name: "Standard (2 to 4 days)", pricePence: 395, freeOverPence: 4000 },
{ id: "express", name: "Express (next day)", pricePence: 795 },
],
discount_codes: true,
};
},

async priceOrder(order) {
// Use the same pricing code as your website's checkout.
const basket = await priceBasket({
items: order.items, // [{ id, qty, choice? }]
delivery: order.delivery_option ?? "standard",
code: order.discount_code, // checked by your code, not SharePay
});
if (basket.error) throw new OrderRefused(basket.error.code, basket.error.message);

const saved = await db.order.create({
data: {
status: "pending",
totalPence: basket.totalPence,
email: order.customer.email,
name: order.customer.name,
address: order.customer.address,
sharepayRequest: order.request_id,
},
});
return {
totalPence: basket.totalPence,
orderReference: saved.reference,
returnUrl: `https://yourshop.com/orders/${saved.id}`,
// Optional. Must add up exactly to totalPence: each pricePence is the
// line total, and delivery and discounts are lines of their own.
lineItems: [
...basket.lines.map((l) => ({ description: l.name, quantity: l.qty, pricePence: l.lineTotalPence })),
...(basket.deliveryPence ? [{ description: "Delivery", pricePence: basket.deliveryPence }] : []),
...(basket.discountPence ? [{ description: "Discount", pricePence: -basket.discountPence }] : []),
],
};
},

// Optional: answers a retried order before priceOrder runs again.
onCheckoutCreated: (requestId, url) => db.aiOrder.create({ data: { requestId, url } }),
findCheckout: async (requestId) => (await db.aiOrder.findUnique({ where: { requestId } }))?.url,
});
  • Never trust a price from outside. None is sent: order.items only names products and quantities. Price them from your own database.
  • Refuse with OrderRefused. Its message reaches the customer through the assistant, for example "SUMMER10 has expired." Any other error becomes a general "couldn't take the order" message, and your internal details stay private.
  • Retries are safe. If SharePay sends the same request_id again, the SDK asks SharePay with the same idempotency key and gets the same checkout back. priceOrder would run again, though, so give findCheckout (as above) or look the request_id up yourself, so you don't save two pending orders.
  • lineItems must add up to totalPence. If they don't, the order is refused and your log says why.
  • Fulfil on the checkout_split.paid webhook, as for any other SharePay order. Until then the order is only pending.

Express​

import express from "express";
import { sharepayRouter } from "./sharepay-routes"; // created by the command

const app = express();
app.use(sharepayRouter); // before any app-wide express.json()

The checkout route reads the raw body (express.text), because the signature covers exactly what SharePay sent. If an app-wide JSON parser runs first, the handler stops with a clear error instead of guessing.

By hand​

If you don't use Node, build the two addresses yourself from AI ordering: the product list format, the checkout format, and Checking the signature. Create your signing secret under Developers, AI ordering, serve the domain-proof line shown there, then save both addresses and switch it on. The same checks run before it switches on. Or run npx @sharepay/cli check https://yourshop.com with SHAREPAY_SECRET_KEY set, so the same safety checks run first.

Keeping it safe​

  • Both secrets stay on your server: in your host's environment settings and your local environment file, never in browser code, never committed. @sharepay/node refuses to load in a browser.
  • Every request from SharePay is signed with your signing secret, over the method, address and body, with a timestamp and a one-time value. The SDK refuses anything unsigned, wrongly signed, older than five minutes or repeated, before your code runs.
  • Running more than one server? Give the SDK a shared store for one-time values (see the @sharepay/node README), so a repeat sent to another server is caught too.
  • SharePay only calls https addresses on your own domain, on the normal port, never follows redirects, and only accepts a checkout your own key created. Before AI ordering switches on, your site must show the domain-proof line, so nobody can point SharePay at a website that isn't theirs.
  • Think a secret has leaked? Revoke the key under Developers, API keys, and choose Replace signing secret under AI ordering. Then run connect again, or update both values on your host.

Troubleshooting​

What the check saysWhat to do
"answered 200 to a request that had no SharePay signature"Your address isn't checking the signature first. Use the @sharepay/node handlers, or check the signature before anything else.
"didn't answer a signed SharePay request"The product list address isn't deployed, or SHAREPAY_SIGNING_SECRET on your host doesn't match. Run connect again to see it.
"Prove you run yourshop.com"Serve the line it shows as plain text at /.well-known/sharepay.txt on your site, deploy, and check again.
"That code doesn't match"Type the code your terminal shows, not one from anywhere else.
"The address must be on yourshop.com"Set your allowed return domain under Developers to your shop's domain.
"A live key needs your business verified first"Use test mode until your business is verified.
"All checks passed. To switch AI ordering on..."You used a test key. Switch it on with a live key or in the dashboard.
"You no longer have permission to connect this business"Ask the business owner for the right role, then run connect again.