Skip to content

Developer notes

Technical reference for developers who customize Canada Post Shipping.

Item Value
Add-on id kv_canadapost
Function prefix fn_kv_canadapost_
Language variables kv_canadapost.*
CSS scope .kv-canadapost (admin), .kv-cpo (storefront picker)
PHP namespace Tygh\Addons\KvCanadapost
Shipping service module kv_canadapost (class Tygh\Shippings\Services\KvCanadapost). The core carrier is can (class Tygh\Shippings\Services\Can, rate-v3, rates only); the module ids do not overlap and nothing in core is overridden
Tables kv_canadapost_accounts, _shipments, _pieces, _manifests, _offices, _log, _jobs

Canada Post web services used and where each is documented

Section titled “Canada Post web services used and where each is documented”

Source: the official Canada Post Developer Program documentation (Developer Resource Centre, canadapost-postescanada.ca/information/app/drc, service pages under /info/mc/business/productsservices/developers/services/) and the official XSD files of its “XSD files” page (/cpc/doc/en/business/developers/xsd/*.xsd), fetched 2026-11-08. The XSD files are kept in tests/spec/; the official sample requests and responses of the service pages are in tests/fixtures/official/.

Hosts (REST Fundamentals, “Endpoints”): development https://ct.soa-gw.canadapost.ca, production https://soa-gw.canadapost.ca. Every request (REST Fundamentals, “HTTP header variables”): Authorization: Basic base64(username:password) of the API key, Accept with the versioned media type of the service group (*/* is refused by Canada Post), Content-Type with the same type on POST, Accept-Language: en-CA or fr-CA (from the admin language). Errors: the <messages><message><code/><description/></message></messages> structure of messages.xsd, with HTTP 4xx / 5xx, and for Create Shipment also with HTTP 200 (“In the case of an application error, the XML body will have an error message structure rather than the success response, but the HTTP code will be 200”), so the client treats any <messages> body as an error. HTTP 202 = “the requested resource is not yet available, try later” (retryable). 401 and 403 with codes AA001 to AA004 pause the account for 30 minutes. Code Server with “Rejected by SLM Monitor” (API Throttle Limits page) is retryable.

Provided endpoints (<link rel href media-type index>, REST Fundamentals “Provided endpoints”) are followed as received with the link’s media-type as Accept, and only when the link’s scheme, host and port equal the Canada Post host of the account’s mode (or the test override).

