How to Swap Products in an Order Using Shopify API?

Hi, I’m working on a solution to swap products in an order using the Shopify API. Specifically, when an order contains the product SAMPLE1, I need to remove it and replace it with SAMPLE2, keeping the same quantity. I’ve been using the PUT /admin/api/2024-10/orders/{orderId}.json endpoint to update the order with the new product, but I’ts not working

Here’s how I’ve been handling it:

  1. Fetch the variant ID for SAMPLE2 using the GET /admin/api/2024-10/products.json?sku=SAMPLE2 endpoint.
  2. Filter the old SAMPLE1 item out of the order’s line items.
  3. Add the new item (SAMPLE2) to the line items with the same quantity.
  4. Update the order using the PUT /admin/api/2024-10/orders/{orderId}.json endpoint.

Can someone confirm if this is the right way to handle the product swap, or should I be using different endpoints to remove the old product and add the new one? Also, are there any potential issues I should be aware of when swapping products this way?

Thanks for the help!

Hi Jeremiah,

You’re definitely on the right track trying to swap products in an order, but I’d recommend leveraging Shopify’s Order Editing API instead of modifying the order directly using the PUT /orders endpoint. This is because the Order Editing API is specifically designed for making adjustments like adding, removing, or replacing line items in existing orders, and it ensures compliance with Shopify’s system rules (e.g., handling inventory, taxes, discounts, and notifications properly).

Here’s a simplified process to swap SAMPLE1 with SAMPLE2:

  1. Start an Order Edit Session: Use the orderEditBegin mutation to initiate an editing session for the order.

  2. Remove the Existing Product: Use the orderEditRemoveLineItem mutation to remove SAMPLE1 from the order.

  3. Add the New Product: Use the orderEditAddVariant mutation to add SAMPLE2 to the order, ensuring the same quantity is maintained.

  4. Commit the Changes: Finalize the updates with the orderEditCommit mutation. You can also choose whether to notify the customer about these changes.

This approach ensures that Shopify properly recalculates taxes, discounts, and any price differences, so you don’t have to handle them manually. It also respects the fulfillment and inventory statuses of the products.

One thing to note: If the order is partially or fully fulfilled, you’ll face some restrictions, as Shopify doesn’t allow editing fulfilled items. Make sure to check the order’s fulfillment status before proceeding.

Feel free to ping me if you have more questions!

Cheers,
Shubham | Untechnickle