IntegrationsShopify

Shopify Custom Actions

Give your bot direct access to the Shopify Admin GraphQL API: cancel orders, edit addresses, issue refunds, look up customers, with Python actions that call Shopify through Octocom.

Anything you want your bot to do in Shopify — look up a customer, read an order, cancel it, edit a shipping address, issue a partial refund, apply a discount, read metafields, tag an order — you build as a Python custom action.

There is no catalogue of pre-built Shopify operations to pick from, and that's deliberate. A wrapper per operation is always a step behind what you actually need. Instead, your action sends any Admin GraphQL query or mutation through shopify_graphql, and Octocom calls Shopify for it with the store's access token.

So the rule of thumb is simple: if the Shopify Admin API can do it, your bot can do it. No allowlist, no feature gate. The only ceiling is the scopes your Shopify integration was granted.

For the most common read there are two plain helpers, shopify_get_order and shopify_find_orders. They are built on shopify_graphql, return the order in Shopify's GraphQL shape and their full source is on that page, so you can use them as they are or copy them as a starting point.

This page is the playbook.


Start here: have Copilot or MCP build it

You don't have to write any of this by hand. Both Octocom Copilot and an agent connected to the Octocom MCP can create, edit, and test custom actions for you — this is the fastest way to go from "the bot should be able to do X" to a working action.

Describe the outcome in plain language:

"Create a Python action called updateShopifyOrderAddress that takes an order ID and a new shipping address, refuses if the order is already fulfilled, updates the shipping address with the Shopify Admin GraphQL API, and tags the conversation address-changed."

The agent writes the code, creates the action, and can run a test against a real order. Because it can also read your workflows, bot rules, and past conversations, the most productive loop is to point it at a real conversation that went wrong and ask it to build the action that would have fixed it.

Every change is scoped to your organisation, and in Copilot every change requires your approval before it is applied. See Octocom Copilot and Octocom MCP for setup.

The rest of this page is what the agent is writing on your behalf — worth understanding so you can review its work, and necessary if you'd rather write it yourself.


Identify the storefront customer

The Shopify theme widget and inline embed automatically attach the logged-in storefront customer's identity to new conversations. Email and name populate the Octocom customer record. The Shopify ID and store domain are available as conversation metadata, including to actions created through Copilot or MCP:

def execute_action(context):
    customer_id = get_conversation_metadata(context, "chat-widget:shopify_customer_id")
    shop_domain = get_conversation_metadata(context, "chat-widget:shopify_shop_domain")
    if not customer_id:
        return {"status": "email_required"}
    return {
        "customerId": customer_id,
        "customerGid": f"gid://shopify/Customer/{customer_id}",
        "shopDomain": shop_domain,
    }

The ID is Shopify's numeric ID stored as a string. Convert it to the gid://shopify/Customer/... format when querying the GraphQL Admin API. Query the conversation's configured business and store with shopify_graphql. The browser-supplied shop domain is context, not a trusted credential or permission selector.

For visitors without a detected Shopify account, an action can ask for their account email and look it up instead. Browser metadata can be edited by the visitor, so sensitive account information and mutations still need the relevant customer authentication. See logged-in customer detection for refresh timing, account changes and supported storefronts.

Calling Shopify: shopify_graphql

Call the Shopify Admin API with shopify_graphql(context, query, variables, api_version=..., shop=...). Octocom sends the request from its own servers with the store's access token: your code never holds a Shopify token, and every request comes from Octocom's fixed IP address, which Shopify's IP allowlist requires.

SHOPIFY_API_VERSION = "2026-10"

ORDER_QUERY = """
query Order($id: ID!) {
  order(id: $id) { id name displayFulfillmentStatus cancelledAt }
}
"""

def execute_action(context):
    order_id = str(context["args"]["orderId"]).strip()
    result = shopify_graphql(
        context,
        ORDER_QUERY,
        {"id": f"gid://shopify/Order/{order_id}"},
        api_version=SHOPIFY_API_VERSION,
    )
    if result.get("errors"):
        return {"success": False, "error": "Shopify could not load the order."}
    return {"success": True, "order": (result.get("data") or {}).get("order")}
  • Pass the API version explicitly. Octocom accepts only versions Shopify still supports (currently 2026-01, 2026-04, 2026-07 and 2026-10) and refuses the rest. When a version retires, Octocom moves existing automations to a newer one.
  • GraphQL only. Shopify made the REST Admin API legacy in October 2024, and it is not available from Python. Everything the REST API did has a GraphQL equivalent. For order lookups, start from shopify_get_order and shopify_find_orders.
  • You get Shopify's response body (data, errors, extensions). Check errors and each mutation's userErrors. Throttled requests are retried for you.

Never ask for, store or hardcode a Shopify token. shopify_graphql is the only supported way to reach the Shopify Admin API from Python.

Multi-store businesses

Without shop, shopify_graphql uses the current business's first connected store. If a business runs several stores, name the one you want by its myshopify.com domain. get_integration_credentials(context) lists every connected store (oldest first):