Purpose Endpoint and media type (service page) What we send / read
Rates POST /rs/ship/price, application/vnd.cpc.ship.rate-v4+xml (Rating > Get Rates; rating.xsd, element mailing-scenario) customer-number and contract-id for commercial quotes (“must be omitted to obtain counter rates”; contract-id omitted for Solutions for Small Business members), promo-code (non-contract only, Rating release notes), quote-type commercial / counter, options/option/option-code SO (signature), parcel-characteristics/{weight (kg, 3 decimals, > 0, <= 99.999), dimensions/{length, width, height} (cm, 1 decimal; length = longest)}, origin-postal-code (A9A9A9), `destination/{domestic/postal-code
Create contract shipment POST /rs/{mailed by customer}/{mobo}/shipment, application/vnd.cpc.shipment-v8+xml (Contract Shipping > Create Shipment; shipment.xsd, element shipment) customer-request-id (our reference, 35 characters, “must be unique or the request will be rejected”, code 7314), group-id (manifest process, kv-<store token>-<YYYYMMDD> in the shop time zone, 32 characters) or transmit-shipment true (no-manifest process; “group-id must not be provided”), cpc-pickup-indicator + requested-shipping-point or shipping-point-id (mutually exclusive, 9187 / 9189), delivery-spec/{service-code, sender/{name, company, contact-phone, address-details/{address-line-1, address-line-2, city, prov-state, country-code CA, postal-zip-code}}, destination/{name, company, client-voice-number, address-details/{..., country-code, postal-zip-code}}, options/option[]/{option-code, option-amount, option-qualifier-2}, parcel-characteristics, notification/{email, on-shipment, on-exception, on-delivery}, print-preferences/{output-format 8.5x11 / 4x6, encoding PDF}, preferences/{show-packing-instructions, show-postage-rate, show-insured-value}, references/{customer-ref-1 "Order <id>", customer-ref-2 <reference>}, customs, settlement-info/{contract-id, intended-method-of-payment Account / CreditCard}}. Reads shipment-info/{shipment-id, shipment-status, tracking-pin, links/link[rel=self, details, group, price, label (index), commercialInvoice, refund]}. Field limits from the XSD: name / company / address lines 44, city 40, phone 25, e-mail 60 (pattern of EmailType); text is cut with mb_substr
Recover a contract shipment GET /rs/{c}/{m}/shipment?requestId=<customer-request-id> (Contract Shipping > Get Shipments: 404 = none, 202 = found but not finished) links to the shipment, then GET the link (Get Shipment)
Void DELETE on the self link (Contract Shipping > Void Shipment; 204) only for contract shipments of the manifest process that were not transmitted
Refund POST on the refund link, shipment-refund-request/email (Contract Shipping > Request Shipment Refund) or non-contract-shipment-refund-request/email (Non-Contract Shipping > Request Non-Contract Shipment Refund) reads service-ticket-id, service-ticket-date. For a transmitted manifest shipment the refund link comes with Get Shipment
Groups GET /rs/{c}/{m}/group (Contract Shipping > Get Groups), then the group’s link rel="group" (Get Shipments) a listed group can be empty (“they can persist for up to 24 hours while empty”), so the add-on follows the group link: shipment links (or 404 = none) say whether the group still holds untransmitted shipments. Only groups that do are transmitted; the rows of empty or unknown groups are refreshed from Get Shipment (shipment-status)
Transmit POST /rs/{c}/{m}/manifest, application/vnd.cpc.manifest-v8+xml (Contract Shipping > Transmit Shipments; manifest.xsd, element transmit-set), 120 s timeout group-ids/group-id[] (at most 30 per manifest, as the page recommends), pickup / deposit as in Create Shipment, detailed-manifests true, method-of-payment, manifest-address/{manifest-company, manifest-name, phone-number, address-details}. Reads manifests/link[rel=manifest] (one per manifest: “domestic, U.S., and international shipments will be placed on separate manifests”). Error 9118 (Group id: {0} was not found for transmission, with or without quotes around the id) refreshes and drops the group and retries once; 9122 (nothing to transmit) refreshes the rows; after both the manifests of the refreshed labels are looked up (below)
Manifest GET the manifest link (Get Manifest): manifest/{po-number, links/link[rel=artifact, manifestShipments]}; GET /rs/{c}/{m}/manifest?start=YYYYMMDD&end=YYYYMMDD (Get Manifests: one day around a lost transmit attempt; for labels transmitted without a stored manifest from the day before the oldest label was created, at most 31 days back, to tomorrow) for recovery every manifest is stored with its PO number and PDF; exactly the shipments listed by manifestShipments are marked transmitted. Get Manifest error 9153 (HTTP 202, “The transmit process has not completed yet”; “Shipments are manifested asynchronously”) and temporary errors mean “not yet”: the first Get Manifest after a transmit waits 350 ms per transmitted shipment (messagescodetables 9153: “A sleep time of 350 ms per shipment is recommended”), at most 10 s. Labels marked transmitted without a stored manifest (transmitted_at = when the store marked them, shop time zone, from midnight 7 days back, per account and mode; the label date only sets the start of the Get Manifests range) are looked up again with Get Manifests at every transmit and on “Check again” (manual only, under the per-account transmit lock, never in a loop)
Create non-contract shipment POST /rs/{mailed by customer}/ncshipment, application/vnd.cpc.ncshipment-v4+xml (Non-Contract Shipping > Create Non-Contract Shipment; ncshipment.xsd, element non-contract-shipment) requested-shipping-point (deposit postal code when it is not the sender’s), delivery-spec as above without print-preferences / settlement-info, sender with the domestic address type (prov-state 2 characters). Reads non-contract-shipment-info/{shipment-id, tracking-pin, links}
Recover a non-contract shipment GET /rs/{c}/ncshipment?from=YYYYMMDDHHMM&to=YYYYMMDDHHMM (“interpreted as being in the Eastern time zone”) or ?trackingPIN= (Get Non-Contract Shipments), then the details link of each (Get Non-Contract Shipment Details) the shipment whose delivery-spec/references/customer-ref-2 is our reference is adopted; window: 15 minutes before to 60 minutes after the attempt
Label / invoice / manifest PDF GET the label, returnLabel, commercialInvoice or artifact link, Accept: application/pdf (Get Artifact) binary PDF; 202 or 404 right after a create (“a delay of approximately one second is required before you can retrieve the shipping label”) is retried twice, then by the fetch_label job
Authorized return POST /rs/{c}/{m}/authorizedreturn, application/vnd.cpc.authreturn-v2+xml (Returns > Create Authorized Return; authreturn.xsd, element authorized-return) create-public-key (8.5 x 11 PDF only), service-code, returner/{name, company, domestic-address/{address-line-1, address-line-2, city, province, postal-code}} (the customer), receiver/{name, company, email, receiver-voice-number, domestic-address} (the ship-from), parcel-characteristics, print-preferences, settlement-info/contract-id, references. Reads authorized-return-info/{tracking-pin, public-key-info/url, links/link[rel=returnLabel]}. “Returns are only available to Canada Post commercial customers with a volume-based agreement”; bill on scan
Tracking GET /vis/track/pin/{pin}/detail, application/vnd.cpc.track-v2+xml (Tracking > Get Tracking Details; track.xsd) reads tracking-detail/{expected-delivery-date, significant-events/occurrence[]/{event-identifier, event-date, event-time, event-time-zone, event-description, event-site, event-province, event-retail-name}}; code 004 “No PIN History” = not scanned yet
Post Offices GET /rs/postoffice?d2po=true&postalCode=A9A9A9&maximum=10, application/vnd.cpc.postoffice+xml (Find a Post Office > Get Nearest Post Office; postoffice.xsd) reads post-office-list/post-office[]/{office-id (10 digits), name, location, distance, address/{office-address, city, province, postal-code}}
Deliver to Post Office (Deliver to Post Office page, “Programming Details”) label option D2PO with option-qualifier-2 = office id, destination name, client-voice-number, the customer’s own address, notification with on-delivery true. Only Expedited Parcel and Xpresspost (“Deliver to Post Office option is available only with Xpresspost and Expedited Parcel Services”)
U.S. customs Create Shipment / Create Non-Contract Shipment, header X-CPC-Zonos-Key and element customs/us-declaration-id code 8722 “Shipments to the United States require a Zonos Declaration ID or a Zonos Account Key”: the add-on sends the header for U.S. destinations when a key is saved, else requires a declaration id
Customs customs/{currency CAD, reason-for-export SOG / SAM / REP / DOC / OTH, other-reason (4-44), sku-list/item[]/{customs-number-of-units, customs-description (45), sku (15), hs-tariff-code (9999.99.99.99), unit-weight (kg), customs-value-per-unit (CAD), customs-unit-of-measure PCE, country-of-origin, province-of-origin (required when the origin is CA)}, invoice-number (10), ioss-id (13)}; options RASE / RTS / ABAN (non-delivery handling, “required for some U.S.A. and international shipments”)
Customer tracking page https://www.canadapost-postescanada.ca/track-reperage/en/details/<PIN> the form the official tracking application itself builds (origin + "/track-reperage/" + language + "/details/" + pin, in the application’s main.js); the core carrier still links to the older cpotools address

Notes from the documentation.

  • Get Post Office Detail has no constructed endpoint (“Invoke the link provided from Get Nearest Post Office where rel=detail”), so the checkout never builds it: the store keeps the Get Nearest Post Office list it received in the session and accepts only an office id from that list.
  • tracking-detail carries no event type; the type of each event-identifier comes from the “Tracking” table of Messages and code tables (copied into Tracking::TYPES, full table in tests/spec/tracking-events.json). DELIVERED = delivered; RTS / RTC label processing, DETENTION, FOR_REVIEW and “returned to sender” attempts = problem; others = in transit.
  • The Get Tracking Details sample on the service page uses significant-events/item while track.xsd defines occurrence; the reader accepts both.
  • The sample responses of the service pages contain typing errors (non-breaking spaces, missing spaces between attributes); only those were corrected in tests/fixtures/official (see its README).
  1. Named lock per order (GET_LOCK), so double clicks, cron and a status change cannot create two labels at once.
  2. A pending row (status Q) with the request key and our reference KV<store token>-<order>-<row> is written before the call. The store token (random, hidden setting) keeps two stores on one Canada Post account apart.
  3. Contract: the reference is the customer-request-id; a repeat is refused by Canada Post (7314) and found again with Get Shipments ?requestId. Non-contract: the reference is customer-ref-2, found with Get Non-Contract Shipments and the details.
  4. Outcome unknown (no answer, 408, 5xx, 7314): status U, then the lookup above; a found shipment is adopted, nothing is bought again automatically. The admin can adopt a PIN (checked against the attempt’s reference) or discard the attempt.
  5. Definite refusals (4xx, <messages> errors) delete the pending row.
  6. Return labels are bill on scan: an unknown outcome is shown and a new return label needs an explicit tick.
  7. Transmit: named lock per account and a manifest row before the call; after a lost answer the group links show whether the groups still hold shipments (then a new transmit is safe), otherwise Get Manifests around the attempt returns the manifests whose manifestShipments hold our shipments. A transmit that Canada Post finished only after that check (slow answer, 504) is caught by the next transmit: the group is empty, its rows are refreshed from Get Shipment and the manifests holding them are stored then; an attempt whose groups no longer hold anything waiting is closed, so it never blocks a later transmit.
  8. Every shipment row stores the account and mode that bought it; void, refund, tracking and label files use that account, and a label bought in development mode is not managed with the production key.
  • Owner mode on (default): account 0 serves every vendor; vendors ship from their company address; vendors see their own shipments and create labels only with “Vendors may create labels”. Manifests are the owner’s.
  • Owner mode off: each vendor connects an account in the vendor panel (Connection), creates labels and returns and transmits manifests for their own orders. Every action checks the company of the order / shipment / manifest against the vendor; queue actions (run now, retry, discard, cron) are admin-only (schemas/permissions/vendor_multivendor.post.php).
  • Sub-orders: the Post Office chosen for a vendor group moves to the vendor’s sub-order (place_suborders).

change_order_status_post (label at a status), delete_order, get_order_info (attaches the Post Office), place_order, place_suborders, template_document_order_context_init (Post Office on invoices and e-mails), init_templater_post (Upgrade Synchronizer, only while an upgrade is pending). Template hooks: orders:tabs_extra (admin order tab), checkout:shipping_method (picker), orders:totals_shipping (storefront order page), index:styles / index:scripts.

The storefront prints nothing per visitor on cacheable pages: the picker is on the checkout (not cached), its data comes from AJAX POST requests (kv_canadapost.offices, kv_canadapost.office_select), and the scripts are loaded on the checkout only.

  • php81 tests/unit.php / php83 tests/unit.php: pure logic; every request document is validated against the official XSD files; the official sample answers are parsed; client header, error and retry rules with a fake transport.
  • php -S 127.0.0.1:<port> tests/mock-server/server.php: a local stand-in for the services (validates each body against the XSD files, media types, Basic auth, the documented business rules and error codes). It is not Canada Post.
  • node tests/e2e/e2e.mjs --store ... --db ... --root <store dir> --store-name <store>: the full HTTP flow on a dev store. It refuses to run unless the provider URL in config.local.php is the local mock.
  • Test hook: $config['kv_canadapost_base_url'] = 'http://127.0.0.1:<port>'; in config.local.php.