Developer notes
Technical reference for developers who customize FedEx REST Rates & Labels.
Add-on identity
Section titled “Add-on identity”| Item | Value |
|---|---|
| Add-on id | kv_fedex_rest |
| Function prefix | fn_kv_fedex_rest_ |
| Language variables | kv_fedex_rest.* |
| CSS scope | .kv-fedex-rest |
| PHP namespace | Tygh\Addons\KvFedexRest |
| Shipping service module | kv_fedex_rest (class Tygh\Shippings\Services\KvFedexRest); the core REST module is fedexrest, no overlap |
FedEx endpoints used and where each is documented
Section titled “FedEx endpoints used and where each is documented”Hosts: https://apis-sandbox.fedex.com (test) and https://apis.fedex.com (live). Every call except the token carries Authorization: Bearer <token>, Accept: application/json, X-locale: en_US. Sources are the FedEx Developer Portal API references (developer.fedex.com). Status:
- official-spec: checked field by field against the OpenAPI document the portal publishes (
developer.fedex.com/wirc/json/api_groups/<Group>/<Resource>.json, fetched 2026-11-07; the sample requests and the response examples are intests/fixtures/). - flagged: the official documents disagree with each other or leave a value open; the add-on does what is stated in the row and the point is repeated under “Open items”.
All groups (OAuth, Rate, Ship, Track, Address Validation, Pickup) and the API Reference Guide (currency codes, tracking status codes) are published as OpenAPI / JSON documents at developer.fedex.com/wirc/json/api_groups/... and were compared field by field on 2026-11-07; the Ship and Pickup samples and examples built from the Address Validation schema are in tests/fixtures/.
Currency codes. FedEx does not use plain ISO 4217 in every field: the Reference Guide lists its own codes (GBP = UKL, CHF = SFR, JPY = JYE, MXN = NMP, SGD = SID, KRW = WON, AED = DHS, TWD = NTD, ARS = ARN, CLP = CHP, DOP = RDD, XCD = ECD, JMD = JAD, KWD = KUD, KYD = CID). Money::fedexCode() maps the store currency for every amount we send (declared value, customs unit price and value, preferredCurrency); Money::isoCode() maps the currency of a reply back before conversion. A rate reply in a currency the store does not have is skipped instead of converted with the wrong rate.
| Purpose | Endpoint | Fields we send / read | Status |
|---|---|---|---|
| OAuth token | POST /oauth/token, application/x-www-form-urlencoded: grant_type=client_credentials, client_id, client_secret (child key accounts: grant_type=csp_credentials, child_key, child_secret) |
reads access_token, expires_in (token cached encrypted; one new login on HTTP 401) |
official-spec; flagged: the OAuth schema and its examples spell the child field child_Key, the guide’s raw request child_key; we send child_key (guide). client_pc_credentials (proprietary parent-child) is not offered |
| Rates | POST /rate/v1/rates/quotes |
accountNumber.value, rateRequestControlParameters.returnTransitTimes, requestedShipment.{shipper.address, recipient.address(+residential), pickupType, packagingType, rateRequestType[], preferredCurrency, requestedPackageLineItems[].{weight, dimensions, declaredValue, packageSpecialServices}}; no serviceType (all services in one answer). Reads output.rateReplyDetails[].{serviceType, serviceName, ratedShipmentDetails[].{rateType, totalNetCharge, currency}, operationalDetail.{deliveryDate, transitTime}} |
official-spec (returnTransitTimes, operationalDetail.{deliveryDate, transitTime} and commit.dateDetail.dayFormat exist; currency is read from the rated detail, then shipmentRateDetail.currency) |
| Create shipment (label) | POST /ship/v1/shipments |
labelResponseOptions (LABEL), accountNumber.value, requestedShipment.{shipDatestamp, pickupType, serviceType, packagingType, shipper, recipients[], shippingChargesPayment{paymentType, payor.responsibleParty.accountNumber}, labelSpecification{labelFormatType, imageType, labelStockType}, rateRequestType, preferredCurrency, totalPackageCount, requestedPackageLineItems[]{sequenceNumber, weight, dimensions, declaredValue, customerReferences, packageSpecialServices}, shipmentSpecialServices (returns), customsClearanceDetail, shippingDocumentSpecification}; header x-customer-transaction-id. Reads output.transactionShipments[0].{masterTrackingNumber, serviceType, pieceResponses[].{trackingNumber, netChargeAmount, packageDocuments[].{docType, encodedLabel}}, shipmentDocuments[], completedShipmentDetail} |
official-spec |
| Return label | same endpoint with shipmentSpecialServices.specialServiceTypes=["RETURN_SHIPMENT"], returnShipmentDetail.returnType="PRINT_RETURN_LABEL" |
official-spec | |
| Cancel shipment | PUT /ship/v1/shipments/cancel |
accountNumber.value, trackingNumber, senderCountryCode, deletionControl="DELETE_ALL_PACKAGES"; reads output.cancelledShipment |
official-spec |
| Track | POST /track/v1/trackingnumbers |
includeDetailedScans, trackingInfo[].trackingNumberInfo.trackingNumber; reads output.completeTrackResults[0].trackResults[0].{latestStatusDetail.{code, derivedCode, statusByLocale}, scanEvents[].{date, eventDescription, scanLocation}, error} |
official-spec (status codes from the Reference Guide: DL delivered, DE / SE / DD exceptions, CA cancelled by sender, OC created, others in transit) |
| Address validation | POST /address/v1/addresses/resolve |
inEffectAsOfTimestamp, validateAddressControlParameters.includeResolutionTokens, addressesToValidate[].address; reads output.resolvedAddresses[0].{streetLinesToken, city, stateOrProvinceCode, postalCodeToken{changed, value} (one object; parsedPostalCode{base, addOn} as fallback), countryCode, classification (MIXED / UNKNOWN / BUSINESS / RESIDENTIAL), customerMessage[], attributes}; there is no postalCode in the reply |
official-spec (the customerMessage item layout is not in the schema: {code, message} and plain strings are both read) |
| Pickup availability | POST /pickup/v1/pickups/availabilities |
pickupAddress, pickupRequestType[], carriers[], countryRelationship, dispatchDate, packageReadyTime, customerCloseTime; reads output.options[] |
official-spec |
| Create pickup | POST /pickup/v1/pickups |
associatedAccountNumber.value, associatedAccountNumberType, originDetail.{pickupLocation, packageLocation, readyDateTimestamp, customerCloseTime}, carrierCode (FDXE / FDXG), countryRelationships, packageCount, totalWeight, remarks; reads output.{pickupConfirmationCode, location} |
official-spec (readyDateTimestamp is local to the pickup postal code and a time zone designator is ignored, so we send the shop’s local wall-clock time without Z) |
| Cancel pickup | PUT /pickup/v1/pickups/cancel |
associatedAccountNumber.value, pickupConfirmationCode, carrierCode, scheduledDate, location (Express) |
official-spec |
| Error body | HTTP 4xx / 5xx: {"transactionId", "errors": [{"code", "message"}]} |
message and code shown (masked) in the log and to the admin | official-spec |
The Ship API has no idempotency key and no “find my shipment by reference” call. That is why a purchase is protected on our side (see “Safe label purchase”).
Open items to confirm in the FedEx sandbox
Section titled “Open items to confirm in the FedEx sandbox”The field names of every call are verified against the official documents (see above). What remains:
- OAuth:
child_Key(schema and examples) versuschild_key(guide) for child-key accounts. We sendchild_key; if the sandbox rejects it, onlyClient\Api::tokenFields()changes. Only used when a child key is entered. - Address validation: the item layout of
customerMessage[](the schema gives none). - Pickup:
countryRelationshipsis alwaysDOMESTIC; export pickups needINTERNATIONAL. - The first run against a real FedEx project: the add-on has been tested against a local mock only.
- Brand: the FedEx logo may only be used under FedEx’s brand rules (permission); the add-on and its gallery use the name as text only.
Structure
Section titled “Structure”| Class | Role |
|---|---|
Client\BaseClient |
HTTP (cURL, TLS verification, timeouts), JSON, OAuth2 token cache (encrypted), one re-login on 401, error mapping, masked logging |
Client\Api |
The FedEx calls above |
Client |
Client per company, the connection test |
Accounts, Secret |
Credentials (test and live) sealed with AES-256-GCM; one account per store owner or per vendor; non-secret fields (account number, ship-from, defaults) in extra |
Config, Access |
Settings, owner mode, who may see and manage what (Access::canLabel() guards every money action) |
RateCalculator |
Rate request, rate list parse, markup, free shipping, fallback; memo and 10 minute cache per request |
Shipments |
Payload (outbound, return, customs), multi-package, safe purchase, cancel, tracking, downloads |
Pickups, Addresses |
Pickup API, Address Validation API |
Parties, Packer, Clock |
Address and party mapping (multi-byte safe cuts), units and package split, shop time zone dates |
Queue, Jobs, JobException, Log |
Job queue (back-off 5 min / 15 min / 1 h / 3 h / 12 h), recurring work, event log with masking |
Safe label purchase
Section titled “Safe label purchase”- A MySQL named lock per order (
kv_fedex_rest_order_<id>) serialises create and return; cancel and tracking use a per-shipment lock. Discarding a pending or unresolved attempt (label or pickup) takes the same lock without waiting and is refused while a request is still in flight, so a paid label can never lose its row. - Before the call a row with status
Qand arequest_key(hash of order, kind, service and packages, not the ship date) is written; the same request finds it. A finished one is returned, a running one makes the job wait, a stale or unresolved one stops with a message. - A timeout, a connection error or HTTP 408 / 500 / 502 / 504 turns the row into
U(unresolved) and nothing retries automatically. HTTP 400 / 401 / 403 / 404 / 429 / 503 delete the row because FedEx did not process the request. Thex-customer-transaction-idheader (kv-<order>-<shipment>) is echoed by FedEx and helps to find the shipment in the FedEx logs. - Pickups use the same pattern (
request_key,Ustatus). - The named lock needs MySQL 5.7+ / MariaDB 10.0.2+ to coexist with the queue’s own lock (older servers release the first lock when another is taken; purchases stay protected by the attempt rows).
Database tables
Section titled “Database tables”| Table | Purpose |
|---|---|
?:kv_fedex_rest_accounts |
Credentials per company (secrets sealed), last connection check, token cache |
?:kv_fedex_rest_log |
Log |
?:kv_fedex_rest_jobs |
Queue |
?:kv_fedex_rest_shipments |
Shipments: kind (outbound / return), service, status, tracking, scan events |
?:kv_fedex_rest_pieces |
One row per package label and per document (commercial invoice), file data |
?:kv_fedex_rest_pickups |
Pickups |
?:kv_fedex_rest_addr |
Address validation result per order and address hash |
Hooks used
Section titled “Hooks used”PHP: change_order_status_post (label at a status), delete_order (removes shipments, labels and the address check), init_templater_post (upgrade synchronizer, only while pending). Template hooks: orders:tabs_extra (admin tab), addons:manage / addons:tabs_content (licence card). Controllers: kv_fedex_rest (admin, vendor, storefront cron), orders.post (tab data). No storefront output apart from the shipping rates, so there is nothing to cache or exclude from the full page cache; rates are only requested while a cart is calculated.
Testing against a mock
Section titled “Testing against a mock”Define the base URL in config.local.php to send all FedEx calls to another host, for example the mock in tests/mock-server/server.js:
$config['kv_fedex_rest_base_url'] = 'http://127.0.0.1:11830';Extending
Section titled “Extending”The service list is Installer::services() (code to name; codes are the FedEx serviceType values). Add a code there and in fn_kv_fedex_rest_upgrade_sync() (it re-runs Installer::install()).