# CustomGiants commerce integration examples

The examples assume an approved reseller or commerce-agent account and, for orders, a live supplier-approved SKU. Get a server-side API credential from the partner portal. The reference lists supported requests and the current protocol version. [OpenAPI specification](https://customgiants.com/api/v1/openapi.json)

## Custom application

This Python client uses the standard library. Set `CG_API_KEY` in your server's secret store. It never reads or sends payment-card data. A public discovery request can omit the key. Set `CG_API_BASE` to your development deployment when testing.

```python
import hashlib
import json
import os
from urllib.error import HTTPError
from urllib.parse import urlencode
from urllib.request import Request, urlopen
from uuid import UUID

API_BASE = os.getenv("CG_API_BASE", "https://customgiants.com/api/v1").rstrip("/")


def call(path, payload=None, *, key=None, operation=None, customer_grant=None):
    headers = {"Accept": "application/json"}
    data = None
    if payload is not None:
        data = json.dumps(payload, sort_keys=True, separators=(",", ":")).encode()
        headers["Content-Type"] = "application/json"
    if key:
        headers["Authorization"] = f"Bearer {key}"
    if operation:
        headers["Idempotency-Key"] = operation
    if customer_grant:
        headers["X-CG-Customer-Grant"] = customer_grant

    request = Request(API_BASE + path, data=data, headers=headers)
    try:
        with urlopen(request, timeout=15) as result:
            return json.load(result)
    except HTTPError as error:
        # Route validation failures to the operator. Keep error messages and
        # customer details out of public logs.
        raise RuntimeError(f"CustomGiants returned HTTP {error.code}") from error


def catalog_search(words, family):
    query = urlencode({"q": words, "category": family})
    return call("/products/?" + query)


def quote(sku, qty, state=None, event_date=None):
    inputs = {"sku": sku, "qty": qty}
    if state:
        inputs["state"] = state
    if event_date:
        inputs["event_date"] = event_date
    return call("/quotes/", inputs, key=os.environ.get("CG_API_KEY"))


def prepare_order(store_id, store_order_id, email, address, lines, blind=False):
    # Persist this key AND this exact payload before making the network request.
    reference = f"{store_id}/{store_order_id}"
    operation = hashlib.sha256(reference.encode()).hexdigest()
    payload = {
        "email": email,
        "address": address,
        "lines": lines,
        "reference": reference,
        "blind_shipping": blind,
    }
    return operation, payload


def submit_saved_order(operation, payload):
    return call("/orders/", payload, key=os.environ["CG_API_KEY"], operation=operation)


def review_cart(lines):
    return call("/handoffs/", {"lines": lines}, key=os.environ["CG_API_KEY"])


def agent_order_status(order_id, customer_grant):
    return call(
        f"/orders/{UUID(str(order_id))}/",
        key=os.environ["CG_API_KEY"],
        customer_grant=customer_grant,
    )
```

For discovery, call `catalog_search("feather", "flags")`, then read `GET /variants/` for verified configurations. A product slug identifies a product family or concept. Use the actual variant SKU when quoting or ordering. If no applicable variant is available, route the buyer to a quote request. Read `unit`, `total` and `savings` as USD cents.

Wholesale quotes may also contain `suggested_resale_unit`. It applies the reseller's saved percentage markup to the quoted wholesale unit price and rounds half up to a whole cent. A synthetic $10.00 wholesale unit at a 20% markup gives `unit=1000` and `suggested_resale_unit=1200`. Use `unit` and `total` when showing the reseller's purchase cost, and display the suggested resale value separately. The reseller sets their customer-facing price in their own store. Retail quote clients should tolerate this field being absent.

For the first wholesale purchase, store the result of `prepare_order` as a durable job. The recipient address contains `name`, `street`, optional `line2`, `city`, a two-letter US `state` and `zip`. Each line contains `sku` and `qty`. Confirm the quote and blind-shipping eligibility, then submit the saved job. Store the returned `id` with the original order and open `account_url` as the authorized reseller to pay. If the response is lost, retry the same job with the same key. A payload conflict requires reconciliation with the original job. Back off after rate-limit or transient service responses.

For a customer-led purchase, call `review_cart` with the approved lines and present the returned `url`. The link expires in 1,800 seconds. The buyer reviews current retail prices and chooses whether to replace the contents of their bag. A wholesale API order uses the reseller's account and its own payment process.

### Artwork and order status

Send a multipart POST to `/artwork/` with fields `order` and `file`. Use the returned wholesale order UUID and an authorized PNG, JPEG or WebP file up to 8 MiB and 16 megapixels. Read the support reference from `ticket`. The ticket belongs to the signed-in reseller and authorized staff. Staff prepare a proof for customer approval before production.

Use `GET /orders/{uuid}/` with a server-held key carrying `orders:read` to retrieve that reseller's order. Display order and shipment status to the authorized operator. Keep wholesale prices, the account payment link and customer contact data out of shared storefront views.

### Customer-authorized agent status

An approved commerce agent can read the status of one customer-owned order through `GET /api/v1/orders/{id}/`. The customer signs in, opens that order, enters the approved agent's identifier under **Authorize a commerce agent**, and issues the seven-day grant. The customer shares the grant privately with the named agent and can revoke it from the same order page.

Call `agent_order_status(order_id, customer_grant)` with the agent's server-held `orders:read` bearer key and the customer grant. The request sends the grant in the `X-CG-Customer-Grant` header. Scope the stored grant to that customer, order and agent. The successful response contains `id`, `status`, and `shipments`, whose entries contain `carrier`, `tracking` and `link`. A missing, mismatched, expired or revoked grant returns 403 for an otherwise authorized agent. Request fresh customer authorization if access is needed again.

## Shopify

A Shopify app can subscribe to the `orders/paid` topic with the necessary store access. Verify the raw HTTPS body using the app's client secret and the base64 `X-Shopify-Hmac-SHA256` header before queuing an order. Shopify's app libraries can perform this verification. Retain the delivery identifier for deduplication, and use the store order ID for the separate CustomGiants idempotency key. [Shopify webhook topics](https://shopify.dev/docs/api/admin-graphql/latest/enums/WebhookSubscriptionTopic#enums-ORDERS_PAID) · [Shopify delivery verification](https://shopify.dev/docs/apps/build/webhooks/verify-deliveries)

The following mapping consumes a verified Shopify paid-order payload. `managed_variants` maps the shop's variant IDs to verified CustomGiants SKUs. Separately assign unrelated lines to their appropriate supplier. If an intended CustomGiants line is missing a mapping, pause that job for review. A store must have access to the customer fields used by its fulfillment adapter. [Shopify protected customer data](https://shopify.dev/docs/apps/launch/protected-customer-data)

```python
def shopify_job(shop_domain, paid_order, managed_variants, fulfilled_line_ids):
    shipping = paid_order["shipping_address"]
    if shipping["country_code"] != "US":
        raise ValueError("Request a destination quote before submitting this order.")
    address = {
        "name": shipping["name"],
        "street": shipping["address1"],
        "line2": shipping.get("address2") or "",
        "city": shipping["city"],
        "state": shipping["province_code"],
        "zip": shipping["zip"],
    }
    lines = [
        {"sku": managed_variants[str(line["variant_id"])], "qty": line["quantity"]}
        for line in paid_order["line_items"]
        if str(line["id"]) in fulfilled_line_ids
    ]
    if not lines:
        return None
    return prepare_order(
        f"shopify/{shop_domain}", paid_order["id"], paid_order["email"], address, lines
    )
```

Provide `fulfilled_line_ids` from your store's supplier assignment. Freeze each approved payload when the job is first queued. Handle edited or cancelled Shopify orders as reconciliation work. Retain the original mapping and purchase request so a later notification cannot create a second wholesale order. Update customer-facing fulfillment only after receiving the corresponding shipment.

## WooCommerce

Create an order webhook in **WooCommerce → Settings → Advanced → Webhooks**. Set your adapter's HTTPS delivery URL and a shared secret. The receiver handles the initial verification ping and verifies real deliveries before processing orders. WooCommerce REST API documents order status, line items, shipping data, and webhook delivery headers. [WooCommerce webhook setup](https://woocommerce.com/document/webhooks/) · [WooCommerce REST API reference](https://woocommerce.github.io/woocommerce-rest-api-docs/)

This mapper accepts a verified order payload. It checks the recorded payment time and expected fulfillment state before preparing a purchase job. Map a variation by its variation ID or a simple product by its product ID. Use a storefront-specific supplier assignment to identify the lines your reseller should fulfill. [WooCommerce order properties](https://woocommerce.github.io/woocommerce-rest-api-docs/#order-properties)

```python
def woo_job(store_id, order, mapped_items, fulfilled_line_ids):
    if not order.get("date_paid") or order["status"] != "processing":
        return None
    shipping = order["shipping"]
    if shipping["country"] != "US":
        raise ValueError("Request a destination quote before submitting this order.")
    address = {
        "name": " ".join([shipping["first_name"], shipping["last_name"]]).strip(),
        "street": shipping["address_1"],
        "line2": shipping.get("address_2") or "",
        "city": shipping["city"],
        "state": shipping["state"],
        "zip": shipping["postcode"],
    }
    lines = []
    for item in order["line_items"]:
        if str(item["id"]) in fulfilled_line_ids:
            source_id = item["variation_id"] or item["product_id"]
            lines.append({"sku": mapped_items[str(source_id)], "qty": item["quantity"]})
    if not lines:
        return None
    return prepare_order(
        f"woo/{store_id}", order["id"], order["billing"]["email"], address, lines
    )
```

Store a unique job per source shop and order before acknowledging the WooCommerce webhook. Process it asynchronously, send only authorized fulfillment data and retain the CustomGiants order ID. Repeated updates resume the existing job. Record a completed shipment in the merchant's order workflow once carrier tracking is available.

## CustomGiants status webhook

Register a callback using an approved reseller key and a JSON body containing your public HTTPS `url` at `POST /webhooks/`. Use port 443. The portal supports up to eight active subscriptions per reseller. Store the returned `signing_secret` at registration. Keep each platform's webhook secret associated with its own receiver.

For each CustomGiants delivery, read `X-CG-Timestamp`, `X-CG-Signature` and the exact original request bytes. The signature is a lowercase hexadecimal digest. After verifying the request, read `id`, `type`, `order` and `status` from the signed body. The following function uses a five-minute local acceptance window. Retain event IDs with a unique database constraint so concurrent or retried deliveries update one logical event.

```python
import hmac
import time


def verified_status_event(secret, timestamp, signature, raw_body):
    issued_at = int(timestamp)
    if abs(time.time() - issued_at) > 300:
        raise ValueError("Expired webhook delivery")
    signed = timestamp.encode("ascii") + b"." + raw_body
    expected = hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest()
    if not hmac.compare_digest(expected, signature):
        raise ValueError("Invalid webhook signature")
    event = json.loads(raw_body)
    if not event.get("id"):
        raise ValueError("Missing event ID")
    return event
```

In the receiver, save the event ID and queue its processing in the same database transaction. Return success once it is durable, including when the event was stored previously. On arrival of an out-of-order event, fetch the current order status with the owning reseller's API key before updating your customer-facing order.
