Blog/Category
Shipping Tips & Tricks

Stripe Checkout to Shipping Label: The Webhook Flow in Next.js

November 26, 2026
Founder and CEO
Stripe Checkout to Shipping Label: The Webhook Flow in Next.js

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.

How does Stripe Checkout turn into a shipping label?

One route, app/api/stripe/webhook/route.ts. Stripe calls it when a customer pays. The route does 6 things:

  1. Verifies the Stripe signature against the raw body.
  2. Skips sessions that aren't paid yet.
  3. Creates a Ship.com order with external_order_id set to the Checkout Session ID.
  4. Rates the order with get_rates and picks the cheapest rate.
  5. Previews the label with buy_label and confirm: false, then buys with confirm: true and max_cost.
  6. Stores the tracking number, tracking URL and label URL.

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.

Which environment variables do you need?

VariableWhat it is
STRIPE_SECRET_KEYYour Stripe secret key
STRIPE_WEBHOOK_SECRETThe signing secret for this webhook endpoint
SHIPCOM_TOKENYour Ship.com connection key, from app.ship.com > Settings > API Integration. It starts with OAUTH2. and lasts 180 days
MAX_LABEL_COSTYour 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.

Why buy through MCP and not a REST call?

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.

What does the route handler look like?

// 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);
}

Why does the raw body matter?

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.

Which Stripe events should you handle?

EventWhen it firesWhat the route does
checkout.session.completedThe customer finishes CheckoutBuys the label if payment_status is paid or no_payment_required
checkout.session.async_payment_succeededA delayed method such as ACH clears laterBuys the label
checkout.session.async_payment_failedA delayed payment failsNothing 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.

Where is the shipping address in the Checkout Session?

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.

How does this survive Stripe retries?

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.

  • The Ship.com order is keyed on the Session ID through 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.
  • If any step throws, the route returns 500 and Stripe tries again. Every step is safe to repeat.

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.

What can go wrong on the Ship.com side?

  • "rate_id is invalid or has expired. Call get_rates again and use a fresh rate_id." Re-rate and try again.
  • A destination that fails validation. get_rates tells you to fix it with update_order_address. Flag it for a human.
  • "Refusing to buy: rate is $<price> which exceeds max_cost $<max>. Nothing was purchased." Hold the order for a human.
  • HTTP 429 over 60 requests per minute per token, with Retry-After: 60.
  • A clean preview can still fail on confirm. The preview doesn't check billing, plan limits, ship date or address.

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.

Can an ops agent use the same tools?

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.

Frequently asked questions

How do I verify a Stripe webhook signature in the Next.js App Router?

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.

Where is the shipping address in a Stripe Checkout Session?

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.

How do I avoid buying two labels when Stripe retries a webhook?

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.

Can I buy a shipping label without the customer's USPS account?

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.

Build with the Ship.com API

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.

Get your API key

Create a Ship.com account

References

  • Next.js: route.ts: POST handlers, request.text() for webhooks, no bodyParser, runtime = 'nodejs' (accessed November 2026)
  • Stripe: fulfill orders: the two events, payment_status, repeat and concurrent calls per Session (accessed November 2026)
  • Stripe changelog: shipping_details moved: collected_information.shipping_details, Node SDK v18.0.0 (accessed November 2026)
  • Stripe: webhooks: raw body, 5-minute tolerance, retries for 3 days, duplicate events, quick 2xx (accessed November 2026)
  • stripe-node README: constructEvent() needs the raw body (accessed November 2026)
  • AI SDK: MCP tools: createMCPClient from @ai-sdk/mcp, HTTP transport with headers, calling execute directly, close() (accessed November 2026)
  • AI SDK: tool approvals: toolApproval and user-approval (accessed November 2026)
  • Vercel: AI SDK 7: v7 release, June 25, 2026 (accessed November 2026)
  • Ship.com MCP documentation: create_order, external_order_id, get_rates, buy_label preview and max_cost, error strings, rate limits, void rules (accessed November 2026)
Joe DiSorbo
About the author
Joe DiSorbo
Founder and CEO

Joe DiSorbo is the founder and CEO of Ship.com, the shipping platform that gives more than 10,000 business customers discounted USPS and UPS rates and simplifies logistics for ecommerce brands and software platforms. Before Ship.com, he founded and led Webgistix, an ecommerce technology and global fulfillment company that grew internationally before Rakuten acquired it in 2013. His background spans global operations, software development, finance and logistics, with experience across the United States and Asia. Joe holds undergraduate degrees in Economics and Geography, masters degrees in Finance and International Management, and is a graduate of Harvard Business School (OPM 41).

Shipping software built for online sellers

Ship.com saves you time and money, giving you more freedom to live your life.

  • No credit card required.
  • Up to 89% off USPS and up to 87% off UPS.
  • Connects with major e-commerce platforms.
  • Free home pickup. Skip the trip to the post office.
Try for free
UPS
UP TO 87% OFF
Daily Rates*
USPS
UP TO 89% OFF
Retail Prices*
Today's orders
Order #1042USPS Ground AdvantageReady
Order #1043UPS Ground SaverReady
Order #1044USPS Priority MailReady
★★★★★Trusted by 10,000+ business customers

More on this topic

See all