# Availability Source: https://docs.unihop.app/direct/api-reference/endpoint/availability direct/api-reference/openapi.json GET /availability Retrive the availability of the service provider. # Create Order Source: https://docs.unihop.app/direct/api-reference/endpoint/create-order direct/api-reference/openapi.json POST /orders Creates a new order in the system # Cancel Order Source: https://docs.unihop.app/direct/api-reference/endpoint/delete direct/api-reference/openapi.json POST /orders/{uid}/cancel Deletes a single ord based on the UID supplied # Get Order Source: https://docs.unihop.app/direct/api-reference/endpoint/get direct/api-reference/openapi.json GET /orders/{uid} Returns a single order by its unique identifier. # Get Order by Partner Reference Source: https://docs.unihop.app/direct/api-reference/endpoint/get-partner-order direct/api-reference/openapi.json GET /orders/partner/{partner_reference} Returns a single order by its unique partner_reference. # Get Quote Source: https://docs.unihop.app/direct/api-reference/endpoint/quote direct/api-reference/openapi.json POST /quote Returns a price quote for a delivery without creating an order. Accepts the same parameters as creating an order. # Authentication Source: https://docs.unihop.app/direct/authentication Sign your requests with an RS256 JWT To authenticate with our API, you'll need to generate a **public/private RSA key pair**. We use **RS256** (RSA Signature with SHA-256) to sign and verify requests securely. This guide will help you: 1. ✅ Generate your keys 2. 🛠 Use them to sign JWTs 3. 🔑 Share your public key with us 4. 🔄 Decode webhook JWTs from us *** ## 1. ✅ Generate RSA Key Pair Run the following command in your terminal to generate a 2048-bit RSA key pair: ```bash theme={null} openssl genpkey -algorithm RSA -out private_key.pem -pkeyopt rsa_keygen_bits:2048 ``` This creates your private key file: **private\_key.pem.** Now generate the public key: ```bash theme={null} openssl rsa -pubout -in private_key.pem -out public_key.pem ``` You should now have: **private\_key.pem** (keep this safe and secret) **public\_key.pem** (you'll send this to us) ## 2. 🛠 Encode your JWTs JSON Web Tokens (JWTs) are a compact, URL-safe means of representing claims securely between two parties. When using RS256, you'll sign the JWT with your private key, and we'll verify it with your public key. ### JWT Structure A JWT consists of three parts separated by dots (`.`): * **Header**: Contains the token type and signing algorithm * **Payload**: Contains the claims (data) * **Signature**: Verifies the token hasn't been altered For our API, your JWT **must** include the following claims in the payload: | Claim | Description | Required | Example | | ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | ---------------------------------- | | `iss` | Issuer - Your partner\_uid (provided by us) | Yes | `"iss": "your_partner_uid"` | | `iat` | Issued At - Current timestamp (seconds since epoch) | Yes | `"iat": 1686104400` | | `exp` | Expiration Time - Must be within 30 minutes of `iat` | Yes | `"exp": 1686106200` | | `merchant_id` | Merchant identifier - Allows a partner to route requests to a specific merchant. Useful when integrating multiple merchants under a single account. | No | `"merchant_id": "merchant_abc123"` | ### Code Examples #### PHP Using the [firebase/php-jwt](https://github.com/firebase/php-jwt) library: ```php theme={null} use Firebase\JWT\JWT; // Load your private key $privateKey = file_get_contents('private_key.pem'); // Create payload with required claims $payload = [ 'iss' => 'your_partner_uid', // Replace with your partner_uid 'iat' => time(), 'exp' => time() + 1800, // 30 minutes 'merchant_id' => 'merchant_abc123', // Optional: specify the merchant ]; // Sign the JWT with RS256 algorithm $jwt = JWT::encode($payload, $privateKey, 'RS256'); // Use this token in your Authorization header echo "Bearer " . $jwt; ``` #### Node.js Using the [jsonwebtoken](https://github.com/auth0/node-jsonwebtoken) library: ```javascript theme={null} const jwt = require('jsonwebtoken'); const fs = require('fs'); // Load your private key const privateKey = fs.readFileSync('private_key.pem'); // Create payload with required claims const payload = { iss: 'your_partner_uid', // Replace with your partner_uid iat: Math.floor(Date.now() / 1000), exp: Math.floor(Date.now() / 1000) + 1800, // 30 minutes merchant_id: 'merchant_abc123' // Optional: specify the merchant }; // Sign the JWT with RS256 algorithm const token = jwt.sign(payload, privateKey, { algorithm: 'RS256' }); // Use this token in your Authorization header console.log('Bearer ' + token); ``` #### Python Using the [PyJWT](https://github.com/jpadilla/pyjwt) library: ```python theme={null} import jwt import time # Load your private key with open('private_key.pem', 'rb') as key_file: private_key = key_file.read() # Create payload with required claims payload = { 'iss': 'your_partner_uid', # Replace with your partner_uid 'iat': int(time.time()), 'exp': int(time.time()) + 1800, # 30 minutes 'merchant_id': 'merchant_abc123', # Optional: specify the merchant } # Sign the JWT with RS256 algorithm token = jwt.encode(payload, private_key, algorithm='RS256') # Use this token in your Authorization header print(f"Bearer {token}") ``` ### Important Notes 1. **Token Expiration**: Your token must expire within 30 minutes of creation. The server will reject tokens with longer expiration times. 2. **Token Format**: Always include the token in your Authorization header with the "Bearer" prefix: ``` Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9... ``` 3. **Security**: Keep your private key secure. Never share it or commit it to version control. 4. **Validation**: The server validates: * The token signature using your public key * The presence of required claims (`iss`, `iat`, `exp`) * That the token hasn't expired * That the expiration is within 30 minutes of issuance * If `merchant_id` is provided, that it corresponds to a valid merchant under your account ## 3. 🔑 Share Your Public Key After generating your key pair, you need to share your public key with us. This allows us to verify the JWTs you sign. 1. Contact your account manager or support team 2. Send them your `public_key.pem` file 3. We'll associate it with your account Once your public key is registered in our system, you can start using JWT authentication for your API requests. ## 4. 🔄 Decoding Webhook JWTs When you receive webhooks from our service, the payload is secured with a JWT signed using our private key. To verify and decode these JWTs, you'll need to use our public key. ### Webhook JWT Structure Webhooks sent from our service include a JWT in the `Authorization` header with the following structure: * **Header**: Contains `alg: "RS256"` and `typ: "JWT"` * **Payload**: Contains: * `iss`: Always set to `"unihop"` (our issuer identifier) * `exp`: Expiration timestamp (30 minutes from creation) * `payload`: The actual webhook data ### Verification Process When receiving a webhook, you should: 1. Extract the JWT from the `Authorization` header 2. Verify the JWT signature using our public key 3. Check that the `iss` claim is `"unihop"` 4. Ensure the token hasn't expired 5. Extract and process the webhook data from the `payload` field ### Code Examples #### PHP Using the [firebase/php-jwt](https://github.com/firebase/php-jwt) library: ```php theme={null} use Firebase\JWT\JWT; use Firebase\JWT\Key; function handleWebhook($request) { // Extract JWT from Authorization header $authHeader = $request->header('Authorization'); if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) { return response()->json(['error' => 'Unauthorized - Token missing'], 401); } $token = trim(str_replace('Bearer ', '', $authHeader)); try { // Load our public key $publicKey = file_get_contents('unihop_public_key.pem'); // Decode and verify the JWT $decoded = JWT::decode($token, new Key($publicKey, 'RS256')); // Verify issuer if (!isset($decoded->iss) || $decoded->iss !== 'unihop') { throw new Exception("Invalid issuer"); } // Extract the webhook payload if (!isset($decoded->payload)) { throw new Exception("Payload missing"); } $webhookData = $decoded->payload; // Process the webhook data processWebhookData($webhookData); return response()->json(['status' => 'success'], 200); } catch (Exception $e) { return response()->json(['error' => 'Invalid token: ' . $e->getMessage()], 401); } } ``` #### Node.js Using the [jsonwebtoken](https://github.com/auth0/node-jsonwebtoken) library: ```javascript theme={null} const jwt = require('jsonwebtoken'); const fs = require('fs'); function handleWebhook(req, res) { // Extract JWT from Authorization header const authHeader = req.headers.authorization; if (!authHeader || !authHeader.startsWith('Bearer ')) { return res.status(401).json({ error: 'Unauthorized - Token missing' }); } const token = authHeader.replace('Bearer ', '').trim(); try { // Load our public key const publicKey = fs.readFileSync('unihop_public_key.pem'); // Verify and decode the JWT const decoded = jwt.verify(token, publicKey, { algorithms: ['RS256'] }); // Verify issuer if (!decoded.iss || decoded.iss !== 'unihop') { throw new Error('Invalid issuer'); } // Extract the webhook payload if (!decoded.payload) { throw new Error('Payload missing'); } const webhookData = decoded.payload; // Process the webhook data processWebhookData(webhookData); return res.status(200).json({ status: 'success' }); } catch (error) { return res.status(401).json({ error: 'Invalid token: ' + error.message }); } } ``` #### Python Using the [PyJWT](https://github.com/jpadilla/pyjwt) library: ```python theme={null} import jwt from flask import Flask, request, jsonify app = Flask(__name__) @app.route('/webhook', methods=['POST']) def handle_webhook(): # Extract JWT from Authorization header auth_header = request.headers.get('Authorization') if not auth_header or not auth_header.startswith('Bearer '): return jsonify({'error': 'Unauthorized - Token missing'}), 401 token = auth_header.replace('Bearer ', '').strip() try: # Load our public key with open('unihop_public_key.pem', 'rb') as key_file: public_key = key_file.read() # Verify and decode the JWT decoded = jwt.decode( token, public_key, algorithms=['RS256'], options={'verify_signature': True} ) # Verify issuer if 'iss' not in decoded or decoded['iss'] != 'unihop': raise ValueError('Invalid issuer') # Extract the webhook payload if 'payload' not in decoded: raise ValueError('Payload missing') webhook_data = decoded['payload'] # Process the webhook data process_webhook_data(webhook_data) return jsonify({'status': 'success'}), 200 except Exception as e: return jsonify({'error': f'Invalid token: {str(e)}'}), 401 def process_webhook_data(data): # Implement your webhook processing logic here pass if __name__ == '__main__': app.run(debug=True) ``` ### Important Security Considerations 1. **Always Verify the Signature**: Never process webhook data without first verifying the JWT signature with our public key. 2. **Check the Issuer**: Confirm that the `iss` claim is `"unihop"` to ensure the webhook came from our service. 3. **Validate Expiration**: Reject tokens that have expired to prevent replay attacks. 4. **Implement Idempotency**: Webhooks may be sent multiple times in rare cases. Implement idempotency checks to avoid processing the same webhook twice. 5. **Use HTTPS**: Always use HTTPS for your webhook endpoint to ensure the data remains encrypted in transit. ### Obtaining Our Public Key To verify webhooks from our service, you'll need our public key. Contact your account manager or support team to obtain the public key file (`unihop_public_key.pem`). ### Testing Webhook Verification You can test your webhook verification implementation using our webhook testing tool in the developer dashboard. This allows you to send test webhooks to your endpoint and verify that your verification logic works correctly. ## Testing Your JWT You can use online tools like [jwt.io](https://jwt.io/) to verify your JWT is correctly formatted: 1. Paste your JWT in the "Encoded" field 2. Paste your public key in the "Verify Signature" section 3. Confirm the signature is verified and the payload contains the correct claims ## Troubleshooting If you're experiencing authentication issues, check: * Your JWT includes all required claims (`iss`, `iat`, `exp`) * The `iss` claim matches your partner\_uid * The token hasn't expired * The expiration time is within 30 minutes of the issued time * You're using the correct private key to sign the token * We have your correct public key on file * The Authorization header format is correct (`Bearer `) * If using `merchant_id`, verify the ID matches a merchant registered under your account For further assistance, contact our support team. # Direct API Source: https://docs.unihop.app/direct/index Book and track UniHop deliveries on your own account ## Who this is for A business booking its own deliveries, and marketplaces booking on behalf of the sellers they host. You get an account of your own, signed-JWT authentication, and an optional `merchant_id` claim to attribute an order to a specific seller. Everything booked through this API is billed to your account. Building software that other businesses install and book through, like a checkout scheduling app or an order management system? Use the [Platform API](/platforms/index). There, each merchant authenticates with their own UniHop API key and is billed on their own account. ## Base URL ``` https://backend.unihop.app/api/v1 ``` ## Authentication Every request carries a JWT you sign with your private key, in the `Authorization` header: ``` Authorization: Bearer YOUR_JWT_TOKEN ``` See [Authentication](/direct/authentication) for generating your key pair, the required claims, and code samples. ## Endpoints | | | | ---------------------------------------------------------------------------------- | ------------------------------------------- | | [Get Quote](/direct/api-reference/endpoint/quote) | Price and distance, nothing created | | [Create Order](/direct/api-reference/endpoint/create-order) | Book a delivery and send it to dispatch | | [Get Order](/direct/api-reference/endpoint/get) | Status, courier, ETA, proof of delivery | | [Get Order by Partner Reference](/direct/api-reference/endpoint/get-partner-order) | The same, keyed on your own reference | | [Cancel Order](/direct/api-reference/endpoint/delete) | Before pickup, with the fee stated up front | | [Availability](/direct/api-reference/endpoint/availability) | A liveness check before offering delivery | ## Tracking and updates Every created order returns a tracking link, a public page you can give the recipient with no login. For programmatic updates, register a webhook URL and we'll push every status change as it happens. See [Webhooks](/direct/webhooks). ## Response format All responses are JSON. Successful responses carry the relevant data. Errors carry a machine-readable code and a human-readable message. ## Need a hand? Your account manager handles accounts, delivery styles, and coverage. API questions: [help.unihop.app](https://help.unihop.app). # Webhooks Source: https://docs.unihop.app/direct/webhooks Status changes and courier movement, pushed to your endpoint This page covers the webhook event types, the request body, and how to verify what we send. ## Event Types Our webhook system dispatches requests based on specific event names, categorized primarily into `delivery` and `location` events. Each event signifies a distinct state change or action within our system. ### Delivery Events Delivery events provide updates on the lifecycle of a delivery, from assignment to completion or failure. The following is a comprehensive list of delivery event types: * `delivery.assigned`: A delivery has been assigned. * `delivery.pickup_enroute`: The delivery driver is enroute to the pickup location. * `delivery.pickup_arrived`: The delivery driver has arrived at the pickup location. * `delivery.pickup_complete`: The delivery driver has completed the pickup. * `delivery.dropoff_enroute`: The delivery driver is enroute to the dropoff location. * `delivery.dropoff_arrived`: The delivery driver has arrived at the dropoff location. * `delivery.dropoff_complete`: The delivery driver has completed the dropoff. * `delivery.return_in_progress`: The delivery is in the process of being returned. * `delivery.returned`: The delivery has been successfully returned. * `delivery.canceled`: The delivery has been canceled. * `delivery.failed`: The delivery has failed. ### Location Events Location events provide updates on the geographical status of a delivery or driver. The following is a comprehensive list of location event types: * `location.pickup_enroute`: The driver is enroute to the pickup location. * `location.assigned_driver`: A driver has been assigned to the delivery. * `location.pickup_complete`: The driver has completed the pickup and is now enroute to the dropoff. * `location.dropoff_enroute`: The driver is enroute to the dropoff location. * `location.return_in_progress`: The driver is in the process of returning to the origin. ## Request Body Structure All webhook requests are sent as `POST` requests with a JSON payload. The structure of the request body is consistent across all event types and contains detailed information pertinent to the event. Below is a breakdown of the fields included in the request body: ```json theme={null} { "event_name": "string", "merchant_id": "string | null", "status": "string", "price": { "value": "number", "currency": "string" }, "currency": "string", "distance": { "value": "number", "unit": "string" }, "pickup_name": "string", "dropoff_name": "string", "delivery_date": "string", "delivery_start_time": "string", "partner_payload": "object", "driver_id": "number", "driver_name": "string", "driver_location": { "lat": "number", "lng": "number" }, "driver_dropoff_phone_number": "string", "driver_pickup_phone_number": "string", "driver_vehicle_make": "string", "driver_vehicle_model": "string", "driver_vehicle_year": "number", "dropoff_time_estimated": "string", "pickup_address_street": "string", "pickup_address_city": "string", "pickup_address_country": "string", "pickup_address_number": "string", "pickup_address_county": "string", "pickup_address_state": "string", "pickup_address_postal_code": "string", "pickup_address_latitude": "number", "pickup_address_longitude": "number", "pickup_phone_number": "string", "pickup_instructions": "string", "email": "string", "dropoff_address_street": "string", "dropoff_address_city": "string", "dropoff_address_country": "string", "dropoff_address_number": "string", "dropoff_address_secondary_number": "string", "dropoff_address_county": "string", "dropoff_address_state": "string", "dropoff_address_postal_code": "string", "dropoff_address_latitude": "number", "dropoff_address_longitude": "number", "dropoff_phone_number": "string", "dropoff_instructions": "string", "dropoff_email": "string", "package_description": "string", "package_minimum_vehicle_size": "string", "package_delivery_mode": "string", "package_requirements": "array", "items_count": "number", "items": "array", "weight": "number", "dimentions": { "height": "number", "length": "number", "width": "number" }, "package_value": "number", "pickup_start_time": "string", "dropoff_start_time": "string", "delivery_end_time": "string", "dropoff_verification_image_url": "string", "dropoff_signature_image_url": "string", "cancellation_reason": "string", "tip": "number", "partner_reference": "string" } ``` ### Field Descriptions | Field Name | Type | Description | | :--------------------------------- | :----- | :--------------------------------------------------------------------------------------------------------------------------- | | `event_name` | string | The specific webhook event that triggered the notification (e.g., `pickup_complete`). | | `merchant_id` | string | The merchant identifier associated with this order, if one was provided in the JWT during order creation. `null` if not set. | | `status` | string | The current high-level status of the delivery task. | | `price` | object | An object representing the total cost of the delivery. | | `price.value` | number | The total price of the delivery in a standard decimal format, converted from cents. | | `price.currency` | string | The ISO 4217 currency code for the price. | | `currency` | string | The ISO 4217 currency code for the transaction. | | `distance` | object | An object representing the estimated driving distance for the delivery. | | `distance.value` | number | The estimated driving distance value (e.g., in kilometers). | | `distance.unit` | string | The unit of measurement for the distance (e.g., `kilometers`). | | `pickup_name` | string | The full name of the contact person at the pickup location. | | `dropoff_name` | string | The full name of the contact person at the dropoff location. | | `delivery_date` | string | The scheduled date for the delivery to begin, formatted as `YYYY-MM-DD`. | | `delivery_start_time` | string | The scheduled start of the delivery window, as an ISO 8601 UTC datetime (`YYYY-MM-DDTHH:MM:SS+00:00`). | | `partner_payload` | object | An arbitrary object provided by the partner during job creation for their own reference. | | `driver_id` | number | A unique numeric identifier for the courier/driver. | | `driver_name` | string | The full name of the assigned courier. | | `driver_location` | object | The last known GPS coordinates of the driver. | | `driver_location.lat` | number | The latitude of the driver's location. | | `driver_location.lng` | number | The longitude of the driver's location. | | `driver_dropoff_phone_number` | string | The driver's phone number for dropoff-related communication. | | `driver_pickup_phone_number` | string | The driver's phone number for pickup-related communication. | | `driver_vehicle_make` | string | The make of the driver's vehicle (e.g., `Tesla`). | | `driver_vehicle_model` | string | The model of the driver's vehicle (e.g., `Model Z`). | | `driver_vehicle_year` | number | The manufacturing year of the driver's vehicle. | | `dropoff_time_estimated` | string | The estimated time of arrival at the dropoff location, in a standard datetime format. | | `pickup_address_street` | string | Street name of the pickup address. | | `pickup_address_city` | string | City of the pickup address. | | `pickup_address_country` | string | Country of the pickup address. | | `pickup_address_number` | string | Street number of the pickup address. | | `pickup_address_secondary_number` | string | Apartment or suite number for the pickup address. | | `pickup_address_county` | string | County of the pickup address. | | `pickup_address_state` | string | State of the pickup address. | | `pickup_address_postal_code` | string | Postal or ZIP code of the pickup address. | | `pickup_address_latitude` | number | Latitude coordinate of the pickup address. | | `pickup_address_longitude` | number | Longitude coordinate of the pickup address. | | `dropoff_address_street` | string | Street name of the dropoff address. | | `dropoff_address_city` | string | City of the dropoff address. | | `dropoff_address_country` | string | Country of the dropoff address. | | `dropoff_address_number` | string | Street number of the dropoff address. | | `dropoff_address_secondary_number` | string | Apartment or suite number for the dropoff address. | | `dropoff_address_county` | string | County of the dropoff address. | | `dropoff_address_state` | string | State of the dropoff address. | | `dropoff_address_postal_code` | string | Postal or ZIP code of the dropoff address. | | `dropoff_address_latitude` | number | Latitude coordinate of the dropoff address. | | `dropoff_address_longitude` | number | Longitude coordinate of the dropoff address. | | `pickup_phone_number` | string | The contact phone number for the pickup location. | | `pickup_instructions` | string | Special instructions for the courier at the pickup location. | | `email` | string | The email address of the contact person at the pickup location. | | `dropoff_phone_number` | string | The contact phone number for the dropoff location. | | `dropoff_instructions` | string | Special instructions for the courier at the dropoff location. | | `dropoff_email ` | string | The email of the entity to contact. | | `package_description` | string | A description of the contents of the package being delivered. | | `package_minimum_vehicle_size` | string | The minimum vehicle size required for this delivery (e.g., `CAR`, `BIKE`). | | `package_delivery_mode` | string | The delivery mode, indicating if it's on-demand (`NOW`) or scheduled. | | `package_requirements` | array | A list of special requirements for the delivery (e.g., `photo_proof_of_delivery`). | | `items_count` | number | The number of items in the package. | | `items` | array | A list of objects, each detailing an item in the package. Can be null. | | `weight` | number | The weight of the package. | | `dimentions` | object | The dimentions of the package. | | `package_value` | number | The declared value of the package, converted from cents. | | `pickup_start_time` | string | The start of the pickup window, as an ISO 8601 UTC datetime (`YYYY-MM-DDTHH:MM:SS+00:00`). | | `dropoff_start_time` | string | The start of the dropoff window, as an ISO 8601 UTC datetime (`YYYY-MM-DDTHH:MM:SS+00:00`). | | `delivery_end_time` | string | The end of the dropoff window, as an ISO 8601 UTC datetime (`YYYY-MM-DDTHH:MM:SS+00:00`). | | `dropoff_verification_image_url` | string | URL to a photo taken as proof of delivery. Available on relevant events. | | `dropoff_signature_image_url` | string | URL to a signature captured as proof of delivery. Available on relevant events. | | `cancellation_reason` | string | The reason for a delivery cancellation. Available on cancellation events. | | `tip` | number | The tip amount for the driver, converted from cents. | | `partner_reference` | string | A reference ID provided by the partner during job creation. | ## Authentication Headers All webhook requests include the following headers: | Header | Description | | --------------- | ------------------------------------------------------------------ | | `Content-Type` | Set to `application/json` | | `Accept` | Set to `application/json` | | `Authorization` | Bearer token containing a JWT encoded version of the request body. | # UniHop API Source: https://docs.unihop.app/index Last-mile delivery for local businesses across the U.S. and Canada UniHop moves packages the last mile. You send us a pickup, a dropoff, and when it needs to happen. We source a driver, and our dispatch team watches the delivery through to the doorstep. Two APIs. Pick the one that matches whose account the deliveries are booked on. **Book on your own account.** One signed-JWT credential, one bill for everything you book. For a business booking its own deliveries, and for marketplaces booking for the merchants they host, with an optional `merchant_id` to attribute each order to the right one. **Book on your merchants' accounts.** Each merchant brings their own UniHop API key and is billed directly, so you are never in the billing path. For software other businesses install and book through, like a checkout scheduling app or an order management system. ## Both APIs share The same delivery engine, the same dispatch team, and the same delivery styles. Requests and responses use the same field names, and both can receive webhooks as a delivery moves. What differs is who authenticates, and who pays. ## Need a hand? Your account manager handles accounts, delivery styles, and coverage. API questions: [help.unihop.app](https://help.unihop.app). # Check Availability Source: https://docs.unihop.app/platforms/api-reference/endpoint/availability platforms/api-reference/openapi.json GET /availability A liveness check for your storefront # Cancel a Delivery Source: https://docs.unihop.app/platforms/api-reference/endpoint/cancel-delivery platforms/api-reference/openapi.json POST /deliveries/{uid}/cancel Cancel before pickup, with the fee stated up front # Create a Delivery Source: https://docs.unihop.app/platforms/api-reference/endpoint/create-delivery platforms/api-reference/openapi.json POST /deliveries Book a delivery and send it straight to dispatch # Get a Delivery Source: https://docs.unihop.app/platforms/api-reference/endpoint/get-delivery platforms/api-reference/openapi.json GET /deliveries/{uid} Current status, courier details, and proof of delivery # Quote a Delivery Source: https://docs.unihop.app/platforms/api-reference/endpoint/quote platforms/api-reference/openapi.json POST /quote Price and distance, without creating anything # Authentication Source: https://docs.unihop.app/platforms/authentication One API key, sent as a bearer token ## How it works Two things identify a request: 1. **Your platform identifier**, in the URL path (`/api/v1/your_platform/deliveries`). It tells us the delivery came through you. 2. **The merchant's API key**, in the `Authorization` header. It tells us whose delivery it is and which account to bill. ``` Authorization: Bearer live_eyJpdiI6IkR4TjhLQzFyWXBRPSIsInZhbHVlIjoi... ``` The key belongs to the merchant, not to you. You never hold a key of your own, and you are never billed for what your merchants book. ## Getting a key Merchants generate their own key in their UniHop dashboard and paste it into your app's settings. There is nothing to request from us per merchant. You get your platform identifier at onboarding. Ask your account manager for it. Keys don't expire, but a merchant can regenerate theirs at any time, which invalidates the old one immediately. ## Example ```bash cURL theme={null} curl https://backend.unihop.app/api/v1/your_platform/availability \ -H "Authorization: Bearer $MERCHANT_API_KEY" ``` ```javascript Node.js theme={null} const response = await fetch( 'https://backend.unihop.app/api/v1/your_platform/availability', { headers: { Authorization: `Bearer ${process.env.MERCHANT_API_KEY}` } } ); ``` ```python Python theme={null} import os import requests response = requests.get( 'https://backend.unihop.app/api/v1/your_platform/availability', headers={'Authorization': f"Bearer {os.environ['MERCHANT_API_KEY']}"}, ) ``` ```php PHP theme={null} $response = Http::withToken($merchant->unihop_api_key) ->get('https://backend.unihop.app/api/v1/your_platform/availability'); ``` ## When authentication fails Every failure is a `401` with a machine-readable `code`: | Code | What happened | | ----------------- | ------------------------------------------------------------- | | `missing_token` | No `Authorization` header, or it isn't a bearer token | | `invalid_api_key` | The key is wrong, regenerated, or belongs to a closed account | ```json theme={null} { "code": "invalid_api_key", "message": "API key failed authentication." } ``` A bad key and an unknown platform identifier return the same code, so the URL space can't be enumerated. Retrying won't fix a `401`. Prompt the merchant to re-enter their key. ## Rate limits Requests are counted per merchant key, so one busy merchant can't throttle the rest of your platform. Over the limit returns a `429` with a `Retry-After` header. Back off for that many seconds and retry. Planning a bulk import? Tell your account manager and we'll raise the ceiling for the window. ## Merchant attribution The key already tells us which merchant an order belongs to, so you don't need to send anything else to identify them. Use `platform_payload` for your own correlation: your order ID, your internal store ID, whatever you route on. We store the object untouched and return it on every read and webhook. # Platform API Source: https://docs.unihop.app/platforms/index Book and track UniHop deliveries for the merchants on your platform ## Who this is for Software that other businesses install and book through: a checkout delivery scheduling app, an order management system, a shipping layer in a storefront. Each merchant brings their own UniHop API key. They generate it in their UniHop dashboard and paste it into your app's settings. You send that key on their deliveries, and their deliveries are billed to their own account. You are never in the billing path. Booking deliveries for your own business, or running a marketplace where the orders are yours? Use the [Direct API](/direct/index) instead. ## Base URL Your platform identifier sits in the path: ``` https://backend.unihop.app/api/v1/{platform} ``` We issue the identifier at onboarding. It replaces `{platform}` in every call: ``` https://backend.unihop.app/api/v1/your_platform/deliveries ``` ## Your first delivery ```bash theme={null} curl -X POST https://backend.unihop.app/api/v1/your_platform/quote \ -H "Authorization: Bearer $MERCHANT_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "pickup_name": "Corner Bakery", "pickup_address_street": "Massachusetts Ave", "pickup_address_number": "1740", "pickup_address_city": "Cambridge", "pickup_address_state": "MA", "pickup_address_postal_code": "02138", "pickup_address_country": "US", "dropoff_name": "Dana Whitfield", "dropoff_address_street": "Broadway", "dropoff_address_number": "355", "dropoff_address_city": "Somerville", "dropoff_address_state": "MA", "dropoff_address_postal_code": "02145", "dropoff_address_country": "US", "email": "orders@cornerbakery.example", "delivery_date": "2026-08-20", "dropoff_start_time": "2026-08-20T18:00:00Z", "currency": "USD" }' ``` The same body works on `POST /deliveries`, so you can quote at checkout and book afterwards without rebuilding the request. Store the `uid` from the create response. Reads, cancellations and webhooks are all keyed on it. Your own order and store IDs go in `platform_payload`, which we return on every read and webhook. ## The five endpoints | | | | ---------------------------------------------------------------------- | ------------------------------------------- | | [Quote a delivery](/platforms/api-reference/endpoint/quote) | Price and distance, nothing created | | [Create a delivery](/platforms/api-reference/endpoint/create-delivery) | Book it and send it to dispatch | | [Get a delivery](/platforms/api-reference/endpoint/get-delivery) | Status, courier, ETA, proof of delivery | | [Cancel a delivery](/platforms/api-reference/endpoint/cancel-delivery) | Before pickup, with the fee stated up front | | [Check availability](/platforms/api-reference/endpoint/availability) | A liveness check for your storefront | ## Delivery styles The style drives which vehicles and handling rules apply. Omit `delivery_style` and you get **Standard**. | Style | Use it for | | ------------------ | ----------------------------------------------------------------------------------------------------------- | | `Standard` | Everyday parcels and orders one person can carry | | `Hybrid` | Routes that mix a scheduled window with on-demand sourcing | | `Special Handling` | Fragile, temperature-sensitive, or high-value goods | | `Oversize` | Anything needing an SUV or larger. Set `package_minimum_vehicle_size` to match, or the request is rejected. | Additional styles can be enabled for your platform during onboarding. ## Times and time zones Every datetime, in and out, is ISO 8601 UTC: `2026-08-20T18:00:00Z`. We don't infer local time from an address. Set `package_delivery_mode` to `NOW` for on-demand. Leave it out (or send `SCHEDULED`) and both `delivery_date` and `dropoff_start_time` are required. ## Tracking and updates Every created delivery returns a `tracking_link`, a public page you can give the recipient with no login. For programmatic updates, give us a webhook URL at onboarding. See [Webhooks](/platforms/webhooks). ## Need a hand? Your account manager handles platform identifiers, styles, and coverage. API questions: [help.unihop.app](https://help.unihop.app). # Webhooks Source: https://docs.unihop.app/platforms/webhooks Status changes and courier movement, pushed to your endpoint ## Turning them on Give your account manager an HTTPS URL during onboarding and we'll push events to it. No URL on file means no webhooks. Poll [`GET /deliveries/{uid}`](/platforms/api-reference/endpoint/get-delivery) instead for the same state. One URL per platform. Fan out to individual merchants on your side using `uid` or `platform_payload`. Both are on every event. ## What we send `POST` to your URL, `Content-Type: application/json`, with a JWT in the `Authorization` header. We expect a `2xx`. Anything else, or a timeout, and we retry up to five times with a growing gap between attempts. Webhooks can arrive more than once, and status events can arrive out of order when a courier's updates bunch up. Key on `uid` and treat handling as idempotent. ## Event types **Delivery events** cover the lifecycle of the delivery itself: | Event | Meaning | | ----------------------------- | ---------------------------------------------------------------------- | | `delivery.created` | We accepted the delivery and started sourcing a driver | | `delivery.assigned` | A driver has taken it | | `delivery.pickup_enroute` | The driver is on the way to the pickup | | `delivery.pickup_arrived` | The driver is at the pickup | | `delivery.pickup_complete` | The package is in the vehicle | | `delivery.dropoff_enroute` | The driver is on the way to the recipient | | `delivery.dropoff_arrived` | The driver is at the dropoff. Proof of delivery arrives on this event. | | `delivery.dropoff_complete` | Delivered | | `delivery.return_in_progress` | The package is going back to the pickup | | `delivery.returned` | The package is back at the pickup | | `delivery.canceled` | Canceled by you, by us, or by the provider. See `cancellation_reason`. | | `delivery.failed` | The delivery could not be completed | **Location events** are the same milestones carrying fresh courier coordinates. Use these to move a pin on a map, and the delivery events to drive state. `location.assigned_driver`, `location.pickup_enroute`, `location.pickup_arrived`, `location.pickup_complete`, `location.dropoff_enroute`, `location.dropoff_arrived`, `location.return_in_progress` ## Body ```json theme={null} { "uid": "9f8e7d6c-1b2a-4c3d-8e9f-0a1b2c3d4e5f", "event_name": "delivery.pickup_complete", "status": "Picked Up", "platform_payload": { "store_id": "corner-bakery-cambridge", "order_id": "10482" }, "price": { "value": 14.25, "currency": "USD" }, "distance": { "value": 2.4, "unit": "miles" }, "tip": 3.0, "pickup_name": "Corner Bakery", "pickup_phone_number": "+16175550142", "pickup_instructions": "Counter pickup, ask for the online order shelf", "email": "orders@cornerbakery.example", "pickup_address": { "street": "Massachusetts Ave", "number": "1740", "city": "Cambridge", "county": "Middlesex", "state": "MA", "postal_code": "02138", "country": "US", "latitude": 42.3875, "longitude": -71.1191 }, "dropoff_name": "Dana Whitfield", "dropoff_phone_number": "+16175550188", "dropoff_instructions": "Blue door, leave with the front desk", "dropoff_address": { "street": "Broadway", "number": "355", "city": "Somerville", "county": "Middlesex", "state": "MA", "postal_code": "02145", "country": "US", "latitude": 42.3812, "longitude": -71.0964 }, "driver_id": 82854783, "driver_name": "Marcus Bell", "driver_location": { "lat": 42.3841, "lng": -71.1077 }, "driver_pickup_phone_number": "+16175550110", "driver_dropoff_phone_number": "+16175550110", "driver_vehicle_make": "Toyota", "driver_vehicle_model": "Prius", "driver_vehicle_year": 2021, "dropoff_time_estimated": "2026-08-20T18:22:00+00:00", "delivery_date": "2026-08-20", "pickup_start_time": "2026-08-20T17:30:00+00:00", "dropoff_start_time": "2026-08-20T18:00:00+00:00", "delivery_start_time": "2026-08-20T17:30:00+00:00", "delivery_end_time": "2026-08-20T18:30:00+00:00", "package_description": "Two boxed cakes", "package_minimum_vehicle_size": "SEDAN", "package_delivery_mode": "scheduled", "package_requirements": ["photo_proof_of_delivery"], "package_value": 68.0, "items_count": 2, "items": [], "weight": 4.5 } ``` ### Notes on individual fields | Field | Worth knowing | | ------------------------------------ | -------------------------------------------------------------------------------------------------------------------- | | `uid` | The identifier `POST /deliveries` returned. The only key tying an event back to your order, so store it at creation. | | `platform_payload` | Whatever object you sent at creation, returned untouched. Put your own order and store IDs here. | | `status` | Human-readable delivery status, e.g. `Picked Up`. `event_name` is the machine-readable one; branch on that. | | `pickup_address` / `dropoff_address` | Nested objects, not flattened fields. Omitted entirely when we have nothing to put in them. | | `driver_location` | Present on `location.*` events and on delivery events once a driver is assigned. | | `price.value` | Decimal, converted from cents. `null` until pricing settles. | | `dropoff_verification_image_url` | Photo proof. Only on `delivery.dropoff_arrived`. | | `dropoff_signature_image_url` | Signature proof, when the delivery required one. Only on `delivery.dropoff_arrived`. | | `cancellation_reason` | Only on `delivery.canceled`. | | Datetimes | ISO 8601 UTC (`YYYY-MM-DDTHH:MM:SS+00:00`). `delivery_date` is a plain `YYYY-MM-DD`. | Fields we have no value for are sent as `null` or omitted. Treat both the same way. ## Verifying the request Each webhook carries a JWT signed with our RSA private key. Verify it with our public key before you trust the body. Your account manager provides `unihop_public_key.pem`. ``` Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9... ``` The token decodes to: ```json theme={null} { "iss": "unihop", "exp": 1786291200, "payload": { } } ``` `payload` holds the body documented above. Check that `iss` is `unihop`, that the signature verifies under `RS256`, and that `exp` hasn't passed. ```php PHP theme={null} use Firebase\JWT\JWT; use Firebase\JWT\Key; $token = substr($request->header('Authorization'), 7); $decoded = JWT::decode($token, new Key(file_get_contents('unihop_public_key.pem'), 'RS256')); abort_unless($decoded->iss === 'unihop', 401); $event = $decoded->payload; ``` ```javascript Node.js theme={null} const jwt = require('jsonwebtoken'); const fs = require('fs'); const publicKey = fs.readFileSync('unihop_public_key.pem'); app.post('/unihop/webhook', (req, res) => { const token = req.headers.authorization?.replace('Bearer ', ''); try { const decoded = jwt.verify(token, publicKey, { algorithms: ['RS256'] }); if (decoded.iss !== 'unihop') throw new Error('Unexpected issuer'); handleEvent(decoded.payload); return res.sendStatus(200); } catch (error) { return res.status(401).json({ error: error.message }); } }); ``` ```python Python theme={null} import jwt with open('unihop_public_key.pem', 'rb') as key_file: public_key = key_file.read() @app.route('/unihop/webhook', methods=['POST']) def unihop_webhook(): token = request.headers.get('Authorization', '').removeprefix('Bearer ') try: decoded = jwt.decode(token, public_key, algorithms=['RS256']) except jwt.PyJWTError as error: return jsonify({'error': str(error)}), 401 if decoded.get('iss') != 'unihop': return jsonify({'error': 'Unexpected issuer'}), 401 handle_event(decoded['payload']) return '', 200 ``` ## Responding Return a `2xx` as soon as you've stored the event, then do the real work asynchronously. We treat a slow endpoint as a failed one.