# Authorize App Source: https://docs.teleship.com/api-reference/authentication/authorize-app /api-reference/openapi.json get /oauth/authorize Initiates OAuth 2.0 authorization for partner applications. ## Setup Create an OAuth app in **Teleship Shipper Portal** to get your `clientId` and `clientSecret`. ## Usage **1. Start authorization:** ```javascript const state = crypto.randomUUID(); sessionStorage.setItem('oauth_state', state); window.location.href = `https://api.teleship.com/oauth/authorize?${new URLSearchParams({ clientId: 'your_client_id', responseType: 'code', redirectUri: 'https://yourapp.com/callback', scope: 'read_accounts write_shipments', state: state })}`; ``` **2. Handle callback:** ```javascript const params = new URLSearchParams(window.location.search); const code = params.get('code'); const accountClientId = params.get('account_client_id'); const accountClientSecret = params.get('account_client_secret'); const state = params.get('state'); // Validate state if (state !== sessionStorage.getItem('oauth_state')) throw new Error('Invalid state'); ``` **3. Get access token:** ```javascript const response = await fetch('https://api.teleship.com/oauth/token', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ clientId: accountClientId, clientSecret: accountClientSecret }) }); const { accessToken } = await response.json(); ``` **4. Make API calls:** ```javascript fetch('https://api.teleship.com/api/shipments', { headers: { 'Authorization': `Bearer ${accessToken}` } }); ``` ## Parameters | Parameter | Required | Description | |-----------|----------|-------------| | `clientId` | Yes | OAuth app client ID | | `responseType` | Yes | Must be `code` | | `redirectUri` | Yes | Callback URL | | `scope` | Yes | Space-separated permissions | | `state` | Recommended | CSRF token | ## Scopes - `read_accounts` `write_accounts` `read_shipments` `write_shipments` # Get access token Source: https://docs.teleship.com/api-reference/authentication/get-access-token /api-reference/openapi.json post /oauth/token Obtain an OAuth2 access token for API authentication. **How it works:** - Provide your client credentials (client_id and client_secret) - Receive a Bearer token for API access - Token expires after 1 hour **Security:** - Always use HTTPS - Store credentials securely - Never expose client_secret in client-side code # Refresh access token Source: https://docs.teleship.com/api-reference/authentication/refresh-access-token /api-reference/openapi.json post /oauth/refresh Obtain a new access token using a refresh token. **How it works:** - Provide your refresh token received from the /oauth/token endpoint - Receive a new Bearer token and optionally a new refresh token - Use this to maintain long-lived sessions without re-authentication **Security:** - Always use HTTPS - Store refresh tokens securely (encrypted) - Refresh tokens should be treated as sensitive as passwords # Cancel pickup Source: https://docs.teleship.com/api-reference/shipping-services/cancel-pickup /api-reference/openapi.json post /api/pickups/{pickupId}/cancel Cancel a previously scheduled pickup, preventing the collection from taking place. **When to use:** - Customer cancels pickup request - You need to reschedule the pickup for a different time **Result:** The pickup is cancelled and cannot be used for collection. # Create a manifest Source: https://docs.teleship.com/api-reference/shipping-services/create-a-manifest /api-reference/openapi.json post /api/manifests # Create shipping label Source: https://docs.teleship.com/api-reference/shipping-services/create-shipping-label /api-reference/openapi.json post /api/shipments/labels Create a shipping label for your shipment, ready for printing and attaching to your package. **What happens:** - Validates your shipment details - Books the shipment with the selected service - Returns a label and tracking number **Why use this?** Automate label generation for e-commerce orders, warehouse operations, or bulk shipping. # Delete webhook Source: https://docs.teleship.com/api-reference/shipping-services/delete-webhook /api-reference/openapi.json delete /api/webhooks/{id} Delete a webhook endpoint, stopping all event notifications to that URL. **Use this to:** - Remove outdated or compromised endpoints - Manage your integrations and event subscriptions # Get all services Source: https://docs.teleship.com/api-reference/shipping-services/get-all-services /api-reference/openapi.json get /api/services ### Teleship Services API Retrieve a comprehensive list of all shipping services available on the Teleship platform. **What you get:** - Service names and codes - Whether first-mile pickup is included - Typical transit times and dispatch schedules - Service type (End-to-End or Hub Direct) > **Tip:** Use this endpoint to dynamically populate service options in your shipping UI or to compare available logistics solutions. #### Available Services The following table summarizes all available shipping services: | Service Name | Code | First Mile Included | |-------------|------|-------------------| | Expedited DDP (Post Office drop-off/collection) | `TELESHIP-EXPEDITED-PICKUP` | true | | [New] Postal DDP - PDDP (Post Office drop-off/collection) | `TELESHIP-POSTAL-PICKUP` | true | | Expedited DDP for Enterprise (No first mile, >100 intl. parcels/day) | `TELESHIP-EXPEDITED-DROPOFF` | false | | Standard DDP for Enterprise (No first mile, >100 intl. parcels/day) | `TELESHIP-STANDARD-DROPOFF` | false | | Postal DDP for Enterprise (No first mile, >100 intl. parcels/day) | `TELESHIP-POSTAL-DROPOFF` | false | | Standard DDP (Post Office drop-off/collection) | `TELESHIP-STANDARD-PICKUP` | true | # Get all webhooks Source: https://docs.teleship.com/api-reference/shipping-services/get-all-webhooks /api-reference/openapi.json get /api/webhooks Retrieve a list of all webhook endpoints you have registered. ## Overview This endpoint returns all webhook endpoints associated with your account, including their configuration, status, and metadata. ## Response Details Each webhook in the response includes: - **id**: Unique identifier for the webhook - **url**: The endpoint URL where webhooks are sent - **description**: Optional description of the webhook's purpose - **enabledEvents**: Array of events this webhook is subscribed to - **enabled**: Whether the webhook is currently active - **metadata**: Custom key-value pairs attached to the webhook - **createdAt**: When the webhook was created - **updatedAt**: When the webhook was last modified ## Pagination The response supports pagination using query parameters: - **_start**: Starting index (default: 0) - **_end**: Ending index (default: 10) - **_sort**: Field to sort by (default: createdAt) - **_order**: Sort order - ASC or DESC (default: ASC) ## Example Response ```json [ { "id": "wh_1234567890", "url": "https://your-app.com/webhooks/teleship", "description": "Production webhook for order updates", "enabledEvents": ["label.generated", "shipment.updated"], "enabled": true, "metadata": { "environment": "production", "team": "shipping" }, "createdAt": "2024-01-15T10:30:00Z", "updatedAt": "2024-01-15T10:30:00Z" }, { "id": "wh_0987654321", "url": "https://staging.your-app.com/webhooks/teleship", "description": "Staging webhook for testing", "enabledEvents": ["*"], "enabled": false, "metadata": { "environment": "staging" }, "createdAt": "2024-01-10T14:20:00Z", "updatedAt": "2024-01-12T09:15:00Z" } ] ``` ## Webhook Management Use this endpoint to: - **Audit your webhooks** - Review all registered endpoints - **Check webhook status** - Verify which webhooks are enabled/disabled - **Monitor configuration** - Ensure webhooks are subscribed to the right events - **Troubleshoot issues** - Identify webhooks that might be causing problems ## Security Note The webhook secret is not included in the response for security reasons. The secret is only returned when creating a new webhook. # Get shipping quotes Source: https://docs.teleship.com/api-reference/shipping-services/get-shipping-quotes /api-reference/openapi.json post /api/rates/quotes Calculate and retrieve real-time shipping rates and quotes for your shipment. **How it works:** - Provide shipment details (origin, destination, weight, dimensions, etc.) - Receive a list of available services, each with: - Price breakdown (Freight, VAT, Duty, etc.) - Estimated delivery date - Service code and name **Example use case:** Get instant shipping options for a checkout page or to compare costs for different service levels. # Get tracking details Source: https://docs.teleship.com/api-reference/shipping-services/get-tracking-details /api-reference/openapi.json get /api/tracking/{trackingNumber} Get real-time tracking updates for a shipment using its tracking number. **What you receive:** - Current status (e.g., in transit, delivered) - Event history (pickups, scans, delivery attempts) - Estimated delivery date **Perfect for:** Building a branded tracking page or sending proactive shipment notifications. # Register webhook endpoint Source: https://docs.teleship.com/api-reference/shipping-services/register-webhook-endpoint /api-reference/openapi.json post /api/webhooks Register a new webhook endpoint to receive real-time notifications about shipping events. ## Overview Webhooks allow you to receive real-time updates about shipping events directly to your application. When events occur in your Teleship account, we'll send HTTP POST requests to your webhook endpoint with event data. ## How it works 1. **Register your endpoint** - Provide your URL and select which events to subscribe to 2. **Receive events** - Teleship sends HTTP POST requests to your endpoint when events occur 3. **Verify signatures** - Use the webhook secret to verify requests come from Teleship 4. **Process events** - Handle the event data in your application ## Payload Structure All webhook payloads follow a consistent structure: ```json { "eventName": "label.generated", "objectType": "shipment", "objectId": "6f384ad7-f8bf-40ce-8bf0-715248738f10", "data": { // Event-specific data (see examples below) } } ``` ### Payload Fields - **eventName**: The type of event that occurred (e.g., "label.generated", "shipment.updated") - **objectType**: The type of object this event relates to (e.g., "shipment", "manifest") - **objectId**: The unique identifier of the object (e.g., shipment ID, manifest ID) - **data**: The event-specific data payload ## Security & Signature Verification ### Webhook Secret Each webhook endpoint has a unique secret that's only returned when you create the webhook. This secret is used to verify that webhook requests come from Teleship. **Important**: The secret remains the same for the lifetime of the webhook unless you regenerate it. ### Signature Header Teleship includes a signature in the `x-teleship-signature` header with every webhook request. Verify this signature to ensure the request is authentic: ```javascript // Example signature verification const crypto = require('crypto'); function verifyWebhookSignature(payload, signature, secret) { const expectedSignature = crypto .createHmac('sha256', secret) .update(JSON.stringify(payload)) .digest('hex'); return crypto.timingSafeEqual( Buffer.from(signature), Buffer.from(expectedSignature) ); } ``` ## Event Types ### Available Events - **`*`**: Subscribe to all events (default) - **`label.generated`**: When a shipping label is created - **`shipment.updated`**: When shipment status or details change - **`manifest.created`**: When a manifest is created - **`document.uploaded`**: When documents are uploaded ### Event Data Structure The `data` field contains event-specific information. For shipment events, this includes: ```json { "status": "label_created", "shipmentId": "6f384ad7-f8bf-40ce-8bf0-715248738f10", "trackingNumber": "TSGBUSA54UHK092337564", "customerReference": "#1001", "shipDate": "2025-06-30T22:36:22.843Z", "estimatedDelivery": "2025-07-08T06:59:59.999Z", "events": [ { "timestamp": "2025-06-30T22:26:25.201Z", "code": "S_102", "description": "Shipment info received by carrier", "location": "London, UK" } ], "shipFrom": { "name": "London Store", "company": "TELESHIP LIMITED", "address": { "line1": "Flat 4, 24 Upper Tachbrook Street", "city": "London", "state": "England", "country": "GB", "postcode": "SW1V 1SW" } }, "shipTo": { "name": "Fanny Dadin", "email": "fanny@teleship.com", "phone": "+1 213-601-6000", "address": { "line1": "1300 Eunice Avenue", "city": "Los Angeles", "state": "CA", "country": "US", "postcode": "90001" } }, "firstMile": { "carrier": "DHL Express", "trackingNumber": "1234567890", "trackingUrl": "https://www.dhl.com/track/1234567890" }, "lastMile": { "carrier": "USPS", "trackingNumber": "9400100000000000000000", "trackingUrl": "https://tools.usps.com/go/TrackConfirmAction?tLabels=9400100000000000000000" } } ``` ## Important Details ### Events Array The `events` field is an **array** containing the complete event history for the shipment, not just the most recent event. Each event includes: - **timestamp**: When the event occurred (UTC timezone) - **code**: Event code from the carrier - **description**: Human-readable event description - **location**: Where the event occurred (if available) ### ObjectId and ObjectType - **objectId**: The unique identifier of the shipment, manifest, or other object this event relates to - **objectType**: The type of object ("shipment", "manifest", etc.) These fields help you identify which specific object the event relates to in your system. ### Timezone All timestamps in webhook payloads are in **UTC timezone** (ISO 8601 format). Convert to your local timezone as needed. ### FirstMile and LastMile The `firstMile` and `lastMile` objects contain external carrier tracking information: - **firstMile**: Information about the pickup/departure carrier - **lastMile**: Information about the final delivery carrier These fields are only populated when: - The shipment uses multiple carriers (e.g., international shipments) - External tracking numbers are available - The carriers provide tracking URLs The events in the `events` array come from both first-mile and last-mile carriers, providing a complete picture of the shipment's journey. ## Best Practices 1. **Verify signatures** - Always verify the webhook signature to ensure authenticity 2. **Handle duplicates** - Webhooks may be sent multiple times; use event IDs to prevent duplicate processing 3. **Respond quickly** - Return a 2xx status code immediately, then process the event asynchronously 4. **Handle failures gracefully** - Implement retry logic for failed webhook processing 5. **Monitor webhook health** - Track webhook delivery success rates and response times ## Example Implementation ```javascript // Express.js webhook handler example app.post('/webhooks/teleship', express.raw({type: 'application/json'}), (req, res) => { const signature = req.headers['x-teleship-signature']; const payload = req.body; // Verify signature if (!verifyWebhookSignature(payload, signature, process.env.WEBHOOK_SECRET)) { return res.status(400).send('Invalid signature'); } // Parse payload const event = JSON.parse(payload); // Handle different event types switch (event.eventName) { case 'label.generated': handleLabelGenerated(event.data); break; case 'shipment.updated': handleShipmentUpdated(event.data); break; default: console.log('Unhandled event type:', event.eventName); } // Respond quickly res.status(200).send('OK'); }); ``` ## Why use webhooks? - **Real-time updates**: Get instant notifications when shipment status changes - **Automation**: Trigger workflows based on shipping events - **Integration**: Sync shipment data with your order management system - **Customer experience**: Update customers with real-time tracking information # Retrieve a manifest Source: https://docs.teleship.com/api-reference/shipping-services/retrieve-a-manifest /api-reference/openapi.json get /api/manifests/{manifestId} # Retrieve shipping details Source: https://docs.teleship.com/api-reference/shipping-services/retrieve-shipping-details /api-reference/openapi.json get /api/shipments/labels/{shipmentId} Retrieve detailed information about a specific shipment, including: - Tracking status and history - Estimated and actual delivery dates - Downloadable shipping documents (labels, invoices) - Service and package details **Use this endpoint to:** Display shipment progress to customers or for internal tracking and auditing. # Schedule pickup Source: https://docs.teleship.com/api-reference/shipping-services/schedule-pickup /api-reference/openapi.json post /api/pickups Schedule a pickup request for your shipments, scheduling a collection from your location. **What happens:** - Validates your pickup window (startAt and endAt times) - Ensures pickup window is between 1 hour and 12 hours - Validates pickup window is within available hours (2AM-12PM Mon-Fri by default) - Schedules the pickup with the selected time window - Returns pickup confirmation **Pickup Window Requirements:** - Window duration: 1 hour (3600 seconds) to 12 hours (43200 seconds) - Available hours: 2AM-12PM Monday-Friday (configurable per account) - Both startAt and endAt must be in the future - Both times must be on weekdays - Times are validated as-is (no timezone conversion) **Why use this?** Schedule collections for multiple shipments at once, optimizing logistics operations. # Sync tracking data Source: https://docs.teleship.com/api-reference/shipping-services/sync-tracking-data /api-reference/openapi.json post /api/tracking/sync-tracking Force-sync tracking data from carrier APIs for shipments with middle-mile identifiers. Admin only. # Test webhook endpoint Source: https://docs.teleship.com/api-reference/shipping-services/test-webhook-endpoint /api-reference/openapi.json post /api/webhooks/test Send a test webhook notification to verify your endpoint is working correctly. ## Overview This endpoint allows you to test your webhook implementation by sending a sample webhook payload to your registered endpoints. This is useful for: - Verifying your webhook handler is working correctly - Testing signature verification - Debugging webhook processing logic - Ensuring your endpoint can handle the expected payload structure ## How it works 1. **Provide shipment IDs** - Specify which shipments to use for the test 2. **Send test webhooks** - Teleship sends test notifications to all your enabled webhooks 3. **Verify results** - Check the response to see which webhooks were notified successfully ## Test Payload The test webhook will send a `shipment.updated` event with real shipment data, allowing you to test with actual data structure. ## Response The response includes: - Overall success status - Number of webhooks notified - Detailed results for each shipment - Any errors that occurred during testing ## Example Usage ```bash curl -X POST "https://api.teleship.com/api/webhooks/test" \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "shipmentIds": ["ship_123", "ship_456"] }' ``` ## Example Response ```json { "success": true, "message": "Successfully tested webhooks for 2/2 shipments", "webhooksNotified": 4, "results": [ { "shipmentId": "ship_123", "success": true, "message": "Test webhook sent successfully to 2 webhook(s)", "webhooksNotified": 2 }, { "shipmentId": "ship_456", "success": true, "message": "Test webhook sent successfully to 2 webhook(s)", "webhooksNotified": 2 } ] } ``` ## Troubleshooting If webhook tests fail: 1. **Check endpoint URL** - Ensure your webhook endpoint is accessible 2. **Verify signature handling** - Make sure your signature verification is working 3. **Check response time** - Ensure your endpoint responds within 30 seconds 4. **Review logs** - Check your webhook handler logs for errors 5. **Test manually** - Use tools like ngrok to test locally during development # Upload shipping document Source: https://docs.teleship.com/api-reference/shipping-services/upload-shipping-document /api-reference/openapi.json post /documents/etds/upload # Void shipping label Source: https://docs.teleship.com/api-reference/shipping-services/void-shipping-label /api-reference/openapi.json post /api/shipments/labels/{shipmentId}/void Cancel a previously created shipping label, preventing the shipment from being processed or picked up. **When to use:** - Customer cancels an order after label creation - You need to correct shipment details before dispatch **Result:** The label is invalidated and cannot be used for shipping. # Export taxes collections as CSV Source: https://docs.teleship.com/api-reference/taxes-collections/export-taxes-collections-as-csv /api-reference/openapi.json get /api/taxes-collections/export # Get a taxes collection by ID Source: https://docs.teleship.com/api-reference/taxes-collections/get-a-taxes-collection-by-id /api-reference/openapi.json get /api/taxes-collections/{id} # List taxes collections Source: https://docs.teleship.com/api-reference/taxes-collections/list-taxes-collections /api-reference/openapi.json get /api/taxes-collections # Process duty payment for a collection Source: https://docs.teleship.com/api-reference/taxes-collections/process-duty-payment-for-a-collection /api-reference/openapi.json post /api/taxes-collections/{id}/payment Process the duty payment for a taxes collection using Stripe. # Calculate duties and taxes Source: https://docs.teleship.com/api-reference/trade-engine/calculate-duties-and-taxes /api-reference/openapi.json post /api/trade-engine/duties-taxes Calculate import duties, taxes, and customs fees for international shipments. **How it works:** - Provide shipment and commodity details (origin, destination, HS codes, values) - Receive a breakdown of all applicable duties and taxes in the `dutiesAndTaxes` response **Additional Services:** - `additionalServices.postalDuties`: Calculate lower postal duty rates instead of courier rates - `additionalServices.taxesCollection`: Create a DDU taxes collection (see below) **DDU Taxes Collection (when `additionalServices.taxesCollection: true`):** - Requires: `incoterms: DDU`, `trackingNumber`, and `shipTo.phone` OR `shipTo.email` - Creates a taxes collection record with status `pending_classification` - Triggers background HS code classification and duty recalculation - Returns `dutiesAndTaxes: null` (final amount calculated after classification) - Returns `collection` object with `collectionId`, `status`, `paymentUrl`, and `collectionDeadline` - Notification channel: Both SMS and email when both provided, otherwise whichever is available - Partner receives webhook when classification completes and collection is ready for payment **Why use this?** Show landed cost estimates to customers, avoid surprise fees, ensure customs compliance, and collect duties from consignees for DDU shipments. # Classify commodities Source: https://docs.teleship.com/api-reference/trade-engine/classify-commodities /api-reference/openapi.json post /api/trade-engine/classifications Classify multiple products or commodities to determine their correct HS codes and compliance requirements. **What you get:** - Predicted HS codes for each product - Regulatory and import restrictions - Confidence level of the classification **Use case:** Automate customs documentation and ensure accurate product classification for international shipping. # Get a single duties/taxes API usage audit log for the authenticated account Source: https://docs.teleship.com/api-reference/trade-engine/get-a-single-dutiestaxes-api-usage-audit-log-for-the-authenticated-account /api-reference/openapi.json get /api/trade-engine/duties-usage-logs/{id} # Get duties/taxes API usage statistics for the authenticated account Source: https://docs.teleship.com/api-reference/trade-engine/get-dutiestaxes-api-usage-statistics-for-the-authenticated-account /api-reference/openapi.json get /api/trade-engine/duties-usage-stats # Get HTS restrictions for products Source: https://docs.teleship.com/api-reference/trade-engine/get-hts-restrictions-for-products /api-reference/openapi.json post /api/trade-engine/hts-compliance Retrieve HTS/HS code restrictions for multiple products without performing classification. **What you get:** - Import restrictions and compliance requirements for each product - Region-specific filtering (US, EU27, ROW) - Review state tracking (if productId/variantId provided) - Progressive HTS code matching for maximum coverage **Use case:** Identify import restrictions, licensing requirements, and compliance obligations for products with existing HS codes. **Key Features:** - Destination country filtering: Filter restrictions by destination and additional regions - Review state: Track which restrictions have been reviewed by merchants - Flexible lookup: Match products by productId, variantId, or hsCode - Progressive matching: Matches HS codes at multiple specificity levels (e.g., 8471.30.01 → 8471.30 → 8471) **Note:** Unlike the classifications endpoint, this does NOT perform HS code classification. Use this when you already have HS codes and only need restrictions. # List duties/taxes API usage audit logs for the authenticated account Source: https://docs.teleship.com/api-reference/trade-engine/list-dutiestaxes-api-usage-audit-logs-for-the-authenticated-account /api-reference/openapi.json get /api/trade-engine/duties-usage-logs # Teleship API Source: https://docs.teleship.com/index Build cross-border shipping, trade compliance, tracking, webhooks, and taxes collection with Teleship. Teleship is a cross-border logistics API for global commerce. Use the API to quote shipments, create labels, track parcels, classify commodities, calculate duties and taxes, and collect DDU charges. ## Base URLs | Environment | URL | | ----------- | -------------------------- | | Production | `https://api.teleship.com` | ## Authentication Most endpoints use Bearer authentication. Use the authentication endpoints to authorize apps, get access tokens, and refresh tokens. ## API areas | Area | Use it to | | ----------------- | ------------------------------------------------------------------------- | | Authentication | Authorize apps and manage tokens | | Shipping services | Quote, label, track, manifest, schedule pickups, and manage webhooks | | Trade engine | Classify commodities and calculate duties and taxes | | Taxes collections | List collections, export CSVs, retrieve collections, and process payments | ## Errors Error responses use a `messages` array with code, level, timestamp, message, and details. Use the endpoint pages for request schemas, examples, response bodies, and status codes.