Microsoft Dynamics 365 Integration with CubeMaster API

A step-by-step guide to consuming the https://api.cubemaster.net/loads endpoint using Dynamics 365 orders or shipments

To use the CubeMaster API, you need an API key (TokenID) for authentication. Here's how to get started:

  1. Visit the CubeMaster website: https://cubemaster.net.
  2. Locate the "Sign In" option (typically found in the top-right corner).
  3. Fill out the registration form with your details (e.g., name, email, password, company information).
  4. After signing up, log in to your account dashboard.
  5. Navigate to the "Settings" - "Integration" section to generate your API key (TokenID).
  6. Generate an API key. Once generated, you’ll receive a unique TokenID (e.g., abc123xyz789). Copy this key and store it securely, as it will be used in the HTTP headers of your API requests.
  7. Copy the TokenID and store it securely.

Note: The TokenID will be used in the HTTP headers of your POST request for authentication.

A RESTful API is a way for systems like Dynamics 365 to talk to external services like CubeMaster:

  • Endpoint: A URL like https://api.cubemaster.net/loads where you send data.
  • POST Method: Used to send data to create a resource (e.g., a load plan).
  • JSON: A lightweight data format (like a structured list) for sending and receiving info.
  • Headers: Metadata sent with your request, including the TokenID for security.
  • Response: The server’s reply, which could be success data or an error message.

We’ll send shipment data from Dynamics 365 to CubeMaster and get back a detailed load plan.