slug = (context.get("business") or {}).get("slug")
shopify = (get_integration_credentials(context).get(slug) or {}).get("shopify") or {}
for store in shopify.get("stores") or []:
    result = shopify_graphql(context, ORDER_QUERY, {"id": gid}, api_version=SHOPIFY_API_VERSION, shop=store["domain"])
    # try each store until you find the order

A worked example: cancelling an unfulfilled order

This is the shape most write actions end up taking — look up state, check guards, act, report back in terms the bot can use.

SHOPIFY_API_VERSION = "2026-10"

ORDER_QUERY = """
query Order($id: ID!) {
  order(id: $id) { id name cancelledAt displayFulfillmentStatus }
}
""".strip()

CANCEL_MUTATION = """
mutation OrderCancel($orderId: ID!, $refundMethod: OrderCancelRefundMethodInput!,
                     $restock: Boolean!, $reason: OrderCancelReason!, $notifyCustomer: Boolean) {
  orderCancel(orderId: $orderId, refundMethod: $refundMethod, restock: $restock,
              reason: $reason, notifyCustomer: $notifyCustomer) {
    job { id done }
    orderCancelUserErrors { field message code }
  }
}
""".strip()

def execute_action(context):
    order_gid = f"gid://shopify/Order/{str(context['args']['orderId']).strip()}"

    # 1. Read the order first — never act blind.
    read = shopify_graphql(context, ORDER_QUERY, {"id": order_gid}, api_version=SHOPIFY_API_VERSION)
    order = (read.get("data") or {}).get("order")
    if not order:
        return {"success": False, "error": "Order not found."}

    # 2. Guards. Refuse anything ambiguous rather than guessing.
    if order.get("cancelledAt"):
        return {"success": False, "error": "This order is already cancelled."}

    if order.get("displayFulfillmentStatus") != "UNFULFILLED":
        return {
            "success": False,
            "error": "This order has already shipped and cannot be cancelled.",
        }

    # 3. Act.
    result = shopify_graphql(
        context,
        CANCEL_MUTATION,
        {
            "orderId": order["id"],
            "refundMethod": {"originalPaymentMethodsRefund": True},
            "restock": True,
            "reason": "CUSTOMER",
            "notifyCustomer": True,
        },
        api_version=SHOPIFY_API_VERSION,
    )

    errors = result.get("errors") or (((result.get("data") or {}).get("orderCancel") or {})
              .get("orderCancelUserErrors")) or []
    if errors:
        return {"success": False, "error": "Shopify refused the cancellation."}

    # 4. Report structured, customer-safe output.
    add_conversation_tag(context, "order-cancelled")
    return {
        "success": True,
        "order_name": order.get("name"),
        "refunded_to_original_payment": True,
    }

Notice the pattern: the action decides, not the bot. The workflow instruction is just "call cancelShopifyOrder with the order ID" — every rule about what is and isn't cancellable lives in Python, where it can't be argued out of by a persistent customer.


Test with real test orders

This is the part most people skip, and it's the part that matters. Shopify write actions are irreversible — a cancelled order stays cancelled, a refund stays refunded. Test against orders you created on purpose.

The loop:

  1. Create a test order in Shopify. Use a draft order, a 100%-off discount code, or Shopify's Bogus Gateway so no real money moves. Make it look like the real thing: right product, right variant, right fulfilment state.
  2. Run the action from the dashboard. Open the action, fill in the test arguments (the order ID), and click Run Test. You get the raw return value back, plus any error.
  3. Check Shopify. Confirm the order actually changed the way you expected — not just that the action returned success: True.
  4. Test the guards, not just the happy path. Run it against an already-fulfilled order, an already-cancelled order, and a nonexistent order ID. Each should return a clean, readable error rather than a stack trace.
  5. Then test it through the bot. Enable the action in a workflow and drive a real conversation at it. Passing a direct test only proves the code works; it doesn't prove the bot calls it at the right moment with the right arguments.

If your action reads conversation data — metadata, tags, message history — pass a Conversation ID in the test panel so context["conversation"] is populated with real data. Keep a test conversation open in another tab, send messages to set up the state you want, then re-run.

See Testing for the full test-panel reference.


Guardrails worth building in

Hard-won patterns from stores running Shopify write actions in production:

  • Read before you write. Always query the order and check its state before mutating it. Fulfilment status, cancellation status, and financial status all change what's safe to do.
  • Refuse ambiguity. If the customer has three active subscriptions and you can't tell which one they mean, don't guess — return an error and let the bot hand off. A wrong write costs more than a handoff.
  • Carve out the cases that must never be automated. Prepaid orders, wholesale orders, orders under manual review. Detect them explicitly and return a "hand off to a human" result rather than proceeding.
  • Make actions idempotent where you can. If the change has already been applied, return success with an "already done" flag instead of applying it twice.
  • Never fail a completed write. If step 1 succeeded and step 2 failed, return success: True with a flag telling the bot a human needs to finish the job. The bot must not tell the customer the cancellation failed when the money has already moved.
  • Return customer-safe output. Whatever you return may end up in the reply. Don't leak internal SKUs, error strings, or reasons — return a clean summary and, if a handoff is needed, an explicit instruction for what the bot should say.
  • Check userErrors. A mutation Shopify refused still answers HTTP 200; the reason is in the mutation's userErrors.

Next steps

On this page