Skip to content

๐Ÿš€ Quick Start Guide - Main System Integration โ€‹

๐Ÿ“‹ Overview โ€‹

Get your main system integrated with Partner Services in just 15 minutes! This guide covers the essential steps to start using partner management and shipment assignment APIs.

Time Required: 15 minutes
Skill Level: Intermediate
Prerequisites: Basic REST API knowledge


๐ŸŽฏ What You'll Accomplish โ€‹

By the end of this guide, you'll have:

  • โœ… HMAC Authentication setup and working
  • โœ… Partner Data Retrieval from the API
  • โœ… Basic Shipment Assignment functionality
  • โœ… Test Environment ready for development

๐Ÿ”ง Step 1: Environment Setup (2 minutes) โ€‹

API Configuration โ€‹

javascript
// config.js
const API_CONFIG = {
  baseURL: "https://partner-services.logistics.com/api/v1",
  // For development/testing
  devURL: "http://localhost:3000/api/v1",

  // Your credentials (obtain from Partner Services team)
  partnerId: "your_partner_id",
  apiKey: "your_api_key",
  secretKey: "your_secret_key",
};

Required Dependencies โ€‹

bash
# For Node.js projects
npm install axios crypto-js moment

# For Python projects
pip install requests cryptography

# For PHP projects
composer require guzzlehttp/guzzle

๐Ÿ” Step 2: HMAC Authentication Setup (5 minutes) โ€‹

Node.js Implementation โ€‹

javascript
const crypto = require("crypto");
const axios = require("axios");

class PartnerServicesClient {
  constructor(config) {
    this.baseURL = config.baseURL;
    this.partnerId = config.partnerId;
    this.secretKey = config.secretKey;
  }

  // Generate HMAC signature
  generateSignature(method, path, body, timestamp) {
    const bodyStr = body ? JSON.stringify(body) : "";
    const stringToSign = `${method}\n${path}\n${bodyStr}\n${timestamp}`;

    return crypto
      .createHmac("sha256", this.secretKey)
      .update(stringToSign)
      .digest("hex");
  }

  // Make authenticated API request
  async makeRequest(method, path, body = null) {
    const timestamp = Math.floor(Date.now() / 1000);
    const signature = this.generateSignature(method, path, body, timestamp);

    const headers = {
      "Content-Type": "application/json",
      "x-partner-id": this.partnerId,
      "x-timestamp": timestamp,
      "x-signature": signature,
    };

    try {
      const response = await axios({
        method,
        url: `${this.baseURL}${path}`,
        headers,
        data: body,
      });

      return response.data;
    } catch (error) {
      console.error("API Error:", error.response?.data || error.message);
      throw error;
    }
  }
}

// Initialize client
const client = new PartnerServicesClient(API_CONFIG);

Authentication Test โ€‹

javascript
// Test authentication
async function testAuth() {
  try {
    const result = await client.makeRequest("GET", "/health");
    console.log("โœ… Authentication successful:", result);
    return true;
  } catch (error) {
    console.error("โŒ Authentication failed:", error.message);
    return false;
  }
}

// Run test
testAuth();

๐Ÿ‘ฅ Step 3: Partner Data Retrieval (3 minutes) โ€‹

Fetch Partner Configuration โ€‹

javascript
async function getPartnerData(partnerId) {
  try {
    // Get comprehensive partner data
    const partnerData = await client.makeRequest(
      "GET",
      `/partners/comprehensive-data?format=standard`
    );

    console.log("Partner Zones:", partnerData.data.zones?.total || 0);
    console.log("Partner Services:", partnerData.data.services?.total || 0);
    console.log(
      "Partner Packages:",
      partnerData.data.packages?.packageCharges?.total || 0
    );

    return partnerData;
  } catch (error) {
    console.error("Failed to fetch partner data:", error);
    throw error;
  }
}

// Get your partner data
getPartnerData().then((data) => {
  console.log("โœ… Partner data loaded successfully");
});

