1 ---
2 sidebar_label: "Agentic Commerce"
3 tags:
4 - cart
5 - order
6 - server
7 - tutorial
8 products:
9 - cart
10 - customer
11 - order
12 - fulfillment
13 - payment
14 ---
15
16 import { Github, PlaySolid } from "@medusajs/icons"
17 import { Prerequisites, WorkflowDiagram, CardList } from "docs-ui"
18
19 export const metadata = {
20 title: `Implement Agentic Commerce (ChatGPT Instant Checkout) Specifications`,
21 }
22
23 # {metadata.title}
24
25 In this tutorial, you'll learn how to implement [Agentic Commerce](https://developers.openai.com/commerce) specifications in Medusa that allow you to sell through ChatGPT.
26
27 When you install a Medusa application, you get a fully-fledged commerce platform with the Framework for customization. The Medusa application's commerce features are built around [Commerce Modules](../../../commerce-modules/page.mdx), which are available out-of-the-box.
28
29 The [Agentic Commerce Protocol](https://developers.openai.com/commerce) supports instant checkout experiences within AI agents. By implementing Agentic Commerce specifications in your Medusa application, customers can purchase products through ChatGPT and other AI agents.
30
31 <Note>
32
33 Instant Checkout in ChatGPT is currently available in select regions and for select businesses. The implementation in this guide is based on OpenAI's [Agentic Commerce documentation](https://developers.openai.com/commerce) and may require some adjustments when you apply for [Instant Checkout](https://chatgpt.com/merchants).
34
35 </Note>
36
37 ## Summary
38
39 By following this tutorial, you will learn how to:
40
41 - Build a product feed matching the [Agentic Commerce specifications](https://developers.openai.com/commerce/specs/feed).
42 - Create [Agentic Checkout APIs](https://developers.openai.com/commerce/specs/checkout) that handle checkout requests from AI agents.
43 - Send webhook events to AI agents matching the [Agentic Commerce specifications](https://developers.openai.com/commerce/specs/webhooks).
44
45 By the end of this tutorial, you'll have all necessary resources to apply for [Instant Checkout](https://chatgpt.com/merchants) and start selling in ChatGPT. You can also sell through other AI agents that support the Agentic Commerce Protocol.
46
47 You can follow this tutorial whether you're new to Medusa or an advanced Medusa developer.
48
49 ![Diagram showing the Agentic Commerce integration between user, ChatGPT, and Medusa application](https://res.cloudinary.com/dza7lstvk/image/upload/v1759333742/Medusa%20Resources/agentic-commerce_jqr5wn.jpg)
50
51 <CardList items={[
52 {
53 href: "https://github.com/medusajs/examples/tree/main/agentic-commerce",
54 title: "Full Code",
55 text: "Find the full code for this guide in this repository.",
56 icon: Github,
57 },
58 {
59 href: "https://res.cloudinary.com/dza7lstvk/raw/upload/v1759332538/OpenApi/agentic-commerce-openapi_hvsioq.yaml",
60 title: "OpenApi Specs for Postman",
61 text: "Import this OpenApi Specs file into tools like Postman.",
62 icon: PlaySolid,
63 },
64 ]} />
65
66 ---
67
68 ## Step 1: Install a Medusa Application
69
70 <Prerequisites items={[
71 {
72 text: "Node.js v20.19.0+ or v22.12.0+",
73 link: "https://nodejs.org/en/download"
74 },
75 {
76 text: "Git CLI tool",
77 link: "https://git-scm.com/downloads"
78 },
79 {
80 text: "PostgreSQL",
81 link: "https://www.postgresql.org/download/"
82 }
83 ]} />
84
85 Begin by installing the Medusa application on your machine with the following command:
86
87 ```bash npx2yarnExec
88 npx create-medusa-app@latest
89 ```
90
91 You'll first be asked for the project's name. You can optionally choose to install the [Next.js Starter Storefront](../../../nextjs-starter/page.mdx) as well.
92
93 After that, the installation process will begin. This will install the Medusa application as a monorepository in a directory with your project's name. The backend is installed in the `apps/backend` directory. If you chose to install the Next.js Starter Storefront, it'll be in the `apps/storefront` directory.
94
95 Once the installation finishes successfully, the Medusa Admin dashboard will open with a form to create a new user. Enter the user's credentials and submit the form. Then, you can log in with the new user and explore the dashboard.
96
97 <Note title="Ran into Errors">
98
99 Check out the [troubleshooting guides](../../../troubleshooting/create-medusa-app-errors/page.mdx) for help.
100
101 </Note>
102
103 <Note>
104
105 In this guide, all file paths of backend customizations are relative to the `apps/backend` directory of your Medusa project.
106
107 </Note>
108
109 ---
110
111 ## Step 2: Create Agentic Commerce Module
112
113 To integrate third-party services into Medusa, you create a custom module. A module is a reusable package with functionalities related to a single feature or domain. Medusa integrates the module into your application without implications or side effects on your setup.
114
115 In this step, you'll create a module that integrates with an AI agent through the Agentic Commerce Protocol. This module is useful to send the product feed and webhook events to the AI agent.
116
117 <Note>
118
119 Refer to the [Modules documentation](!docs!/learn/fundamentals/modules) to learn more.
120
121 </Note>
122
123 ### a. Create Module Directory
124
125 A module is created under the `src/modules` directory of your Medusa application. So, create the directory `src/modules/agentic-commerce`.
126
127 ### b. Create Module Service
128
129 You define a module's functionalities in a service. A service is a TypeScript or JavaScript class that the module exports. In the service's methods, you can connect to the database (useful if your module defines database tables) or connect to third-party services.
130
131 In this section, you'll create the Agentic Commerce Module's service and the methods necessary to interact with the Agentic Commerce Protocol.
132
133 To create the service, create the file `src/modules/agentic-commerce/service.ts` with the following content:
134
135 ```ts title="src/modules/agentic-commerce/service.ts"
136 type ModuleOptions = {
137 // TODO add module options like API key, etc.
138 signatureKey: string
139 }
140
141 export default class AgenticCommerceService {
142 options: ModuleOptions
143 constructor({}, options: ModuleOptions) {
144 this.options = options
145 // TODO initialize client
146 }
147 }
148 ```
149
150 The service's constructor receives two parameters:
151
152 - The [Module's container](!docs!/learn/fundamentals/modules/container) that allows you to resolve Framework tools.
153 - The module's options that you'll later pass when registering the module in the Medusa application. You can add more options based on your integration.
154
155 If you're connecting to AI agents through an SDK or API client, you can initialize it in the constructor.
156
157 #### sendProductFeed Method
158
159 Next, you'll add the `sendProductFeed` method to the service. This method sends the [product feed](https://developers.openai.com/commerce/specs/feed) to AI agents, allowing them to search and display your products.
160
161 Add the following method to the `AgenticCommerceService` class:
162
163 ```ts title="src/modules/agentic-commerce/service.ts"
164 export default class AgenticCommerceService {
165 // ...
166 async sendProductFeed(productFeed: string) {
167 // TODO send product feed
168 console.log(`Synced product feed ${productFeed}`)
169 }
170 }
171 ```
172
173 OpenAI hasn't publicly published the endpoint for sending product feeds. So, in this method, you'll just log the product feed URL to the console.
174
175 When you apply for [Instant Checkout](https://chatgpt.com/merchants), you'll get access to the endpoint and can implement the logic to send the product feed in this method.
176
177 <Note>
178
179 You'll implement the logic to create product feeds later.
180
181 </Note>
182
183 #### verifySignature Method
184
185 Next, you'll add the `verifySignature` method to the service. This method verifies signatures of requests sent by AI agents to Agentic Checkout APIs that you'll create later.
186
187 Add the following import at the top of the `src/modules/agentic-commerce/service.ts` file:
188
189 ```ts title="src/modules/agentic-commerce/service.ts"
190 import crypto from "crypto"
191 ```
192
193 Then, add the following method to the `AgenticCommerceService` class:
194
195 ```ts title="src/modules/agentic-commerce/service.ts"
196 export default class AgenticCommerceService {
197 // ...
198 async verifySignature({
199 signature,
200 payload,
201 }: {
202 // base64 encoded signature
203 signature: string
204 payload: any
205 }) {
206 try {
207 // Decode the base64 signature
208 const receivedSignature = Buffer.from(signature, "base64")
209
210 // Create HMAC-SHA256 signature using your signing key
211 const expectedSignature = crypto
212 .createHmac("sha256", this.options.signatureKey)
213 .update(JSON.stringify(payload), "utf8")
214 .digest()
215
216 // Compare signatures using constant-time comparison to prevent timing attacks
217 return crypto.timingSafeEqual(receivedSignature, expectedSignature)
218 } catch (error) {
219 console.error("Signature verification failed:", error)
220 return false
221 }
222 }
223 }
224 ```
225
226 This method receives request signatures and payloads, then verifies signatures using HMAC-SHA256 with the module's `signatureKey` option.
227
228 When you apply for [Instant Checkout](https://chatgpt.com/merchants), you'll receive a signature key for verifying request signatures. You can set this key in the module's options.
229
230 #### getSignature Method
231
232 Next, you'll add the `getSignature` method to the service. This method generates a base64 signature for a payload in the same format that AI agents use for inbound requests, which is useful to test the checkout APIs locally.
233
234 Add the following method to the `AgenticCommerceService` class:
235
236 ```ts title="src/modules/agentic-commerce/service.ts"
237 export default class AgenticCommerceService {
238 // ...
239 async getSignature(data: any) {
240 return Buffer.from(crypto.createHmac("sha256", this.options.signatureKey)
241 .update(JSON.stringify(data), "utf8").digest()).toString("base64")
242 }
243 }
244 ```
245
246 This method receives a payload and generates a signature using HMAC-SHA256 with the module's `signatureKey` option.
247
248 #### sendWebhookEvent Method
249
250 Finally, you'll add the `sendWebhookEvent` method to the service. This method sends webhook events to AI agents.
251
252 First, add the following type at the top of the `src/modules/agentic-commerce/service.ts` file:
253
254 ```ts title="src/modules/agentic-commerce/service.ts"
255 export type AgenticCommerceWebhookEvent = {
256 type: "order_create" | "order_update"
257 data: {
258 type: "order"
259 id: string
260 checkout_session_id: string
261 permalink_url: string
262 status: "created" | "manual_review" |
263 "confirmed" | "processing" | "shipped" |
264 "completed" | "canceled"
265 adjustments: {
266 id: string
267 type: "refund"
268 occurred_at: string
269 status: "completed"
270 amount?: number
271 }[]
272 }
273 }
274 ```
275
276 This type defines the structure of webhook events that you can send to AI agents based on the [ACP `2026-04-17` webhook schema](https://github.com/agentic-commerce-protocol/agentic-commerce-protocol/blob/main/spec/2026-04-17/openapi/openapi.agentic_checkout_webhook.yaml).
277
278 Then, add the following method to the `AgenticCommerceService` class:
279
280 ```ts title="src/modules/agentic-commerce/service.ts"
281 export default class AgenticCommerceService {
282 // ...
283 getWebhookSignature(
284 rawBody: string,
285 timestamp = Math.floor(Date.now() / 1000)
286 ) {
287 const digest = crypto
288 .createHmac("sha256", this.options.signatureKey)
289 .update(`${timestamp}.${rawBody}`, "utf8")
290 .digest("hex")
291
292 return `t=${timestamp},v1=${digest}`
293 }
294 }
295 ```
296
297 Outbound webhook events use a different signature format than inbound requests. This method builds the `Merchant-Signature` header value that the ACP `2026-04-17` release expects, which is a hexadecimal HMAC-SHA256 digest of the timestamp and the raw request body, joined by a period.
298
299 <Note title="Tip">
300
301 Sign the exact raw body string that you send in the request, not a re-serialized copy of the payload. Any difference in key order or whitespace produces a different digest that the receiver can't verify.
302
303 </Note>
304
305 Finally, add the following method to the `AgenticCommerceService` class:
306
307 ```ts title="src/modules/agentic-commerce/service.ts"
308 export default class AgenticCommerceService {
309 // ...
310 async sendWebhookEvent({
311 type,
312 data,
313 }: AgenticCommerceWebhookEvent) {
314 const rawBody = JSON.stringify({ type, data })
315 const signature = this.getWebhookSignature(rawBody)
316 // TODO send order webhook event
317 console.log(
318 `Prepared order webhook event ${type} with Merchant-Signature ${signature}`
319 )
320 }
321 }
322 ```
323
324 This method receives webhook event types and data, serializes the payload once, signs that exact string using the `getWebhookSignature` method, and logs events to the console.
325
326 When you apply for [Instant Checkout](https://chatgpt.com/merchants), you'll get access to endpoints for sending webhook events and can implement the logic in this method.
327
328 ### c. Export Module Definition
329
330 The final piece of a module is its definition, which you export in an `index.ts` file at the root directory. This definition tells Medusa the module name and its service.
331
332 So, create the file `src/modules/agentic-commerce/index.ts` with the following content:
333
334 ```ts title="src/modules/agentic-commerce/index.ts"
335 import AgenticCommerceService from "./service"
336 import { Module } from "@medusajs/framework/utils"
337
338 export const AGENTIC_COMMERCE_MODULE = "agenticCommerce"
339
340 export default Module(AGENTIC_COMMERCE_MODULE, {
341 service: AgenticCommerceService,
342 })
343 ```
344
345 You use the `Module` function from the Modules SDK to create module definitions. It accepts two parameters:
346
347 1. The module name, which is `agenticCommerce`.
348 2. An object with a required `service` property indicating the module's service.
349
350 You also export the module name as `AGENTIC_COMMERCE_MODULE` for later reference.
351
352 ### d. Add Module to Medusa's Configurations
353
354 Once you finish building the module, add it to Medusa's configurations to start using it.
355
356 In `medusa-config.ts`, add a `modules` property and pass an array with your custom module:
357
358 ```ts title="medusa-config.ts"
359 module.exports = defineConfig({
360 // ...
361 modules: [
362 {
363 resolve: "./src/modules/agentic-commerce",
364 options: {
365 signatureKey: process.env.AGENTIC_COMMERCE_SIGNATURE_KEY || "supersecret",
366 },
367 },
368 ],
369 })
370 ```
371
372 Each object in the `modules` array has a `resolve` property, whose value is either a path to the module's directory, or an `npm` package’s name.
373
374 You also pass an `options` property with module options, including the signature key. Once you receive a signature key from OpenAI, you can set it in the `AGENTIC_COMMERCE_SIGNATURE_KEY` environment variable.
375
376 Your module is now ready for use. You'll build workflows around it in the following steps.
377
378 ---
379
380 ## Step 3: Send Product Feed
381
382 In this step, you'll create logic to generate and send product feeds matching [Agentic Commerce specifications](https://developers.openai.com/commerce/specs/feed). These feeds provide AI agents with product information, allowing them to search and display products to customers. Customers can then purchase products through AI agents.
383
384 You'll implement:
385
386 - A [workflow](!docs!/learn/fundamentals/workflows) that generates and sends the product feed.
387 - A [scheduled job](!docs!/learn/fundamentals/scheduled-jobs) that executes the workflow every fifteen minutes. This is the maximum frequency OpenAI allows for product feed updates.
388
389 ### a. Send Product Feed Workflow
390
391 A workflow is a series of actions called steps that complete a task. You construct workflows like functions, but they're special functions that allow you to track execution progress, define rollback logic, and configure advanced features.
392
393 <Note>
394
395 Learn more about workflows in the [Workflows documentation](!docs!/learn/fundamentals/workflows).
396
397 </Note>
398
399 The workflow for sending product feeds will have the following steps:
400
401 <WorkflowDiagram
402 workflow={{
403 name: "sendProductFeedWorkflow",
404 steps: [
405 {
406 type: "step",
407 name: "getProductFeedItemsStep",
408 description: "Get items to include in the product feed",
409 depth: 1
410 },
411 {
412 type: "step",
413 name: "buildProductFeedXmlStep",
414 description: "Generate product feed XML",
415 depth: 2
416 },
417 {
418 type: "step",
419 name: "sendProductFeedStep",
420 description: "Send product feed to AI agent",
421 depth: 3
422 }
423 ]
424 }}
425 />
426
427 #### getProductFeedItemsStep
428
429 The `getProductFeedItemsStep` step retrieves product variants to include in the product feed.
430
431 To create the step, create the file `src/workflows/steps/get-product-feed-items.ts` with the following content:
432
433 export const getProductFeedItemsStepHighlights1 = [
434 ["5", "FeedItem", "The structure of a product feed item."],
435 ["39", "formatPrice", "Utility function to format a price in a given currency."],
436 ]
437
438 ```ts title="src/workflows/steps/get-product-feed-items.ts" highlights={getProductFeedItemsStepHighlights1}
439 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
440 import { getVariantAvailability, QueryContext } from "@medusajs/framework/utils"
441 import { CalculatedPriceSet, ShippingOptionDTO } from "@medusajs/framework/types"
442
443 export type FeedItem = {
444 id: string
445 title: string
446 description: string
447 link: string
448 image_link?: string
449 additional_image_link?: string
450 availability: string
451 inventory_quantity: number
452 price: string
453 sale_price?: string
454 item_group_id: string
455 item_group_title: string
456 gtin?: string
457 condition?: string
458 brand?: string
459 product_category?: string
460 material?: string
461 weight?: string
462 color?: string
463 size?: string
464 seller_name: string
465 seller_url: string
466 seller_privacy_policy: string
467 seller_tos: string
468 return_policy: string
469 return_window?: number
470 }
471
472 type StepInput = {
473 currency_code: string
474 country_code: string
475 }
476
477 const formatPrice = (price: number, currency_code: string) => {
478 return `${new Intl.NumberFormat("en-US", {
479 currency: currency_code,
480 minimumFractionDigits: 2,
481 maximumFractionDigits: 2,
482 }).format(price)} ${currency_code.toUpperCase()}`
483 }
484
485 export const getProductFeedItemsStep = createStep(
486 "get-product-feed-items",
487 async (input: StepInput, { container }) => {
488 // TODO implement step
489 }
490 )
491 ```
492
493 You define the `FeedItem` type that matches the structure of an item in the product feed. You also define the `StepInput` type that includes the input parameters for the step, which are the currency and country codes.
494
495 Then, you define the `formatPrice` utility function that formats a price in a given currency. This is the format required by the Agentic Commerce specifications.
496
497 Finally, you create a step with `createStep` from the Workflows SDK. It accepts two parameters:
498
499 1. The step's unique name, which is `get-product-feed-items`.
500 2. An async function that receives two parameters:
501 - The step's input.
502 - An object that has properties including the [Medusa container](!docs!/learn/fundamentals/medusa-container), which is a registry of Framework and commerce tools that you can access in the step.
503
504 Next, you'll implement the step's logic. Replace the step implementation with the following:
505
506 ```ts title="src/workflows/steps/get-product-feed-items.ts"
507 export const getProductFeedItemsStep = createStep(
508 "get-product-feed-items",
509 async (input: StepInput, { container }) => {
510 const feedItems: FeedItem[] = []
511 const query = container.resolve(
512 ContainerRegistrationKeys.QUERY
513 )
514 const configModule = container.resolve(
515 ContainerRegistrationKeys.CONFIG_MODULE
516 )
517 const storefrontUrl = configModule.admin.storefrontUrl ||
518 process.env.STOREFRONT_URL
519
520 const limit = 100
521 let offset = 0
522 let count = 0
523 const countryCode = input.country_code.toLowerCase()
524 const currencyCode = input.currency_code.toLowerCase()
525
526 do {
527 const {
528 data: products,
529 metadata,
530 } = await query.graph({
531 entity: "product",
532 fields: [
533 "id",
534 "title",
535 "description",
536 "handle",
537 "thumbnail",
538 "images.*",
539 "status",
540 "variants.*",
541 "variants.calculated_price.*",
542 "sales_channels.*",
543 "sales_channels.stock_locations.*",
544 "sales_channels.stock_locations.address.*",
545 "categories.*",
546 ],
547 filters: {
548 status: "published",
549 },
550 context: {
551 variants: {
552 calculated_price: QueryContext({
553 currency_code: currencyCode,
554 }),
555 },
556 },
557 pagination: {
558 take: limit,
559 skip: offset,
560 },
561 })
562
563 count = metadata?.count ?? 0
564 offset += limit
565
566 for (const product of products) {
567 if (!product.variants.length) {continue}
568 const salesChannel = product.sales_channels?.find((channel) => {
569 return channel?.stock_locations?.some((location) => {
570 return location?.address?.country_code.toLowerCase() === countryCode
571 })
572 })
573
574 const availability = salesChannel?.id ? await getVariantAvailability(query, {
575 variant_ids: product.variants.map((variant) => variant.id),
576 sales_channel_id: salesChannel?.id,
577 }) : undefined
578
579 const categories = product.categories?.map((cat) => cat?.name)
580 .filter((name): name is string => !!name).join(">")
581
582 for (const variant of product.variants) {
583 // @ts-ignore
584 const calculatedPrice = variant.calculated_price as CalculatedPriceSet
585 const hasOriginalPrice =
586 calculatedPrice?.original_amount !== calculatedPrice?.calculated_amount
587 const originalPrice = hasOriginalPrice ?
588 calculatedPrice.original_amount : calculatedPrice.calculated_amount
589 const salePrice = hasOriginalPrice ?
590 calculatedPrice.calculated_amount : undefined
591 const stockStatus = !variant.manage_inventory ? "in stock" :
592 !availability?.[variant.id]?.availability ? "out of stock" : "in stock"
593 const inventoryQuantity = !variant.manage_inventory ?
594 100000 : availability?.[variant.id]?.availability || 0
595 const color = variant.options?.find(
596 (o) => o.option?.title.toLowerCase() === "color"
597 )?.value
598 const size = variant.options?.find(
599 (o) => o.option?.title.toLowerCase() === "size"
600 )?.value
601
602 feedItems.push({
603 id: variant.id,
604 title: product.title,
605 description: product.description ?? "",
606 link: `${storefrontUrl || ""}/${input.country_code}/${product.handle}`,
607 image_link: product.thumbnail ?? "",
608 additional_image_link: product.images?.map(
609 (image) => image.url
610 )?.join(","),
611 availability: stockStatus,
612 inventory_quantity: inventoryQuantity,
613 price: formatPrice(originalPrice as number, currencyCode),
614 sale_price: salePrice ?
615 formatPrice(salePrice as number, currencyCode) : undefined,
616 item_group_id: product.id,
617 item_group_title: product.title,
618 gtin: variant.upc || undefined,
619 condition: "new", // TODO add condition if supported
620 product_category: categories,
621 material: variant.material || undefined,
622 weight: `${variant.weight || 0} kg`,
623 brand: "", // TODO add brands if supported
624 color: color || undefined,
625 size: size || undefined,
626 seller_name: "Medusa", // TODO add seller name if supported
627 seller_url: storefrontUrl || "",
628 seller_privacy_policy: `${storefrontUrl}/privacy-policy`, // TODO update
629 seller_tos: `${storefrontUrl}/terms-of-service`, // TODO update
630 return_policy: `${storefrontUrl}/return-policy`, // TODO update
631 return_window: 0, // TODO update
632 })
633 }
634 }
635 } while (count > offset)
636
637 return new StepResponse({ items: feedItems })
638 })
639 ```
640
641 In the step, you:
642
643 1. Retrieve products with pagination using [Query](!docs!/learn/fundamentals/query). Query allows you to retrieve data across modules. You retrieve the fields necessary for the product field.
644 2. For each product, you loop over its variants to add them to the product feed. You add information related to pricing, availability, and other attributes.
645 - Some of the fields are hardcoded or left empty. You can update them based on your setup.
646 - For more information on the fields, refer to the [Product Feed specifications](https://developers.openai.com/commerce/specs/feed).
647
648 Finally, a step function must return a `StepResponse` instance. You return the list of feed items in the response.
649
650 #### buildProductFeedXmlStep
651
652 Next, you'll create the step that generates the product feed XML from the feed items.
653
654 To create the step, create the file `src/workflows/steps/build-product-feed-xml.ts` with the following content:
655
656 ```ts title="src/workflows/steps/build-product-feed-xml.ts"
657 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
658 import { FeedItem } from "./get-product-feed-items"
659
660 type StepInput = {
661 items: FeedItem[]
662 }
663
664 export const buildProductFeedXmlStep = createStep(
665 "build-product-feed-xml",
666 async (input: StepInput) => {
667 const escape = (str: string) =>
668 str
669 .replace(/&/g, "&amp;")
670 .replace(/</g, "&lt;")
671 .replace(/>/g, "&gt;")
672 .replace(/\"/g, "&quot;")
673 .replace(/'/g, "&apos;")
674
675 const itemsXml = input.items.map((item) => {
676 return (
677 `<item>` +
678 // Flags
679 `<enable_search>true</enable_search>` +
680 `<enable_checkout>true</enable_checkout>` +
681 // Product Variant Fields
682 `<id>${escape(item.id)}</id>` +
683 `<title>${escape(item.title)}</title>` +
684 `<description>${escape(item.description)}</description>` +
685 `<link>${escape(item.link)}</link>` +
686 `<gtin>${escape(item.gtin || "")}</gtin>` +
687 (item.image_link ? `<image_link>${escape(item.image_link)}</image_link>` : "") +
688 (item.additional_image_link ? `<additional_image_link>${escape(item.additional_image_link)}</additional_image_link>` : "") +
689 `<availability>${escape(item.availability)}</availability>` +
690 `<inventory_quantity>${item.inventory_quantity}</inventory_quantity>` +
691 `<price>${escape(item.price)}</price>` +
692 (item.sale_price ? `<sale_price>${escape(item.sale_price)}</sale_price>` : "") +
693 `<condition>${escape(item.condition || "new")}</condition>` +
694 `<product_category>${escape(item.product_category || "")}</product_category>` +
695 `<brand>${escape(item.brand || "Medusa")}</brand>` +
696 `<material>${escape(item.material || "")}</material>` +
697 `<weight>${escape(item.weight || "")}</weight>` +
698 `<item_group_id>${escape(item.item_group_id)}</item_group_id>` +
699 `<item_group_title>${escape(item.item_group_title)}</item_group_title>` +
700 `<size>${escape(item.size || "")}</size>` +
701 `<color>${escape(item.color || "")}</color>` +
702 `<seller_name>${escape(item.seller_name)}</seller_name>` +
703 `<seller_url>${escape(item.seller_url)}</seller_url>` +
704 `<seller_privacy_policy>${escape(item.seller_privacy_policy)}</seller_privacy_policy>` +
705 `<seller_tos>${escape(item.seller_tos)}</seller_tos>` +
706 `<return_policy>${escape(item.return_policy)}</return_policy>` +
707 `<return_window>${item.return_window}</return_window>` +
708 `</item>`
709 )
710 }).join("")
711
712 const xml =
713 `<?xml version="1.0" encoding="UTF-8"?>` +
714 `<rss version="2.0" xmlns:g="http://base.google.com/ns/1.0">` +
715 `<channel>` +
716 `<title>Product Feed</title>` +
717 `<description>Product Feed for Agentic Commerce</description>` +
718 itemsXml +
719 `</channel>` +
720 `</rss>`
721
722 return new StepResponse(xml)
723 }
724 )
725 ```
726
727 This step receives the list of feed items as input.
728
729 In the step, you loop over the feed items and generate an XML string matching the [Agentic Commerce specifications](https://developers.openai.com/commerce/specs/feed). You escape special characters in the fields to ensure the XML is valid.
730
731 Finally, you return the XML string in a `StepResponse` instance.
732
733 #### sendProductFeedStep
734
735 The final step is `sendProductFeedStep`, which sends product feed XML to AI agents.
736
737 Create the file `src/workflows/steps/send-product-feed.ts` with the following content:
738
739 <Note>
740
741 If you get a type error on resolving the Agentic Commerce Module, run the Medusa application once with the `npm run dev` or `yarn dev` command to generate the necessary type definitions, as explained in the [Automatically Generated Types guide](!docs!/learn/fundamentals/generated-types).
742
743 </Note>
744
745 ```ts title="src/workflows/steps/send-product-feed.ts"
746 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
747 import { AGENTIC_COMMERCE_MODULE } from "../../modules/agentic-commerce"
748
749 type StepInput = {
750 productFeed: string
751 }
752
753 export const sendProductFeedStep = createStep(
754 "send-product-feed",
755 async (input: StepInput, { container }) => {
756 const agenticCommerceModuleService = container.resolve(
757 AGENTIC_COMMERCE_MODULE
758 )
759
760 await agenticCommerceModuleService.sendProductFeed(input.productFeed)
761
762 return new StepResponse(void 0)
763 }
764 )
765 ```
766
767 This step receives the product feed XML as input.
768
769 In the step, you resolve the Agentic Commerce Module's service from the Medusa container and call its `sendProductFeed` method to send the product feed to the AI agent.
770
771 #### Create Workflow
772
773 You can now create the workflow that uses the steps you created.
774
775 Create the file `src/workflows/send-product-feed.ts` with the following content:
776
777 ```ts title="src/workflows/send-product-feed.ts"
778 import { createWorkflow, WorkflowResponse } from "@medusajs/framework/workflows-sdk"
779 import { getProductFeedItemsStep } from "./steps/get-product-feed-items"
780 import { buildProductFeedXmlStep } from "./steps/build-product-feed-xml"
781 import { sendProductFeedStep } from "./steps/send-product-feed"
782
783 type GenerateProductFeedWorkflowInput = {
784 currency_code: string
785 country_code: string
786 }
787
788 export const sendProductFeedWorkflow = createWorkflow(
789 "send-product-feed",
790 (input: GenerateProductFeedWorkflowInput) => {
791 const { items: feedItems } = getProductFeedItemsStep(input)
792
793 const xml = buildProductFeedXmlStep({
794 items: feedItems,
795 })
796
797 sendProductFeedStep({
798 productFeed: xml,
799 })
800
801 return new WorkflowResponse({ xml })
802 }
803 )
804
805 export default sendProductFeedWorkflow
806 ```
807
808 You create a workflow using `createWorkflow` from the Workflows SDK. It accepts the workflow's unique name as a first parameter.
809
810 It accepts as a second parameter a constructor function, which is the workflow's implementation. The function can accept input, which in this case is the currency and country codes.
811
812 In the workflow, you:
813
814 1. Retrieve feed items using `getProductFeedItemsStep`.
815 2. Generate product feed XML using `buildProductFeedXmlStep`.
816 3. Send product feed to AI agents using `sendProductFeedStep`.
817
818 Finally, a workflow function must return a `WorkflowResponse` instance. You return the product feed XML in the response.
819
820 ### b. Schedule Job to Send Product Feed
821
822 Next, you'll create a [scheduled job](!docs!/learn/fundamentals/scheduled-jobs) that executes the `sendProductFeedWorkflow` every fifteen minutes. A scheduled job is an asynchronous function that the Medusa application runs at the interval you specify during the Medusa application's runtime.
823
824 Create the file `src/jobs/sync-product-feed.ts` with the following content:
825
826 ```ts title="src/jobs/sync-product-feed.ts"
827 import {
828 MedusaContainer,
829 } from "@medusajs/framework/types"
830 import sendProductFeedWorkflow from "../workflows/send-product-feed"
831 import {
832 ContainerRegistrationKeys,
833 } from "@medusajs/framework/utils"
834
835 export default async function syncProductFeed(container: MedusaContainer) {
836 const logger = container.resolve(
837 ContainerRegistrationKeys.LOGGER
838 )
839 const query = container.resolve(
840 ContainerRegistrationKeys.QUERY
841 )
842
843 const { data: regions } = await query.graph({
844 entity: "region",
845 fields: ["id", "currency_code", "countries.*"],
846 })
847
848 for (const region of regions) {
849 for (const country of region.countries) {
850 await sendProductFeedWorkflow(container).run({
851 input: {
852 currency_code: region.currency_code,
853 country_code: country!.iso_2,
854 },
855 })
856 }
857 }
858
859 logger.info("Product feed synced for all regions and countries")
860 }
861
862 export const config = {
863 name: "sync-product-feed",
864 schedule: "*/15 * * * *", // Every 15 minutes
865 }
866 ```
867
868 In a scheduled job file, you must export:
869
870 1. An asynchronous function that holds the job's logic. The function receives the [Medusa container](!docs!/learn/fundamentals/medusa-container) as a parameter.
871 2. A `config` object that specifies the job name and schedule. The schedule is a [cron expression](https://crontab.guru/) that defines the interval at which the job runs.
872
873 In the scheduled job function, you use Query to retrieve regions in your Medusa application, including their countries and currency codes.
874
875 Then, for each country in each region, you execute `sendProductFeedWorkflow`, passing the region's currency code and the country's ISO 2 code as input.
876
877 ### Use the Scheduled Job
878
879 To use the scheduled job, start the Medusa application with the following command:
880
881 ```bash npm2yarn
882 npm run dev
883 ```
884
885 This job runs every fifteen minutes. The current implementation only logs product feeds to the console. Once you apply for [Instant Checkout](https://chatgpt.com/merchants), you can implement logic to send product feeds in the `sendProductFeed` method of the Agentic Commerce Module's service.
886
887 ---
888
889 ## Step 4: Create Checkout Session API
890
891 In this step, you'll start creating [Agentic Checkout APIs](https://developers.openai.com/commerce/specs/checkout#rest-endpoints) to handle checkout requests from AI agents.
892
893 You'll implement the `POST /checkout_sessions` API route for creating checkout sessions. AI agents call this endpoint when customers want to purchase products. This is equivalent to creating a new cart in Medusa.
894
895 To implement this API route, you'll create:
896
897 1. A workflow that prepares checkout session responses based on [Agentic Commerce specifications](https://developers.openai.com/commerce/specs/checkout#rest-endpoints). You'll use this workflow in other checkout-related workflows.
898 2. A workflow that creates checkout sessions.
899 3. An API route at `POST /checkout_sessions` that executes the workflow to create checkout sessions.
900 4. A middleware to authenticate AI agent requests to checkout APIs.
901 5. A custom error handler to return errors in the format required by [Agentic Commerce specifications](https://developers.openai.com/commerce/specs/checkout#object-definitions).
902
903 ### a. Prepare Checkout Session Response Workflow
904
905 First, you'll create a workflow that prepares checkout session responses. This workflow will be used in other checkout-related workflows to return checkout sessions in the format required by [Agentic Commerce specifications](https://developers.openai.com/commerce/specs/checkout#rest-endpoints).
906
907 The workflow has the following steps:
908
909 <WorkflowDiagram
910 workflow={{
911 name: "prepareCheckoutSessionResponseWorkflow",
912 steps: [
913 {
914 type: "step",
915 name: "useQueryGraphStep",
916 description: "Retrieve the cart details",
917 link: "/references/helper-steps/useQueryGraphStep",
918 depth: 1,
919 },
920 {
921 type: "workflow",
922 name: "listShippingOptionsForCartWithPricingWorkflow",
923 description: "Retrieve shipping options for cart",
924 link: "/references/medusa-workflows/listShippingOptionsForCartWithPricingWorkflow",
925 depth: 2
926 }
927 ]
928 }}
929 />
930
931 These steps and workflows are available in Medusa out-of-the-box. So, you can implement the workflow without creating custom steps.
932
933 To create the workflow, create the file `src/workflows/prepare-checkout-session-data.ts` with the following content:
934
935 ```ts title="src/workflows/prepare-checkout-session-data.ts" collapsibleLines="1-10" expandButtonLabel="Show Imports"
936 import {
937 createWorkflow,
938 transform,
939 WorkflowResponse,
940 } from "@medusajs/framework/workflows-sdk"
941 import {
942 listShippingOptionsForCartWithPricingWorkflow,
943 useQueryGraphStep,
944 } from "@medusajs/medusa/core-flows"
945
946 export type PrepareCheckoutSessionDataWorkflowInput = {
947 buyer?: {
948 first_name: string
949 email: string
950 phone_number?: string
951 }
952 fulfillment_address?: {
953 name: string
954 line_one: string
955 line_two?: string
956 city: string
957 state: string
958 postal_code: string
959 phone_number?: string
960 country: string
961 }
962 cart_id: string
963 messages?: {
964 type: "error" | "info"
965 code: "missing" | "invalid" | "out_of_stock" | "payment_declined" | "required_sign_in" | "requires_3d"
966 content_type: "plain" | "markdown"
967 content: string
968 }[]
969 }
970
971 export const prepareCheckoutSessionDataWorkflow = createWorkflow(
972 "prepare-checkout-session-data",
973 (input: PrepareCheckoutSessionDataWorkflowInput) => {
974 // TODO add steps
975 }
976 )
977 ```
978
979 The `prepareCheckoutSessionDataWorkflow` accepts input with the following properties:
980
981 - `buyer`: Buyer information received from AI agents.
982 - `fulfillment_address`: Fulfillment address information received from AI agents.
983 - `cart_id`: Cart ID in Medusa, which is also the checkout session ID.
984 - `messages`: Messages to include in checkout session responses. This is useful for sending error or info messages to AI agents.
985
986 Next, you'll implement the workflow's logic. Replace the `TODO` in the workflow with the following:
987
988 ```ts title="src/workflows/prepare-checkout-session-data.ts"
989 const { data: carts } = useQueryGraphStep({
990 entity: "cart",
991 fields: [
992 "id",
993 "items.*",
994 "shipping_address.*",
995 "shipping_methods.*",
996 "region.*",
997 "region.payment_providers.*",
998 "currency_code",
999 "email",
1000 "phone",
1001 "payment_collection.*",
1002 "total",
1003 "subtotal",
1004 "tax_total",
1005 "discount_total",
1006 "original_item_total",
1007 "shipping_total",
1008 "metadata",
1009 "order.id",
1010 ],
1011 filters: {
1012 id: input.cart_id,
1013 },
1014 options: {
1015 throwIfKeyNotFound: true,
1016 },
1017 })
1018
1019 // Retrieve shipping options
1020 const shippingOptions = listShippingOptionsForCartWithPricingWorkflow.runAsStep({
1021 input: {
1022 cart_id: carts[0].id,
1023 },
1024 })
1025
1026 // TODO prepare response
1027 ```
1028
1029 You first retrieve the cart using `useQueryGraphStep`, including fields necessary to prepare checkout session responses.
1030
1031 Then, you retrieve shipping options that can be used for the cart using `listShippingOptionsForCartWithPricingWorkflow`.
1032
1033 Next, you'll prepare checkout session response data. Replace the `TODO` in the workflow with the following:
1034
1035 ```ts title="src/workflows/prepare-checkout-session-data.ts"
1036 const responseData = transform({
1037 input,
1038 carts,
1039 shippingOptions,
1040 }, (data) => {
1041 // @ts-ignore
1042 const hasStripePaymentProvider = data.carts[0].region?.payment_providers?.some((provider) => provider?.id.includes("stripe"))
1043 const hasPaymentSession = data.carts[0].payment_collection?.payment_sessions?.some((session) => session?.status === "pending")
1044 return {
1045 id: data.carts[0].id,
1046 buyer: data.input.buyer,
1047 payment_provider: {
1048 provider: hasStripePaymentProvider ? "stripe" : undefined,
1049 supported_payment_methods: hasStripePaymentProvider ? ["card"] : undefined,
1050 },
1051 status: hasPaymentSession ? "ready_for_payment" :
1052 data.carts[0].metadata?.checkout_session_canceled ? "canceled" :
1053 data.carts[0].order?.id ? "completed" : "not_ready_for_payment",
1054 currency: data.carts[0].currency_code,
1055 line_items: data.carts[0].items.map((item) => ({
1056 id: item?.id,
1057 title: item?.title,
1058 // @ts-ignore
1059 base_amount: item?.original_total,
1060 // @ts-ignore
1061 discount: item?.discount_total,
1062 // @ts-ignore
1063 subtotal: item?.subtotal,
1064 // @ts-ignore
1065 tax: item?.tax_total,
1066 // @ts-ignore
1067 total: item?.total,
1068 item: {
1069 id: item?.variant_id,
1070 quantity: item?.quantity,
1071 },
1072 })),
1073 fulfillment_address: data.input.fulfillment_address,
1074 fulfillment_options: data.shippingOptions?.map((option) => ({
1075 type: "shipping",
1076 id: option?.id,
1077 title: option?.name,
1078 subtitle: "",
1079 carrier_info: option?.provider?.id,
1080 earliest_delivery_time: option?.type.code === "express" ?
1081 new Date(Date.now() + 1 * 24 * 60 * 60 * 1000).toISOString() : // RFC 3339 string - 24 hours
1082 new Date(Date.now() + 2 * 24 * 60 * 60 * 1000).toISOString(), // RFC 3339 string - 48 hours
1083 latest_delivery_time: option?.type.code === "express" ?
1084 new Date(Date.now() + 1 * 24 * 60 * 60 * 1000).toISOString() : // RFC 3339 string - 24 hours
1085 new Date(Date.now() + 2 * 24 * 60 * 60 * 1000).toISOString(), // RFC 3339 string - 48 hours
1086 subtotal: option?.calculated_price.calculated_amount,
1087 // @ts-ignore
1088 tax: data.carts[0].shipping_methods?.[0]?.tax_total || 0,
1089 // @ts-ignore
1090 total: data.carts[0].shipping_methods?.[0]?.total || option?.calculated_price.calculated_amount,
1091 })),
1092 fulfillment_option_id: data.carts[0].shipping_methods?.[0]?.shipping_option_id,
1093 totals: [
1094 {
1095 type: "item_base_amount",
1096 display_name: "Item Base Amount",
1097 // @ts-ignore
1098 amount: data.carts[0].original_item_total,
1099 },
1100 {
1101 type: "subtotal",
1102 display_name: "Subtotal",
1103 // @ts-ignore
1104 amount: data.carts[0].subtotal,
1105 },
1106 {
1107 type: "discount",
1108 display_name: "Discount",
1109 // @ts-ignore
1110 amount: data.carts[0].discount_total,
1111 },
1112 {
1113 type: "fulfillment",
1114 display_name: "Fulfillment",
1115 // @ts-ignore
1116 amount: data.carts[0].shipping_total,
1117 },
1118 {
1119 type: "tax",
1120 display_name: "Tax",
1121 // @ts-ignore
1122 amount: data.carts[0].tax_total,
1123 },
1124 {
1125 type: "total",
1126 display_name: "Total",
1127 // @ts-ignore
1128 amount: data.carts[0].total,
1129 },
1130 ],
1131 messages: data.input.messages || [],
1132 links: [
1133 {
1134 type: "terms_of_use",
1135 value: "https://www.medusa-commerce.com/terms-of-use", // TODO: replace with actual terms of use
1136 },
1137 {
1138 type: "privacy_policy",
1139 value: "https://www.medusa-commerce.com/privacy-policy", // TODO: replace with actual privacy policy
1140 },
1141 {
1142 type: "seller_shop_policy",
1143 value: "https://www.medusa-commerce.com/seller-shop-policy", // TODO: replace with actual seller shop policy
1144 },
1145 ],
1146 }
1147 })
1148
1149 return new WorkflowResponse(responseData)
1150 ```
1151
1152 To create variables in workflows, you must use the [transform](!docs!/learn/fundamentals/workflows/variable-manipulation) function. This function accepts data to manipulate as the first parameter and a transformation function as the second parameter.
1153
1154 In the transformation function, you prepare checkout session responses matching [Agentic Commerce response specifications](https://developers.openai.com/commerce/specs/checkout#rest-endpoints). You can replace hardcoded values with dynamic values based on your setup.
1155
1156 Finally, you return response data in a `WorkflowResponse` instance.
1157
1158 ### b. Create Checkout Session Workflow
1159
1160 Next, you'll create a workflow that creates carts for checkout sessions. The `POST /checkout_sessions` API route will execute this workflow.
1161
1162 The workflow has the following steps:
1163
1164 <WorkflowDiagram
1165 workflow={{
1166 name: "createCheckoutSessionWorkflow",
1167 steps: [
1168 {
1169 type: "step",
1170 name: "useQueryGraphStep",
1171 description: "Retrieve the cart details",
1172 link: "/references/helper-steps/useQueryGraphStep",
1173 depth: 1,
1174 },
1175 {
1176 type: "step",
1177 name: "useQueryGraphStep",
1178 description: "Retrieve variant details to validate existence",
1179 link: "/references/helper-steps/useQueryGraphStep",
1180 depth: 2,
1181 },
1182 {
1183 type: "step",
1184 name: "useQueryGraphStep",
1185 description: "Retrieve region details",
1186 link: "/references/helper-steps/useQueryGraphStep",
1187 depth: 3
1188 },
1189 {
1190 type: "step",
1191 name: "useQueryGraphStep",
1192 description: "Retrieve sales channel details",
1193 link: "/references/helper-steps/useQueryGraphStep",
1194 depth: 4
1195 },
1196 {
1197 type: "step",
1198 name: "useQueryGraphStep",
1199 description: "Retrieve customer if it exists.",
1200 link: "/references/helper-steps/useQueryGraphStep",
1201 depth: 5
1202 },
1203 {
1204 type: "when",
1205 condition: "customers.length === 0 && !!input.buyer?.email",
1206 steps: [
1207 {
1208 type: "workflow",
1209 name: "createCustomersWorkflow",
1210 description: "Create customer if it does not exist",
1211 link: "/references/medusa-workflows/createCustomersWorkflow",
1212 depth: 1
1213 }
1214 ],
1215 depth: 6
1216 },
1217 {
1218 type: "step",
1219 name: "createCartWorkflow",
1220 description: "Create cart for checkout session",
1221 link: "/references/medusa-workflows/createCartWorkflow",
1222 depth: 7
1223 },
1224 {
1225 type: "when",
1226 condition: "!!input.fulfillment_address",
1227 steps: [
1228 {
1229 type: "step",
1230 name: "listShippingOptionsForCartWithPricingWorkflow",
1231 description: "Retrieve shipping options for the cart",
1232 link: "/references/medusa-workflows/listShippingOptionsForCartWithPricingWorkflow",
1233 depth: 1
1234 },
1235 {
1236 type: "step",
1237 name: "acquireLockStep",
1238 description: "Acquire lock on the cart to avoid race conditions",
1239 link: "/references/medusa-workflows/steps/acquireLockStep",
1240 depth: 2,
1241 },
1242 {
1243 type: "workflow",
1244 name: "addShippingMethodToCartWorkflow",
1245 description: "Add shipping method to the cart",
1246 link: "/references/medusa-workflows/addShippingMethodToCartWorkflow",
1247 depth: 3
1248 },
1249 {
1250 type: "step",
1251 name: "releaseLockStep",
1252 description: "Release the lock on the cart.",
1253 link: "/references/medusa-workflows/steps/releaseLockStep",
1254 depth: 4,
1255 }
1256 ],
1257 depth: 8
1258 },
1259 {
1260 type: "workflow",
1261 name: "prepareCheckoutSessionDataWorkflow",
1262 description: "Prepare the checkout session response",
1263 depth: 9
1264 }
1265 ]
1266 }}
1267 />
1268
1269 These steps and workflows are available in Medusa out-of-the-box. So, you can implement the workflow without creating custom steps.
1270
1271 Create the file `src/workflows/create-checkout-session.ts` with the following content:
1272
1273 ```ts title="src/workflows/create-checkout-session.ts" collapsibleLines="1-20" expandButtonLabel="Show Imports"
1274 import {
1275 createWorkflow,
1276 transform,
1277 when,
1278 WorkflowResponse,
1279 } from "@medusajs/framework/workflows-sdk"
1280 import {
1281 acquireLockStep,
1282 addShippingMethodToCartWorkflow,
1283 createCartWorkflow,
1284 CreateCartWorkflowInput,
1285 createCustomersWorkflow,
1286 listShippingOptionsForCartWithPricingWorkflow,
1287 releaseLockStep,
1288 useQueryGraphStep,
1289 } from "@medusajs/medusa/core-flows"
1290 import {
1291 prepareCheckoutSessionDataWorkflow,
1292 } from "./prepare-checkout-session-data"
1293
1294 type WorkflowInput = {
1295 items: {
1296 id: string
1297 quantity: number
1298 }[]
1299 buyer?: {
1300 first_name: string
1301 email: string
1302 phone_number?: string
1303 }
1304 fulfillment_address?: {
1305 name: string
1306 line_one: string
1307 line_two?: string
1308 city: string
1309 state: string
1310 postal_code: string
1311 phone_number?: string
1312 country: string
1313 }
1314 }
1315
1316 export const createCheckoutSessionWorkflow = createWorkflow(
1317 "create-checkout-session",
1318 (input: WorkflowInput) => {
1319 // TODO add steps
1320 }
1321 )
1322 ```
1323
1324 The `createCheckoutSessionWorkflow` accepts an input with the [request body of the Create Checkout Session API](https://developers.openai.com/commerce/specs/checkout#rest-endpoints).
1325
1326 #### Retrieve and Validate Variants
1327
1328 Next, you'll start implementing the workflow's logic. You'll first validate that the variants in the input exist.
1329
1330 Replace the `TODO` in the workflow with the following:
1331
1332 ```ts title="src/workflows/create-checkout-session.ts"
1333 // validate item IDs
1334 const variantIds = transform({
1335 input,
1336 }, (data) => {
1337 return data.input.items.map((item) => item.id)
1338 })
1339
1340 // Will fail if any variant IDs are not found
1341 useQueryGraphStep({
1342 entity: "variant",
1343 fields: ["id"],
1344 filters: {
1345 id: variantIds,
1346 },
1347 options: {
1348 throwIfKeyNotFound: true,
1349 },
1350 })
1351
1352 // TODO retrieve region and sales channel
1353 ```
1354
1355 You first create a variable with the variant IDs in the input using the `transform` function.
1356
1357 Then, you use the `useQueryGraphStep` to retrieve the variants with the IDs. You set the `throwIfKeyNotFound` option to `true` to make the step fail if any of the variant IDs are not found.
1358
1359 #### Retrieve Region and Sales Channel
1360
1361 Next, you'll retrieve the region and sales channel. These are necessary to associate the cart with the correct region and sales channel. Replace the `TODO` in the workflow with the following:
1362
1363 ```ts title="src/workflows/create-checkout-session.ts"
1364 // Find the region ID for US
1365 const { data: regions } = useQueryGraphStep({
1366 entity: "region",
1367 fields: ["id"],
1368 filters: {
1369 countries: {
1370 iso_2: "us",
1371 },
1372 },
1373 }).config({ name: "find-region" })
1374
1375 // get sales channel
1376 const { data: salesChannels } = useQueryGraphStep({
1377 entity: "sales_channel",
1378 fields: ["id"],
1379 // You can filter by name for a specific sales channel
1380 // filters: {
1381 // name: "Agentic Commerce"
1382 // }
1383 }).config({ name: "find-sales-channel" })
1384
1385 // TODO retrieve or create customer
1386 ```
1387
1388 You retrieve the region for the US using the `useQueryGraphStep` step. Instant Checkout in ChatGPT currently only supports the US region.
1389
1390 You also retrieve the sales channels. You can filter the sales channels by name if you want to use a specific sales channel.
1391
1392 #### Retrieve or Create Customer
1393
1394 Next, if the AI agent provides buyer information, you'll try to retrieve or create the customer. Replace the `TODO` in the workflow with the following:
1395
1396 ```ts title="src/workflows/create-checkout-session.ts"
1397 // check if customer already exists
1398 const { data: customers } = useQueryGraphStep({
1399 entity: "customer",
1400 fields: ["id"],
1401 filters: {
1402 email: input.buyer?.email,
1403 },
1404 }).config({ name: "find-customer" })
1405
1406 // create customer if it does not exist
1407 const createdCustomers = when ({ customers }, ({ customers }) =>
1408 customers.length === 0 && !!input.buyer?.email
1409 )
1410 .then(() => {
1411 return createCustomersWorkflow.runAsStep({
1412 input: {
1413 customersData: [
1414 {
1415 email: input.buyer?.email,
1416 first_name: input.buyer?.first_name,
1417 phone: input.buyer?.phone_number,
1418 has_account: false,
1419 },
1420 ],
1421 },
1422 })
1423 })
1424
1425 // set customer ID based on existing or created customer
1426 const customerId = transform({
1427 customers,
1428 createdCustomers,
1429 }, (data) => {
1430 return data.customers.length > 0 ?
1431 data.customers[0].id : data.createdCustomers?.[0].id
1432 })
1433
1434 // TODO prepare cart input and create cart
1435 ```
1436
1437 You first try to retrieve the customer using the `useQueryGraphStep` step, filtering by the buyer's email.
1438
1439 Then, to perform an action based on a condition, you use [when-then](!docs!/learn/fundamentals/workflows/conditions) functions. The `when` function accepts as a first parameter the data to evaluate, and as a second parameter a function that returns a boolean.
1440
1441 If the `when` function returns `true`, the `then` function is executed, which also accepts a function that performs steps and returns their result.
1442
1443 In this case, if the customer does not exist, you create it using the `createCustomersWorkflow` workflow.
1444
1445 Finally, you create a variable with the customer ID, which is either the existing customer's ID or the newly created customer's ID.
1446
1447 #### Prepare Cart Input and Create Cart
1448
1449 Next, you'll prepare the input for the cart creation, then create the cart. Replace the `TODO` in the workflow with the following:
1450
1451 ```ts title="src/workflows/create-checkout-session.ts"
1452 const cartInput = transform({
1453 input,
1454 regions,
1455 salesChannels,
1456 customerId,
1457 }, (data) => {
1458 const splitAddressName = data.input.fulfillment_address?.name.split(" ") || []
1459 return {
1460 items: data.input.items.map((item) => ({
1461 variant_id: item.id,
1462 quantity: item.quantity,
1463 })),
1464 region_id: data.regions[0]?.id,
1465 email: data.input.buyer?.email,
1466 customer_id: data.customerId,
1467 shipping_address: data.input.fulfillment_address ? {
1468 first_name: splitAddressName[0],
1469 last_name: splitAddressName.slice(1).join(" "),
1470 address_1: data.input.fulfillment_address?.line_one,
1471 address_2: data.input.fulfillment_address?.line_two,
1472 city: data.input.fulfillment_address?.city,
1473 province: data.input.fulfillment_address?.state,
1474 postal_code: data.input.fulfillment_address?.postal_code,
1475 country_code: data.input.fulfillment_address?.country,
1476 } : undefined,
1477 currency_code: data.regions[0]?.currency_code,
1478 sales_channel_id: data.salesChannels[0]?.id,
1479 metadata: {
1480 is_checkout_session: true,
1481 },
1482 } as CreateCartWorkflowInput
1483 })
1484
1485 const createdCart = createCartWorkflow.runAsStep({
1486 input: cartInput,
1487 })
1488
1489 // TODO retrieve shipping options
1490 ```
1491
1492 You use the `transform` function to prepare the input for the `createCartWorkflow` workflow. You map the input properties to the cart properties.
1493
1494 Then, you create the cart using the `createCartWorkflow` workflow.
1495
1496 #### Retrieve Shipping Options and Add Shipping Method
1497
1498 If the AI agent provides a fulfillment address in the request body, you must select the cheapest shipping option and add it to the cart.
1499
1500 Replace the `TODO` in the workflow with the following:
1501
1502 ```ts title="src/workflows/create-checkout-session.ts"
1503 // Select the cheapest shipping option if a fulfillment address is provided
1504 when(input, (input) => !!input.fulfillment_address)
1505 .then(() => {
1506 // Retrieve shipping options
1507 const shippingOptions = listShippingOptionsForCartWithPricingWorkflow.runAsStep({
1508 input: {
1509 cart_id: createdCart.id,
1510 },
1511 })
1512
1513 const shippingMethodData = transform({
1514 createdCart,
1515 shippingOptions,
1516 }, (data) => {
1517 // get the cheapest shipping option
1518 const cheapestShippingOption = data.shippingOptions.sort(
1519 (a, b) => a.price - b.price
1520 )[0]
1521 return {
1522 cart_id: data.createdCart.id,
1523 options: [{
1524 id: cheapestShippingOption.id,
1525 }],
1526 }
1527 })
1528 acquireLockStep({
1529 key: createdCart.id,
1530 timeout: 2,
1531 ttl: 10,
1532 })
1533 addShippingMethodToCartWorkflow.runAsStep({
1534 input: shippingMethodData,
1535 })
1536 releaseLockStep({
1537 key: createdCart.id,
1538 })
1539 })
1540
1541 // TODO prepare checkout session response
1542 ```
1543
1544 You use the `when` function to check if a fulfillment address is provided in the input. If so, you:
1545
1546 - Retrieve the shipping options using the [listShippingOptionsForCartWithPricingWorkflow](/references/medusa-workflows/listShippingOptionsForCartWithPricingWorkflow).
1547 - Create a variable with the cheapest shipping option using the `transform` function.
1548 - Acquire a lock on the cart to avoid race conditions.
1549 - Add the cheapest shipping option to the cart using the [addShippingMethodToCartWorkflow](/references/medusa-workflows/addShippingMethodToCartWorkflow).
1550 - Release the lock on the cart.
1551
1552 #### Prepare Checkout Session Response
1553
1554 Finally, you'll prepare and return the checkout session response. Replace the `TODO` in the workflow with the following:
1555
1556 ```ts title="src/workflows/create-checkout-session.ts"
1557 // Prepare response data
1558 const responseData = prepareCheckoutSessionDataWorkflow.runAsStep({
1559 input: {
1560 buyer: input.buyer,
1561 fulfillment_address: input.fulfillment_address,
1562 cart_id: createdCart.id,
1563 },
1564 })
1565
1566 return new WorkflowResponse(responseData)
1567 ```
1568
1569 You prepare the checkout session response using the `prepareCheckoutSessionDataWorkflow` workflow you created earlier. You return it as the workflow's response.
1570
1571 ### c. Create Checkout Session API Route
1572
1573 Next, you'll create the [API route](!docs!/learn/fundamentals/api-routes) at `POST /checkout_sessions` that executes the `createCheckoutSessionWorkflow`.
1574
1575 An API route is created in a `route.ts` file under a sub-directory of the `src/api` directory. The path of the API route is the file's path relative to `src/api`.
1576
1577 <Note>
1578
1579 Refer to the [API routes](!docs!/learn/fundamentals/api-routes) to learn more about them.
1580
1581 </Note>
1582
1583 So, to create an API route, create the file `src/api/checkout_sessions/route.ts` with the following content:
1584
1585 <Note>
1586
1587 As of [Medusa v2.13.0](https://github.com/medusajs/medusa/releases/tag/v2.13.0), Zod should be imported from `@medusajs/framework/zod`.
1588
1589 </Note>
1590
1591 ```ts title="src/api/checkout_sessions/route.ts"
1592 import { MedusaRequest, MedusaResponse } from "@medusajs/framework"
1593 import { z } from "@medusajs/framework/zod"
1594 import { createCheckoutSessionWorkflow } from "../../workflows/create-checkout-session"
1595 import {
1596 MedusaError,
1597 ContainerRegistrationKeys,
1598 } from "@medusajs/framework/utils"
1599
1600 export const PostCreateSessionSchema = z.object({
1601 items: z.array(z.object({
1602 id: z.string(), // variant ID
1603 quantity: z.number(),
1604 })),
1605 buyer: z.object({
1606 first_name: z.string(),
1607 email: z.string(),
1608 phone_number: z.string().optional(),
1609 }).optional(),
1610 fulfillment_address: z.object({
1611 name: z.string(),
1612 line_one: z.string(),
1613 line_two: z.string().optional(),
1614 city: z.string(),
1615 state: z.string(),
1616 country: z.string(),
1617 postal_code: z.string(),
1618 phone_number: z.string().optional(),
1619 }).optional(),
1620 })
1621
1622 export const POST = async (
1623 req: MedusaRequest<
1624 z.infer<typeof PostCreateSessionSchema>
1625 >,
1626 res: MedusaResponse
1627 ) => {
1628 const logger = req.scope.resolve(
1629 ContainerRegistrationKeys.LOGGER
1630 )
1631 const responseHeaders = {
1632 "Idempotency-Key": req.headers["idempotency-key"] as string,
1633 "Request-Id": req.headers["request-id"] as string,
1634 }
1635 try {
1636 const { result } = await createCheckoutSessionWorkflow(req.scope)
1637 .run({
1638 input: req.validatedBody,
1639 context: {
1640 idempotencyKey: req.headers["idempotency-key"] as string,
1641 },
1642 })
1643
1644 res.set(responseHeaders).json(result)
1645 } catch (error) {
1646 const medusaError = error as MedusaError
1647 logger.error(medusaError)
1648 res.set(responseHeaders).json({
1649 messages: [
1650 {
1651 type: "error",
1652 code: "invalid",
1653 content_type: "plain",
1654 content: medusaError.message,
1655 },
1656 ],
1657 })
1658 }
1659 }
1660 ```
1661
1662 You first define a validation schema with [Zod](https://zod.dev/) for the request body. The schema matches the [Agentic Commerce request specifications](https://developers.openai.com/commerce/specs/checkout#rest-endpoints).
1663
1664 Then, you export a `POST` route handler function, which exposes a `POST` API route at `/checkout_sessions`.
1665
1666 In the route handler, you execute the `createCheckoutSessionWorkflow`, passing the validated request body as input. You return the workflow's response as the API response.
1667
1668 If an error occurs, you catch it and return it in the format required by the Agentic Commerce specifications.
1669
1670 You also return the `Idempotency-Key` and `Request-Id` headers in the response if they are provided in the request. These headers are required by the [Agentic Commerce specifications](https://developers.openai.com/commerce/specs/checkout#rest-endpoints).
1671
1672 ### d. Create Authentication Middleware
1673
1674 Next, you'll create a [middleware](!docs!/learn/fundamentals/api-routes/middlewares) to authenticate requests to checkout APIs. The middleware will run before API route handlers and verify that requests contain valid API keys and signatures before allowing access to route handlers.
1675
1676 Create the file `src/api/middlewares/validate-agentic-request.ts` with the following content:
1677
1678 ```ts title="src/api/middlewares/validate-agentic-request.ts"
1679 import { MedusaNextFunction, MedusaRequest, MedusaResponse } from "@medusajs/framework"
1680 import { AGENTIC_COMMERCE_MODULE } from "../../modules/agentic-commerce"
1681 import { Modules } from "@medusajs/framework/utils"
1682
1683 export async function validateAgenticRequest(
1684 req: MedusaRequest,
1685 res: MedusaResponse,
1686 next: MedusaNextFunction
1687 ) {
1688 const agenticCommerceModuleService = req.scope.resolve(AGENTIC_COMMERCE_MODULE)
1689 const apiKeyModuleService = req.scope.resolve(Modules.API_KEY)
1690 const signature = req.headers["signature"] as string
1691 const apiKey = req.headers["authorization"]?.replaceAll("Bearer ", "")
1692
1693 const isTokenValid = await apiKeyModuleService.authenticate(apiKey || "")
1694 const isSignatureValid = !!req.body || await agenticCommerceModuleService.verifySignature({
1695 signature,
1696 payload: req.body,
1697 })
1698
1699 if (!isTokenValid || !isSignatureValid) {
1700 return res.status(401).json({
1701 message: "Unauthorized",
1702 })
1703 }
1704
1705 next()
1706 }
1707 ```
1708
1709 You create the `validateAgenticRequest` middleware function that accepts request, response, and next function as parameters.
1710
1711 In this middleware, you:
1712
1713 1. Resolve services of the Agentic Commerce and [API Key](../../../commerce-modules/api-key/page.mdx) modules.
1714 2. Validate that the API key in the `Authorization` header is valid using the API Key Module's service.
1715 3. Validate that the signature in the `Signature` header is valid using the Agentic Commerce Module's service. If the request has no body, you skip signature validation.
1716 4. If either the API key or signature is invalid, you return a `401 Unauthorized` response.
1717 5. Otherwise, you call the `next` function to proceed to the next middleware or route handler.
1718
1719 The headers are expected based on [Agentic Commerce specifications](https://developers.openai.com/commerce/specs/checkout#rest-endpoints). You can create an API key that AI agents can use in the [Secret API Key Settings](!user-guide!/settings/developer/secret-api-keys) of the Medusa Admin dashboard.
1720
1721 To use this middleware, you need to apply it to checkout API routes.
1722
1723 You apply middlewares in the `src/api/middlewares.ts` file. Create this file with the following content:
1724
1725 ```ts title="src/api/middlewares.ts"
1726 import {
1727 defineMiddlewares,
1728 validateAndTransformBody,
1729 } from "@medusajs/framework/http"
1730 import { validateAgenticRequest } from "./middlewares/validate-agentic-request"
1731 import { PostCreateSessionSchema } from "./checkout_sessions/route"
1732
1733 export default defineMiddlewares({
1734 routes: [
1735 {
1736 matcher: "/checkout_sessions*",
1737 middlewares: [
1738 validateAgenticRequest,
1739 ],
1740 },
1741 {
1742 matcher: "/checkout_sessions",
1743 method: ["POST"],
1744 middlewares: [validateAndTransformBody(PostCreateSessionSchema)],
1745 },
1746 ],
1747 })
1748 ```
1749
1750 You apply the `validateAgenticRequest` middleware to all routes starting with `/checkout_sessions`.
1751
1752 You also apply the `validateAndTransformBody` middleware to the `POST /checkout_sessions` route to ensure request bodies include required fields.
1753
1754 ### e. Create Custom Error Handler
1755
1756 Finally, you'll add a custom error handler to return errors in the format required by [Agentic Commerce specifications](https://developers.openai.com/commerce/specs/checkout#object-definitions).
1757
1758 To override the default error handler, you can pass the `errorHandler` property to `defineMiddlewares`. It accepts an error handler function.
1759
1760 In `src/api/middlewares.ts`, add the following import at the top of the file:
1761
1762 ```ts title="src/api/middlewares.ts"
1763 import {
1764 errorHandler,
1765 } from "@medusajs/framework/http"
1766
1767 const originalErrorHandler = errorHandler()
1768 ```
1769
1770 You import the default error handler and store it in a variable to use in your custom error handler.
1771
1772 Then, add the `errorHandler` property to the `defineMiddlewares` function:
1773
1774 ```ts title="src/api/middlewares.ts"
1775 export default defineMiddlewares({
1776 // ...
1777 errorHandler: (error, req, res, next) => {
1778 if (!req.path.startsWith("/checkout_sessions")) {
1779 return originalErrorHandler(error, req, res, next)
1780 }
1781
1782 res.json({
1783 messages: [
1784 {
1785 type: "error",
1786 code: "invalid",
1787 content_type: "plain",
1788 content: error.message,
1789 },
1790 ],
1791 })
1792 },
1793 })
1794 ```
1795
1796 If the request path does not start with `/checkout_sessions`, you call the original error handler to handle errors.
1797
1798 Otherwise, you return errors in the format required by Agentic Commerce specifications.
1799
1800 ### Use the Checkout Session API
1801
1802 To use the `POST /checkout_sessions` API:
1803
1804 - Apply to ChatGPT's [Instant Checkout](https://chatgpt.com/merchants) and access a signature key.
1805 - Create an API key in the [Secret API Key Settings](!user-guide!/settings/developer/secret-api-keys) of the Medusa Admin dashboard.
1806 - Setup the API key in the Instant Checkout settings.
1807
1808 ChatGPT will then use these to create checkout sessions.
1809
1810 ### Test the Create Checkout Session API Locally
1811
1812 To test the `POST /checkout_sessions` API locally, you'll add an API route to retrieve signatures based on payloads. This allows you to simulate signature generation that ChatGPT performs.
1813
1814 Create the file `src/api/signature/route.ts` with the following content:
1815
1816 ```ts title="src/api/signature/route.ts"
1817 import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
1818 import { AGENTIC_COMMERCE_MODULE } from "../../modules/agentic-commerce"
1819
1820 export const POST = async (
1821 req: MedusaRequest,
1822 res: MedusaResponse
1823 ) => {
1824 const agenticCommerceModuleService = req.scope.resolve(AGENTIC_COMMERCE_MODULE)
1825 const signature = await agenticCommerceModuleService.getSignature(req.body)
1826 res.json({ signature })
1827 }
1828 ```
1829
1830 This API route accepts payloads in request bodies and returns signatures generated using the Agentic Commerce Module's service.
1831
1832 Then, start the Medusa application with the following command:
1833
1834 ```bash npm2yarn
1835 npm run dev
1836 ```
1837
1838 After that, send a `POST` request to `http://localhost:9000/signature` with the JSON body to create checkout sessions. For example:
1839
1840 <Note title="Tip">
1841
1842 Make sure you [have a region with the US added to its countries](!user-guide!/settings/regions#create-region) in your Medusa store.
1843
1844 </Note>
1845
1846 ```bash
1847 curl -X POST 'http://localhost:9000/signature' \
1848 -H 'Content-Type: application/json' \
1849 --data-raw '{
1850 "items": [
1851 {
1852 "id": "variant_01K6CQ43RA0RSWW1BXM8C63YT6",
1853 "quantity": 1
1854 }
1855 ],
1856 "fulfillment_address": {
1857 "name": "John Smith",
1858 "line_one": "US",
1859 "city": "New York",
1860 "state": "NY",
1861 "country": "us",
1862 "postal_code": "12345"
1863 },
1864 "buyer": {
1865 "email": "johnsmith@gmail.com",
1866 "first_name": "John",
1867 "phone_number": "123"
1868 }
1869 }'
1870 ```
1871
1872 Make sure to replace the variant ID with an actual variant ID from your store.
1873
1874 Copy the signature from the response.
1875
1876 Finally, send a `POST` request to `http://localhost:9000/checkout_sessions` with the same JSON body and include the `Authorization` and `Signature` headers:
1877
1878 ```bash
1879 curl -X POST 'http://localhost:9000/checkout_sessions' \
1880 -H 'Signature: {your_signature}' \
1881 -H 'Idempotency-Key: idp_123' \
1882 -H 'Request-Id: req_123' \
1883 -H 'Content-Type: application/json' \
1884 -H 'Authorization: Bearer {your_api_key}' \
1885 --data-raw '{
1886 "items": [
1887 {
1888 "id": "variant_01K6CQ43RA0RSWW1BXM8C63YT6",
1889 "quantity": 1
1890 }
1891 ],
1892 "fulfillment_address": {
1893 "name": "John Smith",
1894 "line_one": "US",
1895 "city": "New York",
1896 "state": "NY",
1897 "country": "us",
1898 "postal_code": "12345"
1899 },
1900 "buyer": {
1901 "email": "johnsmith@gmail.com",
1902 "first_name": "John",
1903 "phone_number": "123"
1904 }
1905 }'
1906 ```
1907
1908 Make sure to replace:
1909
1910 - `{your_signature}` with the signature you copied from the previous request.
1911 - `{your_api_key}` with the API key you created in the Medusa Admin dashboard.
1912 - The variant ID with an actual variant ID from your store.
1913
1914 You'll receive in the response the checkout session based on the Agentic Commerce specifications.
1915
1916 ---
1917
1918 ## Step 5: Update Checkout Session API
1919
1920 Next, you'll implement the `POST /checkout_sessions/{id}` API to update a checkout session.
1921
1922 This API is called by the AI agent to update the checkout session's details, such as when the buyer changes the fulfillment address. Whenever the checkout session is updated, you must also reset the cart's payment sessions, as instructed in the [Agentic Commerce specifications](https://developers.openai.com/commerce/specs/checkout#checkout-session).
1923
1924 Similar to before, you'll create:
1925
1926 - A workflow that updates the checkout session.
1927 - An API route that executes the workflow.
1928 - You'll also apply a validation middleware to the API route.
1929
1930 ### a. Update Checkout Session Workflow
1931
1932 First, you'll create the workflow that updates a checkout session. This workflow will be executed by the `POST /checkout_sessions/{id}` API route.
1933
1934 The workflow has the following steps:
1935
1936 <WorkflowDiagram
1937 workflow={{
1938 name: "updateCheckoutSessionWorkflow",
1939 steps: [
1940 {
1941 type: "step",
1942 name: "useQueryGraphStep",
1943 description: "Retrieve the cart details",
1944 link: "/references/helper-steps/useQueryGraphStep",
1945 depth: 1,
1946 },
1947 {
1948 type: "step",
1949 name: "useQueryGraphStep",
1950 description: "Retrieve customer if it exists.",
1951 link: "/references/helper-steps/useQueryGraphStep",
1952 depth: 2
1953 },
1954 {
1955 type: "when",
1956 condition: "customers.length === 0 && !!input.buyer?.email",
1957 steps: [
1958 {
1959 type: "workflow",
1960 name: "createCustomersWorkflow",
1961 description: "Create customer if it does not exist",
1962 link: "/references/medusa-workflows/createCustomersWorkflow",
1963 depth: 1
1964 }
1965 ],
1966 depth: 3
1967 },
1968 {
1969 type: "when",
1970 condition: "!!input.items",
1971 steps: [
1972 {
1973 type: "step",
1974 name: "useQueryGraphStep",
1975 description: "Retrieve the variants to validate that they exist",
1976 link: "/references/helper-steps/useQueryGraphStep",
1977 depth: 1,
1978 }
1979 ],
1980 depth: 4
1981 },
1982 {
1983 type: "step",
1984 name: "acquireLockStep",
1985 description: "Acquire a lock on the cart to avoid concurrent modifications.",
1986 link: "/references/medusa-workflows/steps/acquireLockStep",
1987 depth: 5,
1988 },
1989 {
1990 type: "workflow",
1991 name: "updateCartWorkflow",
1992 description: "Update the cart with the new data",
1993 link: "/references/medusa-workflows/updateCartWorkflow",
1994 depth: 6
1995 },
1996 {
1997 type: "when",
1998 condition: "!!input.fulfillment_option_id",
1999 steps: [
2000 {
2001 type: "workflow",
2002 name: "addShippingMethodToCartWorkflow",
2003 description: "Add shipping method to the cart",
2004 link: "/references/medusa-workflows/addShippingMethodToCartWorkflow",
2005 depth: 1
2006 }
2007 ],
2008 depth: 7
2009 },
2010 {
2011 type: "workflow",
2012 name: "prepareCheckoutSessionDataWorkflow",
2013 description: "Prepare the checkout session response",
2014 depth: 8
2015 },
2016 {
2017 type: "step",
2018 name: "releaseLockStep",
2019 description: "Release lock on the cart",
2020 link: "/references/medusa-workflows/steps/releaseLockStep",
2021 depth: 9
2022 }
2023 ]
2024 }}
2025 />
2026
2027 These steps and workflows are available in Medusa out-of-the-box. So, you can implement the workflow without creating custom steps.
2028
2029 Create the file `src/workflows/update-checkout-session.ts` with the following content:
2030
2031 ```ts title="src/workflows/update-checkout-session.ts" collapsibleLines="1-18" expandButtonLabel="Show Imports"
2032 import {
2033 createWorkflow,
2034 transform,
2035 when,
2036 WorkflowResponse,
2037 } from "@medusajs/framework/workflows-sdk"
2038 import {
2039 acquireLockStep,
2040 addShippingMethodToCartWorkflow,
2041 createCustomersWorkflow,
2042 releaseLockStep,
2043 updateCartWorkflow,
2044 useQueryGraphStep,
2045 } from "@medusajs/medusa/core-flows"
2046 import {
2047 prepareCheckoutSessionDataWorkflow,
2048 } from "./prepare-checkout-session-data"
2049
2050 type WorkflowInput = {
2051 cart_id: string
2052 buyer?: {
2053 first_name: string
2054 email: string
2055 phone_number?: string
2056 }
2057 items?: {
2058 id: string
2059 quantity: number
2060 }[]
2061 fulfillment_address?: {
2062 name: string
2063 line_one: string
2064 line_two?: string
2065 city: string
2066 state: string
2067 postal_code: string
2068 phone_number?: string
2069 country: string
2070 }
2071 fulfillment_option_id?: string
2072 }
2073
2074 export const updateCheckoutSessionWorkflow = createWorkflow(
2075 "update-checkout-session",
2076 (input: WorkflowInput) => {
2077 // Retrieve cart
2078 const { data: carts } = useQueryGraphStep({
2079 entity: "cart",
2080 fields: ["id", "customer.*", "email"],
2081 filters: {
2082 id: input.cart_id,
2083 },
2084 })
2085
2086 // TODO retrieve or create customer
2087 }
2088 )
2089 ```
2090
2091 The `updateCheckoutSessionWorkflow` accepts an input with the [request body of the Update Checkout Session API](https://developers.openai.com/commerce/specs/checkout#rest-endpoints) along with the cart ID.
2092
2093 So far, you retrieve the cart using the `useQueryGraphStep` step.
2094
2095 #### Retrieve or Create Customer (Update)
2096
2097 Next, you'll retrieve the customer if it exists or create it if it doesn't. Replace the `TODO` in the workflow with the following:
2098
2099 ```ts title="src/workflows/update-checkout-session.ts"
2100 // check if customer already exists
2101 const { data: customers } = useQueryGraphStep({
2102 entity: "customer",
2103 fields: ["id"],
2104 filters: {
2105 email: input.buyer?.email,
2106 },
2107 }).config({ name: "find-customer" })
2108
2109 const createdCustomers = when({ customers }, ({ customers }) =>
2110 customers.length === 0 && !!input.buyer?.email
2111 )
2112 .then(() => {
2113 return createCustomersWorkflow.runAsStep({
2114 input: {
2115 customersData: [
2116 {
2117 email: input.buyer?.email,
2118 first_name: input.buyer?.first_name,
2119 phone: input.buyer?.phone_number,
2120 },
2121 ],
2122 },
2123 })
2124 })
2125
2126 const customerId = transform({
2127 customers,
2128 createdCustomers,
2129 }, (data) => {
2130 return data.customers.length > 0 ?
2131 data.customers[0].id : data.createdCustomers?.[0].id
2132 })
2133
2134 // TODO validate variants if items are provided
2135 ```
2136
2137 You first try to retrieve the customer using the `useQueryGraphStep` step, filtering by the buyer's email.
2138
2139 Then, if the customer does not exist, you create it using the `createCustomersWorkflow` workflow.
2140
2141 Finally, you create a variable with the customer ID, which is either the existing customer's ID or the newly created customer's ID.
2142
2143 #### Validate Variants if Items are Provided
2144
2145 Next, you'll validate that the variants in the input exist if items are provided. Replace the `TODO` in the workflow with the following:
2146
2147 ```ts title="src/workflows/update-checkout-session.ts"
2148 // validate items
2149 when(input, (input) => !!input.items)
2150 .then(() => {
2151 const variantIds = transform(input, (input) => input.items?.map((item) => item.id))
2152 return useQueryGraphStep({
2153 entity: "variant",
2154 fields: ["id"],
2155 filters: {
2156 id: variantIds,
2157 },
2158 options: {
2159 throwIfKeyNotFound: true,
2160 },
2161 }).config({ name: "find-variant" })
2162 })
2163
2164 // TODO update cart
2165 ```
2166
2167 You use the `when` function to check if items are provided in the input. If so, you retrieve the variants with the IDs using the `useQueryGraphStep` step. You set the `throwIfKeyNotFound` option to `true` to make the step fail if any of the variant IDs are not found.
2168
2169 #### Update Cart
2170
2171 Next, you'll update the cart based on the input. Replace the `TODO` in the workflow with the following:
2172
2173 ```ts title="src/workflows/update-checkout-session.ts"
2174 acquireLockStep({
2175 key: input.cart_id,
2176 timeout: 2,
2177 ttl: 10,
2178 })
2179 // Prepare update data
2180 const updateData = transform({
2181 input,
2182 carts,
2183 customerId,
2184 }, (data) => {
2185 return {
2186 id: data.carts[0].id,
2187 email: data.input.buyer?.email || data.carts[0].email,
2188 customer_id: data.customerId || data.carts[0].customer?.id,
2189 items: data.input.items?.map((item) => ({
2190 variant_id: item.id,
2191 quantity: item.quantity,
2192 })),
2193 shipping_address: data.input.fulfillment_address ? {
2194 first_name: data.input.fulfillment_address.name.split(" ")[0],
2195 last_name: data.input.fulfillment_address.name.split(" ")[1],
2196 address_1: data.input.fulfillment_address.line_one,
2197 address_2: data.input.fulfillment_address.line_two,
2198 city: data.input.fulfillment_address.city,
2199 province: data.input.fulfillment_address.state,
2200 postal_code: data.input.fulfillment_address.postal_code,
2201 country_code: data.input.fulfillment_address.country,
2202 phone: data.input.fulfillment_address.phone_number,
2203 } : undefined,
2204 }
2205 })
2206
2207 updateCartWorkflow.runAsStep({
2208 input: updateData,
2209 })
2210
2211 // TODO add shipping method if fulfillment option ID is provided
2212 ```
2213
2214 First, you acquire a lock on the cart to avoid concurrent modifications.
2215
2216 Then, you use the `transform` function to prepare the input for the `updateCartWorkflow` workflow. You map the input properties to the cart properties.
2217
2218 After that, you update the cart using the `updateCartWorkflow`. This workflow will also clear the cart's payment sessions.
2219
2220 #### Add Shipping Method if Fulfillment Option ID is Provided
2221
2222 Finally, you'll add the shipping method to the cart if a fulfillment option ID is provided, and prepare and return the checkout session response. Replace the `TODO` in the workflow with the following:
2223
2224 ```ts title="src/workflows/update-checkout-session.ts"
2225 // try to update shipping method
2226 when(input, (input) => !!input.fulfillment_option_id)
2227 .then(() => {
2228 addShippingMethodToCartWorkflow.runAsStep({
2229 input: {
2230 cart_id: updateData.id,
2231 options: [{
2232 id: input.fulfillment_option_id!,
2233 }],
2234 },
2235 })
2236 })
2237
2238 const responseData = prepareCheckoutSessionDataWorkflow.runAsStep({
2239 input: {
2240 cart_id: updateData.id,
2241 buyer: input.buyer,
2242 fulfillment_address: input.fulfillment_address,
2243 },
2244 })
2245
2246 releaseLockStep({
2247 key: input.cart_id,
2248 })
2249
2250 return new WorkflowResponse(responseData)
2251 ```
2252
2253 You use the `when` function to check if a fulfillment option ID is provided in the input. If it is, you add it to the cart using the `addShippingMethodToCartWorkflow` workflow.
2254
2255 Then, you prepare the checkout session response using the `prepareCheckoutSessionDataWorkflow` workflow you created earlier.
2256
2257 Finally, you release the lock on the cart and return the prepared response as the workflow's response.
2258
2259 ### b. Update Checkout Session API Route
2260
2261 Next, you'll create an API route that executes the `updateCheckoutSessionWorkflow`.
2262
2263 Create the file `src/api/checkout_sessions/[id]/route.ts` with the following content:
2264
2265 ```ts title="src/api/checkout_sessions/[id]/route.ts" collapsibleLines="1-7" expandButtonLabel="Show Imports"
2266 import { MedusaRequest, MedusaResponse } from "@medusajs/framework"
2267 import { updateCheckoutSessionWorkflow } from "../../../workflows/update-checkout-session"
2268 import { z } from "@medusajs/framework/zod"
2269 import { MedusaError } from "@medusajs/framework/utils"
2270 import { prepareCheckoutSessionDataWorkflow } from "../../../workflows/prepare-checkout-session-data"
2271 import { refreshPaymentCollectionForCartWorkflow } from "@medusajs/medusa/core-flows"
2272
2273 export const PostUpdateSessionSchema = z.object({
2274 buyer: z.object({
2275 first_name: z.string(),
2276 email: z.string(),
2277 phone_number: z.string().optional(),
2278 }).optional(),
2279 items: z.array(z.object({
2280 id: z.string(),
2281 quantity: z.number(),
2282 })).optional(),
2283 fulfillment_address: z.object({
2284 name: z.string(),
2285 line_one: z.string(),
2286 line_two: z.string().optional(),
2287 city: z.string(),
2288 state: z.string(),
2289 country: z.string(),
2290 postal_code: z.string(),
2291 phone_number: z.string().optional(),
2292 }).optional(),
2293 fulfillment_option_id: z.string().optional(),
2294 })
2295
2296 export const POST = async (
2297 req: MedusaRequest<
2298 z.infer<typeof PostUpdateSessionSchema>
2299 >,
2300 res: MedusaResponse
2301 ) => {
2302 const responseHeaders = {
2303 "Idempotency-Key": req.headers["idempotency-key"] as string,
2304 "Request-Id": req.headers["request-id"] as string,
2305 }
2306 try {
2307 const { result } = await updateCheckoutSessionWorkflow(req.scope)
2308 .run({
2309 input: {
2310 cart_id: req.params.id,
2311 ...req.validatedBody,
2312 },
2313 context: {
2314 idempotencyKey: req.headers["idempotency-key"] as string,
2315 },
2316 })
2317
2318 res.set(responseHeaders).json(result)
2319 } catch (error) {
2320 const medusaError = error as MedusaError
2321
2322 await refreshPaymentCollectionForCartWorkflow(req.scope).run({
2323 input: {
2324 cart_id: req.params.id,
2325 },
2326 })
2327
2328 const { result } = await prepareCheckoutSessionDataWorkflow(req.scope)
2329 .run({
2330 input: {
2331 cart_id: req.params.id,
2332 ...req.validatedBody,
2333 messages: [
2334 {
2335 type: "error",
2336 code: medusaError.type === MedusaError.Types.PAYMENT_AUTHORIZATION_ERROR ?
2337 "payment_declined" : "invalid",
2338 content_type: "plain",
2339 content: medusaError.message,
2340 },
2341 ],
2342 },
2343 })
2344
2345 res.set(responseHeaders).json(result)
2346 }
2347 }
2348 ```
2349
2350 You first define a validation schema with [Zod](https://zod.dev/) for the request body. The schema matches the [Agentic Commerce request specifications](https://developers.openai.com/commerce/specs/checkout#rest-endpoints).
2351
2352 Then, you export a `POST` route handler function, which exposes a `POST` API route at `/checkout_sessions/{id}`.
2353
2354 In the route handler, you execute the `updateCheckoutSessionWorkflow`, passing the cart ID from the URL parameters and the validated request body as input. You return the workflow's response as the API response.
2355
2356 If an error occurs, you refresh the cart's payment sessions using the `refreshPaymentCollectionForCartWorkflow`, and prepare the checkout session response with an error message using the `prepareCheckoutSessionDataWorkflow` workflow. You return this response.
2357
2358 ### c. Apply Validation Middleware
2359
2360 Finally, you'll apply the validation middleware to the `POST /checkout_sessions/{id}` API route.
2361
2362 In `src/api/middlewares.ts`, add the following import at the top of the file:
2363
2364 ```ts title="src/api/middlewares.ts"
2365 import { PostUpdateSessionSchema } from "./checkout_sessions/[id]/route"
2366 ```
2367
2368 Then, add a new route configuration in `defineMiddlewares`:
2369
2370 ```ts title="src/api/middlewares.ts"
2371 export default defineMiddlewares({
2372 routes: [
2373 // ...
2374 {
2375 matcher: "/checkout_sessions/:id",
2376 method: ["POST"],
2377 middlewares: [validateAndTransformBody(PostUpdateSessionSchema)],
2378 },
2379 ],
2380 // ...
2381 })
2382 ```
2383
2384 You apply the `validateAndTransformBody` middleware to the `POST /checkout_sessions/{id}` route to ensure the request body includes the required fields.
2385
2386 ### Use the Update Checkout Session API
2387
2388 To use the `POST /checkout_sessions/:id` API, you need to:
2389
2390 - Apply to ChatGPT's [Instant Checkout](https://chatgpt.com/merchants) and access a signature key.
2391 - Create an API key in the [Secret API Key Settings](!user-guide!/settings/developer/secret-api-keys) of the Medusa Admin dashboard.
2392 - Setup the API key in the Instant Checkout settings.
2393
2394 ChatGPT will then use it to update a checkout session.
2395
2396 ### Test the Update Checkout Session API Locally
2397
2398 To test out the `POST /checkout_sessions/:id` API locally, you need to use the same signature generation API route you created earlier.
2399
2400 First, assuming you already [created a checkout session](#test-the-create-checkout-session-api-locally) and have the cart ID, send a `POST` request to `http://localhost:9000/signature` with the JSON body to update the checkout session. For example:
2401
2402 ```bash
2403 curl -X POST 'http://localhost:9000/signature' \
2404 -H 'Content-Type: application/json' \
2405 --data '{
2406 "fulfillment_option_id": "so_01K6FCGVFMNNC5H43SB9NNNAJ3"
2407 }'
2408 ```
2409
2410 Make sure to replace the fulfillment option ID with an actual shipping option ID from your store.
2411
2412 Then, send a `POST` request to `http://localhost:9000/checkout_sessions/{cart_id}` with the same JSON body, and include the `Authorization` and `Signature` headers:
2413
2414 ```bash
2415 curl -X POST 'http://localhost:9000/checkout_sessions/{cart_id}' \
2416 -H 'Signature: {signature}' \
2417 -H 'Idempotency-Key: idp_123' \
2418 -H 'Request-Id: req_123' \
2419 -H 'Content-Type: application/json' \
2420 -H 'Authorization: Bearer {api_key}' \
2421 --data '{
2422 "fulfillment_option_id": "so_01K6FCGVFMNNC5H43SB9NNNAJ3"
2423 }'
2424 ```
2425
2426 Make sure to replace:
2427
2428 - `{cart_id}` with the cart ID of the checkout session you created earlier.
2429 - `{signature}` with the signature you copied from the previous request.
2430 - `{api_key}` with the API key you created in the Medusa Admin dashboard.
2431 - The fulfillment option ID with an actual shipping option ID from your store.
2432
2433 You'll receive in the response the updated checkout session based on the Agentic Commerce specifications.
2434
2435 ---
2436
2437 ## Step 6: Get Checkout Session API
2438
2439 Next, you'll implement the `GET /checkout_sessions/{id}` API to retrieve a checkout session. This API is called by the AI agent to get the current state of the checkout session.
2440
2441 This API route will use the `prepareCheckoutSessionDataWorkflow` workflow you created earlier to prepare the checkout session response.
2442
2443 To create the API route, add the following function to `src/api/checkout_sessions/[id]/route.ts`:
2444
2445 ```ts title="src/api/checkout_sessions/[id]/route.ts"
2446 export const GET = async (
2447 req: MedusaRequest,
2448 res: MedusaResponse
2449 ) => {
2450 const responseHeaders = {
2451 "Idempotency-Key": req.headers["idempotency-key"] as string,
2452 "Request-Id": req.headers["request-id"] as string,
2453 }
2454 try {
2455 const { result } = await prepareCheckoutSessionDataWorkflow(req.scope)
2456 .run({
2457 input: {
2458 cart_id: req.params.id,
2459 },
2460 context: {
2461 idempotencyKey: req.headers["idempotency-key"] as string,
2462 },
2463 })
2464
2465 res.set(responseHeaders).status(200).json(result)
2466 } catch (error) {
2467 const medusaError = error as MedusaError
2468 const statusCode = medusaError.type === MedusaError.Types.NOT_FOUND ? 404 : 500
2469 res.set(responseHeaders).status(statusCode).json({
2470 type: "invalid_request",
2471 code: "request_not_idempotent",
2472 message: statusCode === 404 ? "Checkout session not found" : "Internal server error",
2473 })
2474 }
2475 }
2476 ```
2477
2478 You export a `GET` route handler function, which exposes a `GET` API route at `/checkout_sessions/{id}`.
2479
2480 In the route handler, you execute the `prepareCheckoutSessionDataWorkflow`, passing the cart ID from the URL parameters as input. You return the workflow's response as the API response.
2481
2482 ### Use the Get Checkout Session API
2483
2484 To use the `GET /checkout_sessions/:id` API, you need to:
2485
2486 - Apply to ChatGPT's [Instant Checkout](https://chatgpt.com/merchants) and access a signature key.
2487 - Create an API key in the [Secret API Key Settings](!user-guide!/settings/developer/secret-api-keys) of the Medusa Admin dashboard.
2488 - Setup the API key in the Instant Checkout settings.
2489
2490 ChatGPT will then use it to get a checkout session.
2491
2492 ### Test the Get Checkout Session API Locally
2493
2494 To test out the `GET /checkout_sessions/:id` API locally, send a `GET` request to `/checkout_sessions/{cart_id}`:
2495
2496 ```bash
2497 curl 'http://localhost:9000/checkout_sessions/{cart_id}' \
2498 -H 'Idempotency-Key: idp_123' \
2499 -H 'Request-Id: req_123' \
2500 -H 'Authorization: Bearer {api_key}'
2501 ```
2502
2503 Make sure to replace:
2504
2505 - `{cart_id}` with the cart ID of the checkout session you created earlier.
2506 - `{api_key}` with the API key you created in the Medusa Admin dashboard.
2507
2508 You'll receive in the response the checkout session based on the Agentic Commerce specifications.
2509
2510 ---
2511
2512 ## Step 7: Complete Checkout Session API
2513
2514 Next, you'll implement the `POST /checkout_sessions/{id}/complete` API to complete a checkout session.
2515
2516 The AI agent calls this API route to finalize the checkout process and create an order. This API route will complete the cart, process the payment, and return the final checkout session details. If an error occurs, it resets the cart's payment sessions and returns the checkout session with an error message.
2517
2518 To implement this API route, you'll create:
2519
2520 - A workflow that completes the checkout session.
2521 - An API route that executes the workflow.
2522 - You'll also apply a validation middleware to the API route.
2523
2524 You'll also set up the [Stripe Payment Module Provider](../../../commerce-modules/payment/payment-provider/stripe/page.mdx). ChatGPT currently supports only Stripe as a payment provider.
2525
2526 ### a. Complete Checkout Session Workflow
2527
2528 The workflow that completes a checkout session has the following steps:
2529
2530 <WorkflowDiagram
2531 workflow={{
2532 name: "completeCheckoutSessionWorkflow",
2533 steps: [
2534 {
2535 type: "step",
2536 name: "useQueryGraphStep",
2537 description: "Retrieve the cart details",
2538 link: "/references/helper-steps/useQueryGraphStep",
2539 depth: 1,
2540 },
2541 {
2542 type: "step",
2543 name: "acquireLockStep",
2544 description: "Acquire a lock on the cart to prevent concurrent modifications",
2545 link: "/references/medusa-workflows/steps/acquireLockStep",
2546 depth: 2,
2547 },
2548 {
2549 type: "when",
2550 condition: "!!input.payment_data.billing_address",
2551 steps: [
2552 {
2553 type: "workflow",
2554 name: "updateCartWorkflow",
2555 description: "Update the cart with the billing address",
2556 link: "/references/medusa-workflows/updateCartWorkflow",
2557 depth: 1
2558 }
2559 ],
2560 depth: 3
2561 },
2562 {
2563 type: "when",
2564 condition: "!!data.carts[0].region?.payment_providers?.find((provider) => provider?.id === data.paymentProviderId)",
2565 steps: [
2566 {
2567 type: "workflow",
2568 name: "createPaymentCollectionForCartWorkflow",
2569 description: "Create payment collection for the cart",
2570 link: "/references/medusa-workflows/createPaymentCollectionForCartWorkflow",
2571 depth: 1
2572 },
2573 {
2574 type: "workflow",
2575 name: "createPaymentSessionsWorkflow",
2576 description: "Create payment sessions in the payment collection",
2577 link: "/references/medusa-workflows/createPaymentSessionsWorkflow",
2578 depth: 2
2579 },
2580 {
2581 type: "workflow",
2582 name: "completeCartWorkflow",
2583 description: "Complete the cart",
2584 link: "/references/medusa-workflows/completeCartWorkflow",
2585 depth: 3
2586 },
2587 {
2588 type: "workflow",
2589 name: "prepareCheckoutSessionDataWorkflow",
2590 description: "Prepare the checkout session response",
2591 depth: 4
2592 }
2593 ],
2594 depth: 4
2595 },
2596 {
2597 type: "when",
2598 condition: "!data.carts[0].region?.payment_providers?.find((provider) => provider?.id === data.paymentProviderId)",
2599 steps: [
2600 {
2601 type: "workflow",
2602 name: "prepareCheckoutSessionDataWorkflow",
2603 description: "Prepare the checkout session response with an error message",
2604 depth: 1
2605 }
2606 ],
2607 depth: 5
2608 },
2609 {
2610 type: "step",
2611 name: "releaseLockStep",
2612 description: "Release the lock on the cart",
2613 link: "/references/medusa-workflows/steps/releaseLockStep",
2614 depth: 6,
2615 }
2616 ]
2617 }}
2618 />
2619
2620 These steps and workflows are available in Medusa out-of-the-box. So, you can implement the workflow without creating custom steps.
2621
2622 To create the workflow, create the file `src/workflows/complete-checkout-session.ts` with the following content:
2623
2624 ```ts title="src/workflows/complete-checkout-session.ts" collapsibleLines="1-21" expandButtonLabel="Show Imports"
2625 import {
2626 createWorkflow,
2627 transform,
2628 when,
2629 WorkflowResponse,
2630 } from "@medusajs/framework/workflows-sdk"
2631 import {
2632 acquireLockStep,
2633 completeCartWorkflow,
2634 createPaymentCollectionForCartWorkflow,
2635 createPaymentSessionsWorkflow,
2636 refreshPaymentCollectionForCartWorkflow,
2637 releaseLockStep,
2638 updateCartWorkflow,
2639 useQueryGraphStep,
2640 } from "@medusajs/medusa/core-flows"
2641 import {
2642 prepareCheckoutSessionDataWorkflow,
2643 PrepareCheckoutSessionDataWorkflowInput,
2644 } from "./prepare-checkout-session-data"
2645
2646 type WorkflowInput = {
2647 cart_id: string
2648 buyer?: {
2649 first_name: string
2650 email: string
2651 phone_number?: string
2652 }
2653 payment_data: {
2654 token: string
2655 provider: string
2656 billing_address?: {
2657 name: string
2658 line_one: string
2659 line_two?: string
2660 city: string
2661 state: string
2662 postal_code: string
2663 country: string
2664 phone_number?: string
2665 }
2666 }
2667 }
2668
2669 export const completeCheckoutSessionWorkflow = createWorkflow(
2670 "complete-checkout-session",
2671 (input: WorkflowInput) => {
2672 // Retrieve cart details
2673 const { data: carts } = useQueryGraphStep({
2674 entity: "cart",
2675 fields: [
2676 "id",
2677 "region.*",
2678 "region.payment_providers.*",
2679 "shipping_address.*",
2680 ],
2681 filters: {
2682 id: input.cart_id,
2683 },
2684 options: {
2685 throwIfKeyNotFound: true,
2686 },
2687 })
2688 acquireLockStep({
2689 key: input.cart_id,
2690 timeout: 2,
2691 ttl: 10,
2692 })
2693
2694 // TODO update cart with billing address if provided
2695 }
2696 )
2697 ```
2698
2699 The `completeCheckoutSessionWorkflow` accepts an input with the properties received from the AI agent to complete the checkout session.
2700
2701 So far, you retrieve the cart using the `useQueryGraphStep`, and you acquire a lock on the cart using the `acquireLockStep` to prevent concurrent modifications.
2702
2703 #### Update Cart with Billing Address
2704
2705 Next, you'll update the cart with the billing address if it's provided. Replace the `TODO` in the workflow with the following:
2706
2707 ```ts title="src/workflows/complete-checkout-session.ts"
2708 when(input, (input) => !!input.payment_data.billing_address)
2709 .then(() => {
2710 const updateData = transform({
2711 input,
2712 carts,
2713 }, (data) => {
2714 return {
2715 id: data.carts[0].id,
2716 billing_address: {
2717 first_name: data.input.payment_data.billing_address!.name.split(" ")[0],
2718 last_name: data.input.payment_data.billing_address!.name.split(" ")[1],
2719 address_1: data.input.payment_data.billing_address!.line_one,
2720 address_2: data.input.payment_data.billing_address!.line_two,
2721 city: data.input.payment_data.billing_address!.city,
2722 province: data.input.payment_data.billing_address!.state,
2723 postal_code: data.input.payment_data.billing_address!.postal_code,
2724 country_code: data.input.payment_data.billing_address!.country,
2725 phone: data.input.payment_data.billing_address!.phone_number,
2726 },
2727 }
2728 })
2729 return updateCartWorkflow.runAsStep({
2730 input: updateData,
2731 })
2732 })
2733
2734 // TODO complete cart if payment provider is valid
2735 ```
2736
2737 You use the `when` function to check if a billing address is provided in the input. If it is, you prepare the input for the `updateCartWorkflow` workflow using the `transform` function, and then you update the cart using the `updateCartWorkflow` workflow.
2738
2739 #### Complete Cart if Payment Provider is Valid
2740
2741 Next, you'll complete the cart if the payment provider is valid. Replace the `TODO` in the workflow with the following:
2742
2743 ```ts title="src/workflows/complete-checkout-session.ts"
2744 const preparationInput = transform({
2745 carts,
2746 input,
2747 }, (data) => {
2748 return {
2749 cart_id: data.carts[0].id,
2750 buyer: data.input.buyer,
2751 fulfillment_address: data.carts[0].shipping_address ? {
2752 name: data.carts[0].shipping_address.first_name + " " + data.carts[0].shipping_address.last_name,
2753 line_one: data.carts[0].shipping_address.address_1 || "",
2754 line_two: data.carts[0].shipping_address.address_2 || "",
2755 city: data.carts[0].shipping_address.city || "",
2756 state: data.carts[0].shipping_address.province || "",
2757 postal_code: data.carts[0].shipping_address.postal_code || "",
2758 country: data.carts[0].shipping_address.country_code || "",
2759 phone_number: data.carts[0].shipping_address.phone || "",
2760 } : undefined,
2761 }
2762 })
2763
2764 const paymentProviderId = transform({
2765 input,
2766 }, (data) => {
2767 switch (data.input.payment_data.provider) {
2768 case "stripe":
2769 return "pp_stripe_stripe"
2770 default:
2771 return data.input.payment_data.provider
2772 }
2773 })
2774
2775 const completeCartResponse = when({
2776 carts,
2777 paymentProviderId,
2778 }, (data) => {
2779 // @ts-ignore
2780 return !!data.carts[0].region?.payment_providers?.find((provider) => provider?.id === data.paymentProviderId)
2781 })
2782 .then(() => {
2783 const paymentCollection = createPaymentCollectionForCartWorkflow.runAsStep({
2784 input: {
2785 cart_id: carts[0].id,
2786 },
2787 })
2788
2789 createPaymentSessionsWorkflow.runAsStep({
2790 input: {
2791 payment_collection_id: paymentCollection.id,
2792 provider_id: paymentProviderId,
2793 data: {
2794 shared_payment_token: input.payment_data.token,
2795 },
2796 },
2797 })
2798
2799 completeCartWorkflow.runAsStep({
2800 input: {
2801 id: carts[0].id,
2802 },
2803 })
2804
2805 return prepareCheckoutSessionDataWorkflow.runAsStep({
2806 input: preparationInput,
2807 })
2808 })
2809
2810 // TODO handle invalid payment provider
2811 ```
2812
2813 You use `transform` to prepare the input for the `prepareCheckoutSessionDataWorkflow` workflow and to map the payment provider from the input to the payment provider ID used in your Medusa store.
2814
2815 Then, you use the `when` function to check if the payment provider is valid for the cart's region. If so, you:
2816
2817 - Create a payment collection for the cart using the [createPaymentCollectionForCartWorkflow](/references/medusa-workflows/createPaymentCollectionForCartWorkflow).
2818 - Create payment sessions in the payment collection using the [createPaymentSessionsWorkflow](/references/medusa-workflows/createPaymentSessionsWorkflow).
2819 - Complete the cart using the [completeCartWorkflow](/references/medusa-workflows/completeCartWorkflow).
2820
2821 Finally, you prepare the checkout session response using the `prepareCheckoutSessionDataWorkflow`.
2822
2823 #### Handle Invalid Payment Provider
2824
2825 Next, you'll handle the case where the payment provider is invalid. You'll prepare an error response to return to the AI agent.
2826
2827 Replace the `TODO` in the workflow with the following:
2828
2829 ```ts title="src/workflows/complete-checkout-session.ts"
2830 const invalidPaymentResponse = when({
2831 carts,
2832 paymentProviderId,
2833 }, (data) => {
2834 return !data.carts[0].region?.payment_providers?.find((provider) => provider?.id === data.paymentProviderId)
2835 })
2836 .then(() => {
2837 refreshPaymentCollectionForCartWorkflow.runAsStep({
2838 input: {
2839 cart_id: carts[0].id,
2840 },
2841 })
2842 const prepareDataWithMessages = transform({
2843 prepareData: preparationInput,
2844 }, (data) => {
2845 return {
2846 ...data.prepareData,
2847 messages: [
2848 {
2849 type: "error",
2850 code: "invalid",
2851 content_type: "plain",
2852 content: "Invalid payment provider",
2853 },
2854 ],
2855 } as PrepareCheckoutSessionDataWorkflowInput
2856 })
2857 return prepareCheckoutSessionDataWorkflow.runAsStep({
2858 input: prepareDataWithMessages,
2859 }).config({ name: "prepare-checkout-session-data-with-messages" })
2860 })
2861
2862 // Return response
2863 ```
2864
2865 You use the `when` function to check if the payment provider is invalid for the cart's region.
2866
2867 If so, you refresh the cart's payment sessions using the `refreshPaymentCollectionForCartWorkflow`, then you prepare the input for the `prepareCheckoutSessionDataWorkflow` workflow. You add an error message indicating that the payment provider is invalid.
2868
2869 #### Return Response
2870
2871 Finally, you'll return the appropriate response based on whether the cart was completed or if there was an error. Replace the `TODO` in the workflow with the following:
2872
2873 ```ts title="src/workflows/complete-checkout-session.ts"
2874 const responseData = transform({
2875 completeCartResponse,
2876 invalidPaymentResponse,
2877 }, (data) => {
2878 return data.completeCartResponse || data.invalidPaymentResponse
2879 })
2880
2881 releaseLockStep({
2882 key: input.cart_id,
2883 })
2884
2885 return new WorkflowResponse(responseData)
2886 ```
2887
2888 You use `transform` to pick either the response from completing the cart or the error response for an invalid payment provider.
2889
2890 Then, you release the lock on the cart using the `releaseLockStep` step, and return the response as the workflow's response.
2891
2892 ### b. Complete Checkout Session API Route
2893
2894 Next, you'll create an API route at `POST /checkout_sessions/{id}/complete` that executes the `completeCheckoutSessionWorkflow`.
2895
2896 Create the file `src/api/checkout_sessions/[id]/complete/route.ts` with the following content:
2897
2898 ```ts title="src/api/checkout_sessions/[id]/complete/route.ts" collapsibleLines="1-7" expandButtonLabel="Show Imports"
2899 import { MedusaRequest, MedusaResponse } from "@medusajs/framework"
2900 import { z } from "@medusajs/framework/zod"
2901 import { completeCheckoutSessionWorkflow } from "../../../../workflows/complete-checkout-session"
2902 import { MedusaError } from "@medusajs/framework/utils"
2903 import { refreshPaymentCollectionForCartWorkflow } from "@medusajs/medusa/core-flows"
2904 import { prepareCheckoutSessionDataWorkflow } from "../../../../workflows/prepare-checkout-session-data"
2905
2906 export const PostCompleteSessionSchema = z.object({
2907 buyer: z.object({
2908 first_name: z.string(),
2909 email: z.string(),
2910 phone_number: z.string().optional(),
2911 }).optional(),
2912 payment_data: z.object({
2913 token: z.string(),
2914 provider: z.string(),
2915 billing_address: z.object({
2916 name: z.string(),
2917 line_one: z.string(),
2918 line_two: z.string().optional(),
2919 city: z.string(),
2920 state: z.string(),
2921 postal_code: z.string(),
2922 country: z.string(),
2923 phone_number: z.string().optional(),
2924 }).optional(),
2925 }),
2926 })
2927
2928 export const POST = async (
2929 req: MedusaRequest<
2930 z.infer<typeof PostCompleteSessionSchema>
2931 >,
2932 res: MedusaResponse
2933 ) => {
2934 const responseHeaders = {
2935 "Idempotency-Key": req.headers["idempotency-key"] as string,
2936 "Request-Id": req.headers["request-id"] as string,
2937 }
2938 try {
2939 const { result } = await completeCheckoutSessionWorkflow(req.scope)
2940 .run({
2941 input: {
2942 cart_id: req.params.id,
2943 ...req.validatedBody,
2944 },
2945 context: {
2946 idempotencyKey: req.headers["idempotency-key"] as string,
2947 },
2948 })
2949
2950 res.set(responseHeaders).json(result)
2951 } catch (error) {
2952 const medusaError = error as MedusaError
2953
2954 await refreshPaymentCollectionForCartWorkflow(req.scope).run({
2955 input: {
2956 cart_id: req.params.id,
2957 },
2958 })
2959 const { result } = await prepareCheckoutSessionDataWorkflow(req.scope)
2960 .run({
2961 input: {
2962 cart_id: req.params.id,
2963 ...req.validatedBody,
2964 messages: [
2965 {
2966 type: "error",
2967 code: medusaError.type === MedusaError.Types.PAYMENT_AUTHORIZATION_ERROR ?
2968 "payment_declined" : "invalid",
2969 content_type: "plain",
2970 content: medusaError.message,
2971 },
2972 ],
2973 },
2974 })
2975
2976 res.set(responseHeaders).json(result)
2977 }
2978 }
2979 ```
2980
2981 You first define a validation schema with [Zod](https://zod.dev/) for the request body. The schema matches the [Agentic Commerce request specifications](https://developers.openai.com/commerce/specs/checkout#rest-endpoints).
2982
2983 Then, you export a `POST` route handler function, which exposes a `POST` API route at `/checkout_sessions/{id}/complete`.
2984
2985 In the route handler, you execute the `completeCheckoutSessionWorkflow`, passing the cart ID from the URL parameters and the validated request body as input. You return the workflow's response as the API response.
2986
2987 If an error occurs, you refresh the cart's payment sessions using the `refreshPaymentCollectionForCartWorkflow`, and prepare the checkout session response with an error message using the `prepareCheckoutSessionDataWorkflow`. You return this response.
2988
2989 ### c. Apply Validation Middleware
2990
2991 Finally, you'll apply the validation middleware to the `POST /checkout_sessions/{id}/complete` API route.
2992
2993 In `src/api/middlewares.ts`, add the following import at the top of the file:
2994
2995 ```ts title="src/api/middlewares.ts"
2996 import { PostCompleteSessionSchema } from "./checkout_sessions/[id]/complete/route"
2997 ```
2998
2999 Then, add a new route configuration in `defineMiddlewares`:
3000
3001 ```ts title="src/api/middlewares.ts"
3002 export default defineMiddlewares({
3003 routes: [
3004 // ...
3005 {
3006 matcher: "/checkout_sessions/:id/complete",
3007 method: ["POST"],
3008 middlewares: [validateAndTransformBody(PostCompleteSessionSchema)],
3009 },
3010 ],
3011 // ...
3012 })
3013 ```
3014
3015 You apply the `validateAndTransformBody` middleware to the `POST /checkout_sessions/{id}/complete` route to ensure the request body includes the required fields.
3016
3017 ### d. Setup Stripe Payment Module Provider
3018
3019 To support payments with Stripe, you'll need to set up the [Stripe Payment Module Provider](../../../commerce-modules/payment/payment-provider/stripe/page.mdx) in your Medusa store.
3020
3021 In `medusa-config.ts`, add a new entry to the `modules` array:
3022
3023 ```ts title="medusa-config.ts"
3024 module.exports = defineConfig({
3025 // ...
3026 modules: [
3027 // ...
3028 {
3029 resolve: "@medusajs/medusa/payment",
3030 options: {
3031 providers: [
3032 {
3033 resolve: "@medusajs/medusa/payment-stripe",
3034 id: "stripe",
3035 options: {
3036 apiKey: process.env.STRIPE_API_KEY,
3037 // other options...
3038 },
3039 },
3040 ],
3041 },
3042 },
3043 ],
3044 })
3045 ```
3046
3047 This will add Stripe as a payment provider in your Medusa store.
3048
3049 Make sure to set the `STRIPE_API_KEY` environment variable with your Stripe secret key, which you can retrieve from the [Stripe Dashboard](https://support.stripe.com/questions/locate-api-keys-in-the-dashboard):
3050
3051 ```env title=".env"
3052 STRIPE_API_KEY=sk_test_...
3053 ```
3054
3055 Finally, you must enable Stripe as a payment provider in the US region. Learn how to do that in the [Regions user guide](!user-guide!/settings/regions#edit-region-details).
3056
3057 ### Use the Complete Checkout Session API
3058
3059 To use the `POST /checkout_sessions/:id/complete` API, you need to:
3060
3061 - Apply to ChatGPT's [Instant Checkout](https://chatgpt.com/merchants) and access a signature key.
3062 - Create an API key in the [Secret API Key Settings](!user-guide!/settings/developer/secret-api-keys) of the Medusa Admin dashboard.
3063 - Setup the API key in the Instant Checkout settings.
3064
3065 ChatGPT will then use it to complete a checkout session.
3066
3067 ### Test the Complete Checkout Session API Locally
3068
3069 To test out the `POST /checkout_sessions/:id/complete` API locally, you need to [generate a shared payment token with Stripe](https://docs.stripe.com/agentic-commerce/testing).
3070
3071 Then, send a `POST` request to `http://localhost:9000/signature` with the JSON body to complete the checkout session. For example:
3072
3073 ```bash
3074 curl -X POST 'http://localhost:9000/signature' \
3075 -H 'Content-Type: application/json' \
3076 --data-raw '{
3077 "buyer": {
3078 "first_name": "John",
3079 "email": "johnsmith@gmail.com",
3080 "phone_number": "123"
3081 },
3082 "payment_data": {
3083 "provider": "stripe",
3084 "token": "{token}"
3085 }
3086 }'
3087 ```
3088
3089 Make sure to replace `{token}` with the shared payment token you generated with Stripe.
3090
3091 Then, send a `POST` request to `http://localhost:9000/checkout_sessions/{cart_id}/complete` with the same JSON body, and include the `Authorization` and `Signature` headers:
3092
3093 ```bash
3094 curl -X POST 'http://localhost:9000/checkout_sessions/{cart_id}/complete' \
3095 -H 'Signature: {signature}' \
3096 -H 'Idempotency-Key: idp_123' \
3097 -H 'Request-Id: req_123' \
3098 -H 'Content-Type: application/json' \
3099 -H 'Authorization: Bearer {api_key}' \
3100 --data-raw '{
3101 "buyer": {
3102 "first_name": "John",
3103 "email": "johnsmith@gmail.com",
3104 "phone_number": "123"
3105 },
3106 "payment_data": {
3107 "provider": "stripe",
3108 "token": "{token}"
3109 }
3110 }'
3111 ```
3112
3113 Make sure to replace:
3114
3115 - `{cart_id}` with the cart ID of the checkout session you created earlier.
3116 - `{signature}` with the signature you copied from the previous request.
3117 - `{token}` with the shared payment token you generated with Stripe.
3118 - `{api_key}` with the API key you created in the Medusa Admin dashboard.
3119
3120 You'll receive in the response the completed checkout session based on the Agentic Commerce specifications.
3121
3122 ---
3123
3124 ## Step 8: Cancel Checkout Session API
3125
3126 The last Checkout Session API you'll implement is the `POST /checkout_sessions/{id}/cancel` API to cancel a checkout session.
3127
3128 The AI agent calls this API route to cancel the checkout process. This API route will cancel any authorized payment sessions associated with the cart, update the cart status to canceled, and return the updated checkout session details.
3129
3130 To implement this API route, you'll create:
3131
3132 - A workflow that cancels the checkout session.
3133 - An API route that executes the workflow.
3134
3135 ### a. Cancel Checkout Session Workflow
3136
3137 The workflow that cancels a checkout session has the following steps:
3138
3139 <WorkflowDiagram
3140 workflow={{
3141 name: "cancelCheckoutSessionWorkflow",
3142 steps: [
3143 {
3144 type: "step",
3145 name: "useQueryGraphStep",
3146 description: "Retrieve the cart details",
3147 link: "/references/helper-steps/useQueryGraphStep",
3148 depth: 1,
3149 },
3150 {
3151 type: "step",
3152 name: "validateCartCancelationStep",
3153 description: "Validate if the cart can be canceled",
3154 depth: 2
3155 },
3156 {
3157 type: "step",
3158 name: "acquireLockStep",
3159 description: "Acquire a lock on the cart to prevent concurrent modifications",
3160 link: "/references/medusa-workflows/steps/acquireLockStep",
3161 depth: 3,
3162 },
3163 {
3164 type: "when",
3165 condition: "!!data.carts[0].payment_collection?.payment_sessions?.length",
3166 steps: [
3167 {
3168 type: "workflow",
3169 name: "cancelPaymentSessionsStep",
3170 description: "Cancel payment sessions associated with the cart",
3171 depth: 1
3172 }
3173 ],
3174 depth: 4
3175 },
3176 {
3177 type: "workflow",
3178 name: "updateCartWorkflow",
3179 description: "Update the cart status to canceled",
3180 link: "/references/medusa-workflows/updateCartWorkflow",
3181 depth: 5
3182 },
3183 {
3184 type: "workflow",
3185 name: "prepareCheckoutSessionDataWorkflow",
3186 description: "Prepare the checkout session response",
3187 depth: 6
3188 },
3189 {
3190 type: "step",
3191 name: "releaseLockStep",
3192 description: "Release the lock on the cart",
3193 link: "/references/medusa-workflows/steps/releaseLockStep",
3194 depth: 7
3195 }
3196 ]
3197 }}
3198 />
3199
3200 You only need to implement the `validateCartCancelationStep` and `cancelPaymentSessionsStep` steps. The other steps and workflows are available in Medusa out-of-the-box.
3201
3202 #### validateCartCancelationStep
3203
3204 The `validateCartCancelationStep` step throws an error if the cart cannot be canceled.
3205
3206 To create the step, create the file `src/workflows/steps/validate-cart-cancelation.ts` with the following content:
3207
3208 ```ts title="src/workflows/steps/validate-cart-cancelation.ts"
3209 import { CartDTO, OrderDTO, PaymentCollectionDTO } from "@medusajs/framework/types"
3210 import { MedusaError } from "@medusajs/framework/utils"
3211 import { createStep } from "@medusajs/framework/workflows-sdk"
3212
3213 export type ValidateCartCancelationStepInput = {
3214 cart: CartDTO & {
3215 payment_collection?: PaymentCollectionDTO
3216 order?: OrderDTO
3217 }
3218 }
3219
3220 export const validateCartCancelationStep = createStep(
3221 "validate-cart-cancelation",
3222 async ({ cart }: ValidateCartCancelationStepInput) => {
3223 if (cart.metadata?.checkout_session_canceled) {
3224 throw new MedusaError(
3225 MedusaError.Types.INVALID_DATA,
3226 "Cart is already canceled"
3227 )
3228 }
3229 if (!!cart.order) {
3230 throw new MedusaError(
3231 MedusaError.Types.INVALID_DATA,
3232 "Cart is already associated with an order"
3233 )
3234 }
3235 const invalidPaymentSessions = cart.payment_collection?.payment_sessions
3236 ?.some((session) => session.status === "authorized" || session.status === "canceled")
3237
3238 if (!!cart.completed_at || !!invalidPaymentSessions) {
3239 throw new MedusaError(
3240 MedusaError.Types.INVALID_DATA,
3241 "Cart cannot be canceled"
3242 )
3243 }
3244 }
3245 )
3246 ```
3247
3248 The `validateCartCancelationStep` accepts a cart as input.
3249
3250 In the step, you throw an error if:
3251
3252 - The cart has a `checkout_session_canceled` metadata field set to `true`, indicating it was already canceled.
3253 - The cart is already associated with an order.
3254 - The cart has a `completed_at` date, indicating it was already completed.
3255 - The cart has any payment sessions with a status of `authorized` or `canceled`.
3256
3257 #### cancelPaymentSessionsStep
3258
3259 The `cancelPaymentSessionsStep` step cancels payment sessions associated with the cart.
3260
3261 To create the step, create the file `src/workflows/steps/cancel-payment-sessions.ts` with the following content:
3262
3263 ```ts title="src/workflows/steps/cancel-payment-sessions.ts"
3264 import { promiseAll, Modules } from "@medusajs/framework/utils"
3265 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
3266
3267 type StepInput = {
3268 payment_session_ids: string[]
3269 }
3270
3271 export const cancelPaymentSessionsStep = createStep(
3272 "cancel-payment-session",
3273 async ({ payment_session_ids }: StepInput, { container }) => {
3274 const paymentModuleService = container.resolve(
3275 Modules.PAYMENT
3276 )
3277
3278 const paymentSessions = await paymentModuleService.listPaymentSessions({
3279 id: payment_session_ids,
3280 })
3281
3282 const updatedPaymentSessions = await promiseAll(
3283 paymentSessions.map((session) => {
3284 return paymentModuleService.updatePaymentSession({
3285 id: session.id,
3286 status: "canceled",
3287 currency_code: session.currency_code,
3288 amount: session.amount,
3289 data: session.data,
3290 })
3291 })
3292 )
3293
3294 return new StepResponse(updatedPaymentSessions, paymentSessions)
3295 },
3296 async (paymentSessions, { container }) => {
3297 if (!paymentSessions) {
3298 return
3299 }
3300 const paymentModuleService = container.resolve(
3301 Modules.PAYMENT
3302 )
3303
3304 await promiseAll(
3305 paymentSessions.map((session) => {
3306 return paymentModuleService.updatePaymentSession({
3307 id: session.id,
3308 status: session.status,
3309 currency_code: session.currency_code,
3310 amount: session.amount,
3311 data: session.data,
3312 })
3313 })
3314 )
3315 }
3316 )
3317 ```
3318
3319 The `cancelPaymentSessionsStep` accepts an array of payment session IDs as input.
3320
3321 In the step, you retrieve the payment sessions using the `listPaymentSessions` method of the [Payment Module](../../../commerce-modules/payment/page.mdx)'s service. Then, you update their status to `canceled` using the `updatePaymentSession` method.
3322
3323 You also pass a third argument to the `createStep` function, which is the [compensation function](!docs!/learn/fundamentals/workflows/compensation-function). This function is executed if the workflow execution fails, allowing you to revert any changes made by the step. In this case, you revert the payment sessions to their original status.
3324
3325 #### Cancel Checkout Session Workflow
3326
3327 You can now implement the `cancelCheckoutSessionWorkflow`.
3328
3329 Create the file `src/workflows/cancel-checkout-session.ts` with the following content:
3330
3331 ```ts title="src/workflows/cancel-checkout-session.ts" collapsibleLines="1-6" expandButtonLabel="Show Imports"
3332 import { createWorkflow, transform, when, WorkflowResponse } from "@medusajs/framework/workflows-sdk"
3333 import { validateCartCancelationStep, ValidateCartCancelationStepInput } from "./steps/validate-cart-cancelation"
3334 import { acquireLockStep, releaseLockStep, updateCartWorkflow, useQueryGraphStep } from "@medusajs/medusa/core-flows"
3335 import { cancelPaymentSessionsStep } from "./steps/cancel-payment-sessions"
3336 import { prepareCheckoutSessionDataWorkflow } from "./prepare-checkout-session-data"
3337
3338 type WorkflowInput = {
3339 cart_id: string
3340 }
3341
3342 export const cancelCheckoutSessionWorkflow = createWorkflow(
3343 "cancel-checkout-session",
3344 (input: WorkflowInput) => {
3345 const { data: carts } = useQueryGraphStep({
3346 entity: "cart",
3347 fields: [
3348 "id",
3349 "payment_collection.*",
3350 "payment_collection.payment_sessions.*",
3351 "order.id",
3352 ],
3353 filters: {
3354 id: input.cart_id,
3355 },
3356 options: {
3357 throwIfKeyNotFound: true,
3358 },
3359 })
3360
3361 validateCartCancelationStep({
3362 cart: carts[0],
3363 } as unknown as ValidateCartCancelationStepInput)
3364
3365 acquireLockStep({
3366 key: input.cart_id,
3367 timeout: 2,
3368 ttl: 10,
3369 })
3370
3371 // TODO cancel payment sessions if any
3372 }
3373 )
3374 ```
3375
3376 The `cancelCheckoutSessionWorkflow` accepts an input with the cart ID of the checkout session to cancel.
3377
3378 So far, you:
3379
3380 1. Retrieve the cart using the `useQueryGraphStep` step.
3381 2. Validate that the cart can be canceled using the `validateCartCancelationStep`.
3382 3. Acquire a lock on the cart using the `acquireLockStep` to prevent concurrent modifications.
3383
3384 Next, you'll cancel the payment sessions if there are any. Replace the `TODO` in the workflow with the following:
3385
3386 ```ts title="src/workflows/cancel-checkout-session.ts"
3387 when({
3388 carts,
3389 }, (data) => !!data.carts[0].payment_collection?.payment_sessions?.length)
3390 .then(() => {
3391 const paymentSessionIds = transform({
3392 carts,
3393 }, (data) => {
3394 return data.carts[0].payment_collection?.payment_sessions?.map((session) => session!.id)
3395 })
3396 cancelPaymentSessionsStep({
3397 payment_session_ids: paymentSessionIds,
3398 })
3399 })
3400
3401 updateCartWorkflow.runAsStep({
3402 input: {
3403 id: carts[0].id,
3404 metadata: {
3405 checkout_session_canceled: true,
3406 },
3407 },
3408 })
3409
3410 // TODO prepare and return response
3411 ```
3412
3413 You use the `when` function to check if the cart has any payment sessions. If so, you prepare an array with the payment session IDs using the `transform` function and then you cancel the payment sessions using the `cancelPaymentSessionsStep`.
3414
3415 You also update the cart using the `updateCartWorkflow` workflow to add a `checkout_session_canceled` metadata field to the cart. This is useful to detect canceled checkout sessions in the future.
3416
3417 Finally, you'll prepare the checkout session response, release the lock, and return the response. Replace the `TODO` in the workflow with the following:
3418
3419 ```ts title="src/workflows/cancel-checkout-session.ts"
3420 const responseData = prepareCheckoutSessionDataWorkflow.runAsStep({
3421 input: {
3422 cart_id: carts[0].id,
3423 },
3424 })
3425
3426 releaseLockStep({
3427 key: input.cart_id,
3428 })
3429
3430 return new WorkflowResponse(responseData)
3431 ```
3432
3433 You prepare the checkout session response using the `prepareCheckoutSessionDataWorkflow` workflow, then you release the lock on the cart using the `releaseLockStep`. Finally, you return the response.
3434
3435 ### b. Cancel Checkout Session API Route
3436
3437 Next, you'll create a `POST` API route at `/checkout_sessions/{id}/cancel` that executes the `cancelCheckoutSessionWorkflow`.
3438
3439 Create the file `src/api/checkout_sessions/[id]/cancel/route.ts` with the following content:
3440
3441 ```ts title="src/api/checkout_sessions/[id]/cancel/route.ts"
3442 import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
3443 import { cancelCheckoutSessionWorkflow } from "../../../../workflows/cancel-checkout-session"
3444 import { MedusaError } from "@medusajs/framework/utils"
3445
3446 export const POST = async (
3447 req: MedusaRequest,
3448 res: MedusaResponse
3449 ) => {
3450 const responseHeaders = {
3451 "Idempotency-Key": req.headers["idempotency-key"] as string,
3452 "Request-Id": req.headers["request-id"] as string,
3453 }
3454 try {
3455 const { result } = await cancelCheckoutSessionWorkflow(req.scope)
3456 .run({
3457 input: {
3458 cart_id: req.params.id,
3459 },
3460 context: {
3461 idempotencyKey: req.headers["idempotency-key"] as string,
3462 },
3463 })
3464
3465 res.set(responseHeaders).json(result)
3466 } catch (error) {
3467 const medusaError = error as MedusaError
3468 res.set(responseHeaders).status(405).json({
3469 messages: [
3470 {
3471 type: "error",
3472 code: "invalid",
3473 content_type: "plain",
3474 content: medusaError.message,
3475 },
3476 ],
3477 })
3478 }
3479 }
3480 ```
3481
3482 You export a `POST` route handler function, which exposes a `POST` API route at `/checkout_sessions/{id}/cancel`.
3483
3484 In the route handler, you execute the `cancelCheckoutSessionWorkflow`, passing the cart ID from the URL parameters as input. You return the workflow's response as the API response.
3485
3486 ### Use the Cancel Checkout Session API
3487
3488 To use the `POST /checkout_sessions/:id/cancel` API, you need to:
3489
3490 - Apply to ChatGPT's [Instant Checkout](https://chatgpt.com/merchants) and access a signature key.
3491 - Create an API key in the [Secret API Key Settings](!user-guide!/settings/developer/secret-api-keys) of the Medusa Admin dashboard.
3492 - Setup the API key in the Instant Checkout settings.
3493
3494 ChatGPT will then use it to cancel a checkout session.
3495
3496 ### Test the Cancel Checkout Session API Locally
3497
3498 To test out the `POST /checkout_sessions/:id/cancel` API locally, send a `POST` request to `/checkout_sessions/{cart_id}/cancel`:
3499
3500 ```bash
3501 curl -X POST 'http://localhost:9000/checkout_sessions/{cart_id}/cancel' \
3502 -H 'Idempotency-Key: idp_123' \
3503 -H 'Request-Id: req_123' \
3504 -H 'Authorization: Bearer {api_key}'
3505 ```
3506
3507 Make sure to replace:
3508
3509 - `{cart_id}` with the cart ID of the checkout session you created earlier.
3510 - `{api_key}` with the API key you created in the Medusa Admin dashboard.
3511
3512 You'll receive in the response the canceled checkout session based on the Agentic Commerce specifications.
3513
3514 ---
3515
3516 ## Step 9: Send Webhook Events to AI Agent
3517
3518 In the last step, you'll send webhook events to AI agents when orders are placed or updated. This informs AI agents about order updates, as specified in [Agentic Commerce specifications](https://developers.openai.com/commerce/specs/checkout#webhooks).
3519
3520 To send webhook events to AI agents on order updates, you'll create a [subscriber](!docs!/learn/fundamentals/events-and-subscribers). A subscriber is an asynchronous function that listens to events to perform tasks.
3521
3522 In this case, you'll create a subscriber that listens to `order.placed` and `order.updated` events to send webhook events to AI agents.
3523
3524 Create the file `src/subscribers/order-webhooks.ts` with the following content:
3525
3526 ```ts title="src/subscribers/order-webhooks.ts"
3527 import type {
3528 SubscriberArgs,
3529 SubscriberConfig,
3530 } from "@medusajs/framework"
3531 import { AGENTIC_COMMERCE_MODULE } from "../modules/agentic-commerce"
3532 import { AgenticCommerceWebhookEvent } from "../modules/agentic-commerce/service"
3533 import {
3534 ContainerRegistrationKeys,
3535 MedusaError,
3536 } from "@medusajs/framework/utils"
3537
3538 export default async function orderWebhookHandler({
3539 event: { data, name },
3540 container,
3541 }: SubscriberArgs<{ id: string }>) {
3542 const orderId = data.id
3543 const query = container.resolve(
3544 ContainerRegistrationKeys.QUERY
3545 )
3546 const agenticCommerceModuleService = container.resolve(AGENTIC_COMMERCE_MODULE)
3547 const configModule = container.resolve(
3548 ContainerRegistrationKeys.CONFIG_MODULE
3549 )
3550 const storefrontUrl = configModule.admin.storefrontUrl || process.env.STOREFRONT_URL
3551
3552 if (!storefrontUrl) {
3553 throw new MedusaError(
3554 MedusaError.Types.INVALID_DATA,
3555 "A storefront URL is required to send ACP order webhooks"
3556 )
3557 }
3558
3559 // retrieve order
3560 const { data: [order] } = await query.graph({
3561 entity: "order",
3562 fields: [
3563 "id",
3564 "cart.id",
3565 "cart.metadata",
3566 "status",
3567 "fulfillments.*",
3568 "transactions.*",
3569 ],
3570 filters: {
3571 id: orderId,
3572 },
3573 })
3574
3575 // only send webhook if order is associated with a checkout session
3576 if (!order || !order.cart?.metadata?.is_checkout_session) {
3577 return
3578 }
3579
3580 // set status based on order and fulfillments
3581 const fulfillments = (order.fulfillments || []).filter(
3582 (fulfillment) => !!fulfillment
3583 )
3584 let status: AgenticCommerceWebhookEvent["data"]["status"] =
3585 "confirmed"
3586
3587 if (order.status === "canceled") {
3588 status = "canceled"
3589 } else if (
3590 fulfillments.length > 0 &&
3591 fulfillments.every((f) => !!f.delivered_at)
3592 ) {
3593 status = "completed"
3594 } else if (
3595 fulfillments.length > 0 &&
3596 fulfillments.every((f) => !!f.shipped_at)
3597 ) {
3598 status = "shipped"
3599 }
3600
3601 // prepare webhook event
3602 const webhookEvent: AgenticCommerceWebhookEvent = {
3603 type: name === "order.placed" ?
3604 "order_create" : "order_update",
3605 data: {
3606 type: "order",
3607 id: order.id,
3608 checkout_session_id: order.cart.id,
3609 permalink_url: `${storefrontUrl}/orders/${order.id}`,
3610 status,
3611 adjustments: order.transactions?.filter(
3612 (transaction) => transaction?.reference === "refund"
3613 ).map((transaction) => ({
3614 id: transaction!.id,
3615 type: "refund",
3616 occurred_at: new Date(
3617 transaction!.created_at
3618 ).toISOString(),
3619 status: "completed",
3620 // eslint-disable-next-line @medusajs/prices-in-major-units
3621 amount: Math.abs(transaction!.amount) * 100,
3622 })) || [],
3623 },
3624 }
3625
3626 // send webhook event
3627 await agenticCommerceModuleService.sendWebhookEvent(webhookEvent)
3628 }
3629
3630 export const config: SubscriberConfig = {
3631 event: ["order.placed", "order.updated"],
3632 }
3633 ```
3634
3635 A subscriber file must export:
3636
3637 1. An asynchronous function, which is the subscriber that executes when events are emitted.
3638 2. A configuration object that holds names of events the subscriber listens to, which are `order.placed` and `order.updated` in this case.
3639
3640 The subscriber function receives an object as a parameter that has a `container` property, which is the [Medusa container](!docs!/learn/fundamentals/medusa-container).
3641
3642 In the subscriber function, you:
3643
3644 - Retrieve orders using Query. You filter by order IDs received in event data.
3645 - If orders don't exist or if order carts don't have the `is_checkout_session` metadata field, you return early since orders are not associated with checkout sessions.
3646 - Map the order's status and fulfillments to an ACP order status. You check the `completed` case before the `shipped` case, since delivered fulfillments are also shipped. You also require at least one fulfillment, because `Array.prototype.every` returns `true` for an empty array and would otherwise report an unfulfilled order as shipped.
3647 - Map refund transactions to the `adjustments` array. Medusa stores refunds as negative amounts, so you use the absolute value.
3648 - Prepare webhook event payloads based on order data, following the [ACP `2026-04-17` webhook schema](https://github.com/agentic-commerce-protocol/agentic-commerce-protocol/blob/main/spec/2026-04-17/openapi/openapi.agentic_checkout_webhook.yaml).
3649 - Send webhook events to AI agents using the `sendWebhookEvent` method of the Agentic Commerce Module's service.
3650
3651 <Note title="Tip">
3652
3653 Extract the payload-building logic into an exported function, such as `buildOrderWebhookEvent`, if you want to unit test the status and adjustment mapping without emitting events. You can find an example in the [tutorial's repository](https://github.com/medusajs/examples/tree/main/agentic-commerce).
3654
3655 </Note>
3656
3657 ### Use Order Webhook Events in ChatGPT
3658
3659 To use order webhook events in ChatGPT:
3660
3661 - Apply to ChatGPT's [Instant Checkout](https://chatgpt.com/merchants) and access a signature key.
3662 - Set up webhook URLs in Instant Checkout settings and update `sendWebhookEvent` to use webhook URLs from the settings.
3663
3664 ChatGPT will then receive webhook events when orders are placed or updated.
3665
3666 ### Test Order Webhook Events Locally
3667
3668 To test order webhook events locally and ensure they're being sent correctly:
3669
3670 1. Start the Medusa server.
3671 2. [Create a checkout session](#test-the-create-checkout-session-api-locally).
3672 3. [Complete the checkout session](#test-the-complete-checkout-session-api-locally).
3673 4. Check the logs of your Medusa server to see that `order.placed` events were emitted and webhook events were sent to AI agents.
3674
3675 ---
3676
3677 ## Next Steps
3678
3679 You've now built Agentic Commerce integration in your Medusa store. You can use it once you apply to ChatGPT's [Instant Checkout](https://chatgpt.com/merchants) and set up the integration in Instant Checkout settings.
3680
3681 If you're new to Medusa, check out the [main documentation](!docs!/learn), where you'll get more in-depth understanding of all concepts used in this guide and more.
3682
3683 To learn more about commerce features that Medusa provides, check out Medusa's [Commerce Modules](../../../commerce-modules/page.mdx).
3684
3685 ### Troubleshooting
3686
3687 If you encounter issues during development, check out the [troubleshooting guides](../../../troubleshooting/page.mdx).
3688
3689 ### Getting Help
3690
3691 If you encounter issues not covered in troubleshooting guides:
3692
3693 1. Visit the [Medusa GitHub repository](https://github.com/medusajs/medusa) to report issues or ask questions.
3694 2. Join the [Medusa Discord community](https://discord.gg/medusajs) for real-time support from community members.