# Connect your system to Massar

Canonical guide: https://massar-eg.co/integration/api
OpenAPI: https://massar-eg.co/integration/openapi.json
Postman: https://massar-eg.co/integration/postman.json
Node.js starter: https://massar-eg.co/integration/examples/quickstart.mjs
Python starter: https://massar-eg.co/integration/examples/quickstart.py
Webhook verifier: https://massar-eg.co/integration/examples/verify-webhook.mjs
Order template: https://massar-eg.co/integration/order.example.json
Support: contact@massar-eg.co

## First successful request (about five minutes once you have an account)

1. Create a brand account at https://massar-eg.co/start (Arabic: /ar/start).
2. Sign in at https://dashboard.massar-eg.co. Open Applications → API → Manage API keys. Only your brand administrator can generate/revoke keys. Confirm your current password, choose Generate API key, give it a name, Generate, and copy it before Done. The whole key is shown once. The password confirmation lasts 15 minutes. Refresh and reconfirm if the server returns OTP_REQUIRED; despite that legacy error name, use password confirmation, not an SMS code.
3. Store the key in a private server environment variable MASSAR_API_KEY. Do not paste it into AI chats, frontend bundles, screenshots or Git. All supported API operations are available to the key for its own brand; selectable key scopes are not currently provided.
4. Import openapi.json into your coding tool or Postman (or import postman.json). Set the Postman apiKey variable in a local, unshared environment. The schema is the request/response reference.
5. Make a read-only cities request. This verifies that the key works, without creating shipments:

```sh
curl --fail-with-body 'https://torok-api.onrender.com/api/integrations/v1/cities?q=Nasr' \
  --header "Authorization: Bearer $MASSAR_API_KEY"
```

The response is `{ "data": [{ "id": "...", "name": "...", "nameAr": "...", "governorate": { "name": "...", "nameAr": "..." }, "deliveryZone": 1 }] }` (illustrative). Select the exact intended city ID; do not automatically choose the first ambiguous result. Search covers Arabic/English city names and English governorate names. Results are capped at 1000, without pagination.

## Copy this brief into your AI coding tool

> Integrate my server with Massar using https://massar-eg.co/integration/openapi.json and https://massar-eg.co/integration/ai-guide.md as the contract. Ask me for my framework and where order IDs, receiver details, product amounts and SKUs are stored. Read MASSAR_API_KEY from my server environment; never ask me to paste it into chat. First implement GET /cities and POST /quote and show me a successful read-only connectivity test. Map my stable order ID to externalOrderId and persist the exact normalized payload before submitting. Make POST /orders an explicit business action, never an automatic test or backfill. Persist the response ID, waybillNo, trackingUrl and current status. Resolve timeouts by GET /orders/{externalOrderId} or replaying the exact payload, never by generating another ID. Add a public HTTPS webhook endpoint that verifies the untouched bytes with HMAC-SHA256, uses timing-safe comparison, checks a five-minute timestamp tolerance, durably deduplicates X-Massar-Delivery, commits a job before acknowledging and tolerates unknown fields/statuses. Add tests with synthetic payloads locally. Do not invent cancellation, pickup, inventory, label-PDF or sandbox endpoints. Show the changes and test results before enabling real order creation.

## Run the starter

Node.js 20+ (no packages): `node quickstart.mjs`.
Python 3.10+ (standard library): `python3 quickstart.py`.
Both read MASSAR_API_KEY, default to GET cities, and print the result. MASSAR_CITY_QUERY selects a search term. After you choose the correct ID, set MASSAR_CITY_ID to also get a price quote. Optional MASSAR_EXTERNAL_ORDER_ID looks up a previously created order.

To create an intended shipment, copy order.example.json to order.json and replace ALL placeholders with verified customer details. Set MASSAR_ORDER_FILE to its path and explicitly set MASSAR_CREATE_ORDER=YES. Run the same starter. This creates a real shipment; there is no public sandbox. Keep secrets and customer payloads outside source control and logs. Do not run the entire Postman collection as a connectivity test.

## Pricing and mapping

POST /quote requires cityId. It optionally accepts productCodAmount (EGP), paymentMethod (COD/PREPAID), weight (kg, 0–20), openPackage (boolean) and insurancePlan (NONE/BASIC/SAFETY/SECURED).

Example request:
```json
{"cityId":"CITY_ID_FROM_CITIES","productCodAmount":1000,"paymentMethod":"COD","weight":1,"openPackage":false,"insurancePlan":"NONE"}
```
The response contains cityId, deliveryZone, deliveryCost, openPackage, openPackageFee, insuranceFee, productCodAmount, totalCodAmount and currency=EGP. Prices are account-specific; use the returned value, not a hardcoded fee. productCodAmount excludes Massar delivery fees. For COD, totalCodAmount includes deliveryCost once. PREPAID has zero customer collection. Product amount and final COD must each stay within 30,000 EGP. Quote is not a reservation and creates no shipment.

Map customer name/address/mobile to receiverName/receiverAddress/receiverMobile1; use actual delivery cityId; map each line to itemName/sku/quantity (1–999), max 20 lines. Required and optional fields, bounds and enums are in OpenAPI. Unknown request fields are rejected. Do not send shipperId: the API key supplies brand identity. Do not send totalCodAmount or deliveryCost in create-order requests: Massar calculates these.