Fetch All Partners (for main system) โ€‹

javascript
async function getAllPartners() {
  try {
    // This will be available after P3.8.1 implementation
    const partners = await client.makeRequest("GET", "/partners/bulk-data");

    console.log(`Found ${partners.data.summary.totalPartners} partners`);
    console.log(`Active: ${partners.data.summary.activePartners}`);

    return partners.data.partners;
  } catch (error) {
    console.error("Failed to fetch all partners:", error);
    // Fallback: Use individual partner APIs
    return await fetchPartnersIndividually();
  }
}

๐Ÿ“ฆ Step 4: Shipment Assignment Test (5 minutes) โ€‹

Check Partner Availability โ€‹

javascript
async function checkPartnerAvailability(shipmentDetails) {
  try {
    const availabilityRequest = {
      pickupPincode: shipmentDetails.pickupPincode,
      deliveryPincode: shipmentDetails.deliveryPincode,
      weight: shipmentDetails.weight,
      shipmentType: shipmentDetails.shipmentType || "B2C",
      paymentType: shipmentDetails.paymentType || "PREPAID",
      declaredValue: shipmentDetails.declaredValue || 0,
      serviceRequirements: ["PICKUP", "DELIVERY"],
    };

    const availability = await client.makeRequest(
      "POST",
      "/partners/availability/check",
      availabilityRequest
    );

    console.log("Partner available:", availability.data.isAvailable);
    if (availability.data.isAvailable) {
      console.log("Confidence:", availability.data.confidence + "%");
      console.log("Available services:", availability.data.services.available);
    }

    return availability.data;
  } catch (error) {
    console.error("Availability check failed:", error);
    throw error;
  }
}

Calculate Shipment Charges โ€‹

javascript
async function calculateCharges(shipmentDetails) {
  try {
    const chargeRequest = {
      partnerId: API_CONFIG.partnerId,
      pickupPincode: shipmentDetails.pickupPincode,
      deliveryPincode: shipmentDetails.deliveryPincode,
      weight: shipmentDetails.weight,
      shipmentType: shipmentDetails.shipmentType || "B2C",
      paymentType: shipmentDetails.paymentType || "PREPAID",
      declaredValue: shipmentDetails.declaredValue || 0,
      serviceRequirements: shipmentDetails.serviceRequirements || [
        "PICKUP",
        "DELIVERY",
      ],
    };

    const charges = await client.makeRequest(
      "POST",
      "/shipments/calculate-charges",
      chargeRequest
    );

    if (charges.data.available) {
      console.log("โœ… Charge calculation successful");
      console.log("Total Amount:", "โ‚น" + charges.data.charges.totalAmount);
      console.log("Weight Charge:", "โ‚น" + charges.data.charges.weightCharge);
      console.log(
        "Distance Charge:",
        "โ‚น" + charges.data.charges.distanceCharge
      );
    } else {
      console.log("โŒ Partner not available for this shipment");
      console.log("Reason:", charges.data.reason);
    }

    return charges.data;
  } catch (error) {
    console.error("Charge calculation failed:", error);
    throw error;
  }
}

Complete Test Example โ€‹

javascript
async function testShipmentFlow() {
  const testShipment = {
    pickupPincode: "110001",
    deliveryPincode: "400001",
    weight: 1500, // grams
    shipmentType: "B2C",
    paymentType: "PREPAID",
    declaredValue: 2500,
    serviceRequirements: ["PICKUP", "DELIVERY"],
  };

  console.log("๐Ÿงช Testing shipment flow...");

  // Step 1: Check availability
  const availability = await checkPartnerAvailability(testShipment);

  if (availability.isAvailable) {
    // Step 2: Calculate charges
    const charges = await calculateCharges(testShipment);

    console.log("โœ… Test completed successfully!");
    return { availability, charges };
  } else {
    console.log("โš ๏ธ Partner not available for test shipment");
    return { availability };
  }
}