Prepare Dynamics 365 to integrate with the CubeMaster API:

  1. Log in to Dynamics 365:
    • Go to your instance (e.g., https://yourcompany.crm.dynamics.com).
    • Enter your credentials in the login screen and click "Sign In."
  2. Navigate to Power Automate:
    • From the Dynamics 365 home screen, click the app launcher (9-dot grid) in the top-left corner.
    • Select "Power Automate" from the list of apps.
  3. Create a new flow:
    • In Power Automate, click "Create" in the left sidebar (a blue button).
    • Choose "Automated Cloud Flow" from the options.
    • In the pop-up, enter a name like "CubeMaster Load Builder" in the "Flow name" field.
    • Search for and select the trigger "When a record is created (Dynamics 365)" in the "Choose your flow's trigger" box.
    • Click "Create" at the bottom of the pop-up.
  4. Configure the trigger:
    • In the trigger settings, select your "Organization Name" from the dropdown (your Dynamics 365 instance).
    • Set "Entity Name" to "Sales Orders" or "Shipments" (depending on your data source) from the dropdown.
    • Click "New Step" (a circular plus button below the trigger).

Use Dynamics 365 order or shipment data to build the JSON request for https://api.cubemaster.net/loads:

  1. Access order/shipment details:
    • In Dynamics 365, go to "Sales" > "Orders" or "Inventory" > "Shipments" from the left navigation bar.
    • Select an order (e.g., click a row in the "Active Sales Orders" grid).
    • Note fields like "Order Number" (for Title), "Description," and line items (for Cargoes).
  2. Add a "Compose" action in Power Automate:
    • Click "New Step" > search for "Compose" > select "Data Operation - Compose."
    • In the "Inputs" field, construct the JSON using dynamic content from the trigger:
  3. Build the JSON payload:
    {
        "Title": @{triggerOutputs()?['body/name']},
        "Description": @{triggerOutputs()?['body/description']},
        "Cargoes": [
            {
                "Name": @{triggerOutputs()?['body/_productid_value@OData.Community.Display.V1.FormattedValue']},
                "Length": @{triggerOutputs()?['body/new_length']},
                "Width": @{triggerOutputs()?['body/new_width']},
                "Height": @{triggerOutputs()?['body/new_height']},
                "Weight": @{triggerOutputs()?['body/new_weight']},
                "OrientationsAllowed": "OrientationsAll",
                "TurnAllowedOnFloor": false,
                "Qty": @{triggerOutputs()?['body/quantity']},
                "ColorKnownName": "Brown"
            }
        ],
        "Containers": [
            {
                "VehicleType": "Dry",
                "Name": "53FT-Intermodal",
                "Length": 630,
                "Width": 98,
                "Height": 106,
                "ColorKnownName": "Blue"
            }
        ],
        "Rules": {
            "IsWeightLimited": true,
            "IsSequenceUsed": false,
            "FillDirection": "FrontToRear",
            "CalculationType": "MixLoad"
        }
    }

    Notes:

    • Use dynamic content (lightning bolt icon) to insert fields like productid, quantity, etc.
    • Add custom fields (e.g., new_length) via "Settings" > "Customizations" > "Customize the System."
    • For multiple line items, use "Apply to each" to loop through triggerOutputs()?['body/salesorderdetails'].

Send the request to CubeMaster using Power Automate:

  1. Add an HTTP action:
    • Click "New Step" > search for "HTTP" > select "HTTP - HTTP."
  2. Configure the HTTP action:
    • Method: Select "POST" from the dropdown.
    • URI: Enter https://api.cubemaster.net/loads.
    • Headers: Add:
      • Key: Authorization, Value: Bearer @{variables('TokenID')}
      • Key: Content-Type, Value: application/json
    • Body: Insert "Outputs" from the "Compose" action.
  3. Save and test:
    • Click "Save" and "Test" (top-right), then create a test order in Dynamics 365.

Process and store the response:

  1. Inspect the response:
    {
        "status": "succeed",
        "message": "Engine created. 5 cargoes. 1 empty containers. Calculation started. Calculation ended. The load built successfully. The load saved to the cloud database.",
        "document": {
            "title": "New Mixed Truck Load",
            "calculationTimeInSeconds": 0.6152743
        },
        "loadSummary": {
            "cargoesLoaded": 68,
            "volumeLoaded": 5261723.4606,
            "weightLoaded": 42674.59999999999
        },
        "filledContainers": [
            {
                "name": "#1 53FT-Intermodal",
                "loadSummary": {
                    "volumeUtilization": 80.39990374424703
                },
                "graphics": {
                    "images": {
                        "path3DDiagram": "https://api.cubemaster.net/runtimes/b28413ca_51ed_44c9_b92e_13147363fd61.PNG"
                    }
                }
            }
        ]
    }
  2. Add "Parse JSON":
    • Click "New Step" > "Parse JSON."
    • Content: Select "Body" from HTTP.
    • Schema: Generate from the sample response above.
  3. Check status:
    • Add "Condition": Parse JSON status equals succeed.
    • "If yes": Create a "Load Plans" record in Dynamics 365 with fields like volumeUtilization.
    • "If no": Send an email with Parse JSON message.

Monitor and troubleshoot the API integration using Power Automate and Dynamics 365 tools:

  1. Check Flow Run History:
    • In Power Automate, go to "My Flows" from the left sidebar.
    • Click on your "CubeMaster Load Builder" flow (listed as a row).
    • In the "Run history" section, click a recent run (timestamped row) to open its details.
    • Expand each step (e.g., "HTTP," "Parse JSON") by clicking the arrow next to it to view:
      • Inputs: Verify the request body and headers (e.g., TokenID).
      • Outputs: Check the response status code (200 for success) and body.
      • Errors: Look for red "Failed" indicators and error messages (e.g., "401 Unauthorized" for invalid TokenID).
  2. Test with Manual Trigger:
    • Edit the flow: Click the three dots (...) next to your flow in "My Flows" > "Edit."
    • Add a "Manually trigger a flow" action as the first step (temporarily replace the Dynamics 365 trigger).
    • Click "Test" (top-right), select "Manually," and run it to isolate API issues from Dynamics 365 triggers.
    • Review the HTTP action’s output for errors like "400 Bad Request" (invalid JSON) or "500 Internal Server Error" (CubeMaster issue).
  3. Enable Flow Analytics:
    • In Power Automate, click "Analytics" in the left sidebar.
    • Select your flow to view success/failure rates, run durations, and error trends in graphical dashboards.
    • Use this to identify recurring issues (e.g., frequent timeouts might indicate network problems).
  4. Log Errors in Dynamics 365:
    • In your flow, after the "Condition" in Step 6, add a "Create a new record" action in the "If no" branch.
    • Set "Entity Name" to a custom "API Logs" entity (create via "Settings" > "Customizations" if needed).
    • Map fields:
      • Error Message: Parse JSON message
      • Timestamp: Current time (dynamic content)
      • Order ID: triggerOutputs()?['body/salesorderid']
    • View logs in Dynamics 365 under a custom "API Logs" tab to track failures.
  5. Use Dynamics 365 System Jobs:
    • In Dynamics 365, go to "Settings" > "System Jobs" from the left navigation.
    • Filter for "Workflow" or "Flow" jobs related to your flow name to see execution status (e.g., "Failed," "Succeeded").
    • Click a failed job to view details like error codes or missing permissions.
  6. Debugging Tips:
    • If the HTTP action fails:
      • Check TokenID: Ensure it matches Step 1 and isn’t expired (re-generate if needed).
      • Validate JSON: Copy the "Compose" output to a tool like JSONLint to fix syntax errors.
      • Test endpoint: Use Postman with the same request to confirm CubeMaster’s response.
    • If data isn’t saved: Verify "Parse JSON" schema matches the response and mappings in "Create a new record" are correct.
    • Enable verbose logging: Add a "Compose" action before HTTP to log the request body for inspection.

Tip: Save and test after each debug step to isolate issues, then revert to the original trigger once stable.