
Updated November 2026. Facts verified against vendor and carrier documentation; see references at the end.
To turn a Stripe Checkout payment into a shipping label in Next.js, add an App Router route handler that reads the raw body with request.text(), verifies it with stripe.webhooks.constructEvent, and handles checkout.session.completed and checkout.session.async_payment_succeeded. Read the address from collected_information.shipping_details. Then use the AI SDK's createMCPClient to call Ship.com's MCP tools: create the order keyed on the Session ID, rate it, preview the label and buy it under a max_cost cap.
One route, app/api/stripe/webhook/route.ts. Stripe calls it when a customer pays. The route does 6 things:
external_order_id set to the Checkout Session ID.get_rates and picks the cheapest rate.buy_label and confirm: false, then buys with confirm: true and max_cost.You'll need npm install stripe @ai-sdk/mcp. The current majors are stripe 23 and AI SDK 7, with @ai-sdk/mcp at 2.x.
| Variable | What it is |
|---|---|
STRIPE_SECRET_KEY | Your Stripe secret key |
STRIPE_WEBHOOK_SECRET | The signing secret for this webhook endpoint |
SHIPCOM_TOKEN | Your Ship.com connection key, from app.ship.com > Settings > API Integration. It starts with OAUTH2. and lasts 180 days |
MAX_LABEL_COST | Your postage ceiling in dollars |
None of these get a NEXT_PUBLIC_ prefix. That prefix ships the value to the browser. The route handler runs on the server, so it reads them from process.env. Ship.com's MCP endpoint also refuses browser requests from other websites, so the key only works from server code anyway.
Stripe may deliver the same webhook more than once, and the MCP tools are built for that. create_order takes external_order_id, so "a retry or re-import returns the existing order instead of creating a duplicate." buy_label previews by default, refuses anything over max_cost, and returns the existing label without charging if the order already has one.
The AI SDK's createMCPClient connects over HTTP with a Bearer header. You don't need a model in the loop. Each MCP tool has an execute function you can call directly, and without an output schema it returns the raw MCP result.
// app/api/stripe/webhook/route.ts
import Stripe from "stripe";
import { createMCPClient } from "@ai-sdk/mcp";
export const runtime = "nodejs";
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
const MAX_LABEL_COST = Number(process.env.MAX_LABEL_COST ?? "15"); // dollars, postage only
const WEIGHT_OZ = 12; // map your product weights here (ounces)
export async function POST(request: Request) {
const body = await request.text(); // raw body, never request.json()
const signature = request.headers.get("stripe-signature");
let event: Stripe.Event;
try {
event = stripe.webhooks.constructEvent(body, signature!, process.env.STRIPE_WEBHOOK_SECRET!);
} catch {
return new Response("Bad signature", { status: 400 });
}
if (
event.type === "checkout.session.completed" ||
event.type === "checkout.session.async_payment_succeeded"
) {
const session = event.data.object as Stripe.Checkout.Session;
if (session.payment_status !== "unpaid") {
try {
await shipSession(session);
} catch (err) {
console.error(err);
return new Response("Retry later", { status: 500 }); // safe: every step is idempotent
}
}
}
return new Response("ok", { status: 200 });
}
async function shipSession(session: Stripe.Checkout.Session) {
const ship = session.collected_information?.shipping_details;
const a = ship?.address;
if (!ship || !a || a.country !== "US") {
console.log(`Session ${session.id}: no US address, ship it by hand`);
return;
}
const mcp = await createMCPClient({
transport: {
type: "http",
url: "https://app.ship.com/mcp",
headers: { Authorization: `Bearer ${process.env.SHIPCOM_TOKEN}` },
},
});
try {
const tools = await mcp.tools();
const call = async (name: string, args: Record<string, unknown>) => {
const res: any = await tools[name].execute(args, {
messages: [],
toolCallId: `${name}-${session.id}`,
});
if (res.isError) throw new Error(res.content?.[0]?.text ?? `${name} failed`);
return res.structuredContent ?? JSON.parse(res.content[0].text);
};
const order = await call("create_order", {
ship_to: {
name: ship.name,
street1: a.line1,
street2: a.line2 ?? undefined,
city: a.city,
state: a.state,
zip: a.postal_code?.slice(0, 5), // Ship.com takes 5-digit ZIPs
country: "US",
},
items: [{ name: "Online order", quantity: 1 }], // map your line items here
weight_oz: WEIGHT_OZ,
external_order_id: session.id, // Stripe retries return this same order
});
const quote = await call("get_rates", { order_id: order.order_id, weight_oz: WEIGHT_OZ });
if (!quote.rates?.length) {
console.log(`Order ${order.order_id}: no rates returned, needs a human`);
return; // don't throw: a 500 makes Stripe retry for days
}
const cheapest = [...quote.rates].sort((x, y) => x.rate - y.rate)[0];
const label = {
order_id: order.order_id,
rate_id: cheapest.rate_id,
package_id: quote.package_id,
method: cheapest.method,
service_level: cheapest.service_level,
};
// Preview first. confirm false spends nothing.
const preview = await call("buy_label", { ...label, confirm: false });
if (preview.price > MAX_LABEL_COST) {
console.log(`Order ${order.order_id}: $${preview.price} is over the cap, needs a human`);
return;
}
// Buy, capped at the previewed price.
const bought = await call("buy_label", { ...label, max_cost: preview.price, confirm: true });
await saveShipment(session.id, bought.tracking_number, bought.tracking_url, bought.label_url);
} finally {
await mcp.close();
}
}
async function saveShipment(sessionId: string, trackingNumber: string, trackingUrl: string, labelUrl: string) {
// write to your database here, keyed on sessionId
console.log(sessionId, trackingNumber, trackingUrl, labelUrl);
}
Stripe signs the exact bytes it sends. The stripe-node README says you "must pass the raw request body, exactly as received from Stripe" to constructEvent(), and a parsed JSON body won't verify. In the App Router that's easy. The Next.js docs show await request.text() for webhooks, and unlike the Pages Router you don't need any bodyParser config. The Stripe libraries also check the timestamp, with a default tolerance of 5 minutes. Leave it alone, and don't set it to 0.
| Event | When it fires | What the route does |
|---|---|---|
checkout.session.completed | The customer finishes Checkout | Buys the label if payment_status is paid or no_payment_required |
checkout.session.async_payment_succeeded | A delayed method such as ACH clears later | Buys the label |
checkout.session.async_payment_failed | A delayed payment fails | Nothing to ship. Worth handling to notify the customer |
Stripe's own fulfillment sample fulfills on either of the first two and checks that payment_status isn't unpaid. Our route does the same. Stripe also says webhooks are required for fulfillment, because there's no guarantee the customer ever lands on your success page.
In session.collected_information.shipping_details. It has .name and .address with line1, line2, city, state, postal_code and country. Stripe moved it there in API version 2025-03-31.basil and removed the old top-level shipping_details from the Node SDK in v18.0.0. A lot of tutorials still read the old field. The event payload follows the API version on your account, so accounts pinned to an older version may still send the legacy shape.
To get an address at all, create the Checkout Session with shipping_address_collection turned on.
Stripe retries for up to 3 days in live mode and can send the same event more than once. Its docs also warn that fulfillment "might be called multiple times, possibly concurrently, for the same Checkout Session." Buying a label spends real money, so a duplicate webhook can't mean a duplicate label.
external_order_id. Two different Stripe events for one session still map to one order.buy_label on an order that already has a label returns the existing label without charging.There's one hole in this. Our docs note that simultaneous calls with the same external_order_id can still create a duplicate. If two deliveries can land at the same moment, add a unique constraint on the Session ID in your own database and claim the row before calling Ship.com.
Also, Stripe asks for a quick 2xx before slow work. Rating and buying take several calls. At volume, save the event, return 200, and buy the label from a background job.
get_rates tells you to fix it with update_order_address. Flag it for a human.Retry-After: 60.The full list is in our post on error handling for shipping agents. To undo a label, the cancel_shipping_label tool voids it within 29 days of the ship date. The refund goes to your postage balance, typically within about 14 days, and not at all if the carrier already scanned it.
Yes. Build it as a separate route and keep the model out of the webhook. Pass await mcp.tools() to generateText or streamText and gate the purchase with AI SDK 7's toolApproval:
toolApproval: { buy_label: "user-approval" }
The MCP client doesn't turn server hints into an approval policy for you, so set it yourself. For the pattern, see how to let an AI agent buy shipping labels safely.
In app/api/.../route.ts, export POST, read the body with await request.text() and pass it with the stripe-signature header and your endpoint secret to stripe.webhooks.constructEvent(). Don't call request.json() first, because a parsed body fails verification. The App Router needs no bodyParser config, unlike API Routes in the Pages Router.
Read session.collected_information.shipping_details, which has name and an address object. Stripe moved it there from the top-level shipping_details field in API version 2025-03-31.basil. Accounts or webhook endpoints pinned to an older API version can still receive the legacy field, so check your version if the new path comes back empty.
Key everything on the Checkout Session ID. Pass it to Ship.com's create_order as external_order_id so a retry returns the same order, and buy_label will return an existing label instead of charging again. Add a unique constraint on the Session ID in your database if two deliveries can arrive at the same time.
Yes. You don't need your own USPS account or eVS either. Ship.com buys postage from your Ship.com balance, and your server calls Ship.com with your connection key. Rates run up to 89% off USPS and up to 87% off UPS. Your customer only sees the tracking link you send them after the label is bought.
For the big picture, read the developer's guide to MCP and API for AI agents. Plan details are on our pricing page.
Turn every paid checkout into a USPS or UPS label at up to 89% off USPS and up to 87% off UPS. Sign up, copy your key from Settings, and add it to your server env. The REST reference is at ship.com/api/overview, the MCP reference is at ship.com/api/mcp, and API questions go to api-support@ship.com.
POST handlers, request.text() for webhooks, no bodyParser, runtime = 'nodejs' (accessed November 2026)payment_status, repeat and concurrent calls per Session (accessed November 2026)collected_information.shipping_details, Node SDK v18.0.0 (accessed November 2026)constructEvent() needs the raw body (accessed November 2026)createMCPClient from @ai-sdk/mcp, HTTP transport with headers, calling execute directly, close() (accessed November 2026)toolApproval and user-approval (accessed November 2026)create_order, external_order_id, get_rates, buy_label preview and max_cost, error strings, rate limits, void rules (accessed November 2026)