// Run the test
testShipmentFlow().catch(console.error);

โœ… Step 5: Verification Checklist โ€‹

Run through this checklist to ensure everything is working:

javascript
async function runVerificationChecklist() {
  console.log("๐Ÿ” Running verification checklist...\n");

  const checks = [
    {
      name: "Authentication",
      test: () => client.makeRequest("GET", "/health"),
    },
    {
      name: "Partner Data Access",
      test: () => client.makeRequest("GET", "/partners/comprehensive-data"),
    },
    {
      name: "Availability Check",
      test: () =>
        checkPartnerAvailability({
          pickupPincode: "110001",
          deliveryPincode: "400001",
          weight: 1000,
          shipmentType: "B2C",
          paymentType: "PREPAID",
        }),
    },
    {
      name: "Charge Calculation",
      test: () =>
        calculateCharges({
          pickupPincode: "110001",
          deliveryPincode: "400001",
          weight: 1000,
          shipmentType: "B2C",
          paymentType: "PREPAID",
        }),
    },
  ];

  const results = [];
  for (const check of checks) {
    try {
      await check.test();
      console.log(`โœ… ${check.name}: PASSED`);
      results.push({ name: check.name, status: "PASSED" });
    } catch (error) {
      console.log(`โŒ ${check.name}: FAILED - ${error.message}`);
      results.push({
        name: check.name,
        status: "FAILED",
        error: error.message,
      });
    }
  }

  console.log("\n๐Ÿ“Š Verification Results:");
  const passed = results.filter((r) => r.status === "PASSED").length;
  console.log(`${passed}/${results.length} checks passed`);

  if (passed === results.length) {
    console.log("๐ŸŽ‰ All checks passed! You're ready to integrate.");
  } else {
    console.log("โš ๏ธ Some checks failed. Review the errors above.");
  }

  return results;
}

// Run verification
runVerificationChecklist();

๐ŸŽ‰ Success! What's Next? โ€‹

Congratulations! You've successfully set up basic integration. Here's what to explore next:

Immediate Next Steps โ€‹

  1. Authentication Guide - Advanced authentication patterns
  2. Main System Flow - Complete workflow implementation
  3. Partner Setup - Partner configuration APIs

Advanced Features (Coming Soon) โ€‹

  • Bulk Partner Operations - Load multiple partners efficiently
  • Real-time Status Updates - Live partner availability
  • Partner Ranking - Compare partners by cost/speed/reliability
  • Dashboard APIs - Operational metrics and monitoring

Production Considerations โ€‹

  • Error Handling - Implement robust error recovery
  • Caching - Add Redis/memory caching for performance
  • Rate Limiting - Respect API rate limits
  • Monitoring - Track API performance and errors

๐Ÿ†˜ Troubleshooting โ€‹

Common Issues โ€‹

โŒ Authentication Failures

Error: 401 Unauthorized

Solution: Check your partnerId, secretKey, and signature generation logic.

โŒ Partner Not Found

Error: Partner data not available

Solution: Verify your partnerId is correct and partner is active.

โŒ Network Timeouts

Error: Request timeout

Solution: Check network connectivity and API server status.

Debug Mode โ€‹

javascript
// Enable debug logging
const client = new PartnerServicesClient({
  ...API_CONFIG,
  debug: true,
});

Getting Help โ€‹


๐ŸŽฏ Next Steps โ€‹

Now that you have a working integration, explore these resources:

๐Ÿ“š Essential References โ€‹

  1. API Routes Reference - Quick-scan of all available endpoints
  2. Authentication Guide - Advanced HMAC implementation
  3. Main System Flow - Complete workflow integration

๐Ÿ”ง Advanced Topics โ€‹

  1. Error Handling - Robust error management strategies
  2. Performance Optimization - Caching and scaling techniques
  3. API Examples - More implementation examples

๐ŸŽฏ Ready for production? Start with Error Handling and Performance Optimization!

Released under the MIT License.