## Create, retry and look up orders

POST /orders accepts CreateOrder in OpenAPI. New order: HTTP 201 and created=true. Same externalOrderId + same normalized payload: HTTP 200 and created=false. Same ID + different data: HTTP 409. No special idempotency header is needed.

Order responses contain id, externalOrderId, waybillNo, status, productCodAmount, deliveryCost, totalCodAmount, paymentMethod, trackingUrl, createdAt and updatedAt. Store those values; don't derive tracking URLs from guessed number formats.

GET /orders/{externalOrderId} uses your store ID, not Massar's waybill; URL-encode it. A 404 means not found for the authenticated brand. After an ambiguous timeout, look up first and retry only the original payload/ID. Persist outgoing jobs and immutable request payloads before the first send. For 409, surface a conflict for review rather than silently creating another order. Treat status as an extensible label and display unrecognized states safely.

## Webhooks: configuration and delivery contract

There is one endpoint per brand. GET /webhook returns null if never configured, otherwise url, active, createdAt and updatedAt. PUT /webhook with `{ "url": "https://your-store.example/api/massar/webhook" }` creates/reactivates it and returns signingSecret ONCE. Every PUT rotates the secret, even for the same URL. Store it as MASSAR_WEBHOOK_SECRET. During rotation, coordinate your verifier update; queued deliveries use the current secret. Do not repeatedly register on every app startup.

Only publicly reachable HTTPS on port 443 is accepted. Private IPs, localhost, embedded credentials and redirects are refused. POST /webhook/test sends webhook.test to your server; successful response is 200 with delivered=true; failure is 502 with status, responseStatus and error. DELETE /webhook disables the subscription and returns 204 with no body.

Headers:
- X-Massar-Event: order.status_changed, order.attempt_recorded or webhook.test.
- X-Massar-Delivery: stable delivery ID across retry attempts; durable deduplication key.
- X-Massar-Timestamp: ISO timestamp for this delivery attempt.
- X-Massar-Signature: `sha256=` + hex HMAC-SHA256 of `timestamp + "." + untouched raw body`, using signingSecret.

Body: event, timestamp (event creation), data. Order data includes externalOrderId, waybillNo, status, collected, productCodAmount, deliveryCost, totalCodAmount, trackingUrl and updatedAt. Attempt events may contain additional data. Test data contains a message. Verify against the HEADER timestamp, not the event body's timestamp. Only API-created orders produce these order webhooks. Shopify/WooCommerce orders have their own integration flows.

Receiver recipe: read raw bytes (before JSON middleware), verify signature and freshness, parse JSON, validate delivery header, and atomically insert a unique delivery ID with a durable processing job. If already accepted, return 2xx. If persistence fails, return 5xx. Return 2xx promptly after durable acceptance; process business actions asynchronously and guard against stale/out-of-order updates using updatedAt. Do not execute order-side effects twice.

Massar allows 10 seconds per attempt and up to five total attempts. Retry delays are approximately 1 minute, 5 minutes, 30 minutes and 2 hours after failures; worker scheduling can add latency. No delivery-order guarantee is promised. Keep server clocks synchronized. Download verify-webhook.mjs for a tested raw-body verifier; your application supplies durable persistence/queue handling.

## Errors, rate limits and troubleshooting

Errors normally return `{ "error": "message" }`; validation messages include field paths. Successful DELETE has no body. No response wrapper is used except GET cities (`data`).

- 400: invalid field, city, unsupported destination or COD total; fix values.
- 401: missing/invalid/revoked key. Header must include `Bearer ` and the API key, not the dashboard login token or Shopify link code.
- 403: inactive brand, or insufficient dashboard role for key management. Contact your brand administrator/support.
- 404: order/active webhook not found in this brand.
- 409: same external ID used with different order data. Reconcile before resending.
- 429: limit is 120 requests/minute per key; honor Retry-After and rate-limit headers, use exponential backoff with jitter.
- 500/503 or connection timeout: back off; for writes, retain the same payload/ID and look up before replaying. 503 may include Retry-After.
- 502 from webhook test: check public HTTPS, DNS, TLS, request parsing, signature verification and receiver logs. It does not mean an order was created.

If you cannot see API tools, sign in as the brand administrator and open Applications → API. A brand employee can read the docs but cannot generate keys. A copied key cannot be recovered later: create a replacement, switch your server, verify GET cities, then revoke the old key. Revoking a key is immediate for subsequent requests.

## Scope and go-live checklist

Supported v1: cities, quote, create order, get one order by external ID, and webhook configuration/testing. It does not expose public cancel/edit-order, pickup-booking, inventory-management or label-PDF endpoints. There is no advertised sandbox or scoped read-only key option. Ask support about operations not listed; AI must not invent endpoints.

Before enabling shipment creation: confirm city mapping, amount/fee treatment, required fields, stable IDs, retries, durable webhook handling, protected secret storage and logging, and your separate physical-service agreement with Massar. Test locally with synthetic fixtures; coordinate any live test orders with Massar. Keep source and destination identifiers in audit logs while redacting API keys and unnecessary customer data. First real order should be intentional and visible in your brand Orders page.
