Using PHP (cURL and Guzzle)
To use the CubeMaster API, you need an API key (TokenID) for authentication. Here's how to get started:
TokenID (e.g., abc123xyz789). Copy this key and store it securely, as it will be used in the HTTP headers of your API requests.Note: The TokenID will be used in the HTTP headers of your POST request for authentication.
For beginners, a RESTful API (Representational State Transfer) is a way for applications to communicate over the internet using standard HTTP methods like GET, POST, PUT, and DELETE.
https://api.cubemaster.net/loads) where the API can be accessed.The CubeMaster API follows REST principles, allowing you to send structured JSON data to build load plans and receive detailed responses.
Assume your customer's orders or shipments are stored in a legacy database (e.g., MySQL). You need to fetch this data to build the API request.
<?php
$conn = new mysqli("localhost", "username", "password", "legacy_db");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Fetch orders/shipments
$sql = "SELECT item_name, length, width, height, weight, qty FROM shipments WHERE order_id = '12345'";
$result = $conn->query($sql);
$cargoes = [];
while ($row = $result->fetch_assoc()) {
$cargoes[] = [
"Name" => $row["item_name"],
"Length" => (float)$row["length"],
"Width" => (float)$row["width"],
"Height" => (float)$row["height"],
"Weight" => (float)$row["weight"],
"Qty" => (int)$row["qty"],
"OrientationsAllowed" => "OrientationsAll",
"TurnAllowedOnFloor" => false,
"ColorKnownName" => "Brown" // Default value
];
}
$conn->close();
?>
This code connects to a MySQL database, retrieves shipment data, and formats it into an array compatible with the CubeMaster API's Cargoes structure.
Construct the request payload by combining static data with dynamic data from the legacy database. Below is the full request JSON used in this guide:
{
"Title": "New Mixed Truck Load",
"Description": "Hello Web API",
"Cargoes": [
{
"Name": "ITEM001",
"Length": 72,
"Width": 30,
"Height": 75,
"Weight": 1002.45,
"OrientationsAllowed": "OrientationsAll",
"TurnAllowedOnFloor": false,
"Qty": 16,
"ColorKnownName": "Brown"
},
{
"Name": "ITEM002",
"Length": 27.31,
"Width": 37.5,
"Height": 76.67,
"Weight": 521.45,
"OrientationsAllowed": "OrientationsAll",
"TurnAllowedOnFloor": false,
"Qty": 28,
"ColorKnownName": "Aqua"
},
{
"Name": "SKU0005",
"Length": 27.31,
"Width": 9.5,
"Height": 75.67,
"Weight": 501.45,
"OrientationsAllowed": "OrientationsAll",
"TurnAllowedOnFloor": true,
"Qty": 24,
"ColorKnownName": "Beige"
},
{
"Name": "SKU0005",
"Qty": 23
},
{
"Name": "SKU0008",
"Qty": 34
}
],
"Containers": [
{
"VehicleType": "Dry",
"Name": "53FT-Intermodal",
"Length": 630,
"Width": 98,
"Height": 106,
"ColorKnownName": "Blue"
}
],
"Rules": {
"IsWeightLimited": true,
"IsSequenceUsed": false,
"FillDirection": "FrontToRear",
"CalculationType": "MixLoad"
}
}
In PHP, encode this as a JSON string:
<?php
$requestData = [
"Title" => "New Mixed Truck Load",
"Description" => "Hello Web API",
"Cargoes" => $cargoes, // From Step 3
"Containers" => [
[
"VehicleType" => "Dry",
"Name" => "53FT-Intermodal",
"Length" => 630,
"Width" => 98,
"Height" => 106,
"ColorKnownName" => "Blue"
]
],
"Rules" => [
"IsWeightLimited" => true,
"IsSequenceUsed" => false,
"FillDirection" => "FrontToRear",
"CalculationType" => "MixLoad"
]
];
$jsonData = json_encode($requestData);
?>
Use PHP's cURL to send the POST request with the TokenID in the headers.
<?php
$apiUrl = "https://api.cubemaster.net/loads";
$tokenId = "YOUR_TOKEN_ID_HERE"; // Replace with your actual TokenID
$ch = curl_init($apiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Content-Type: application/json",
"Authorization: TokenID $tokenId"
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (curl_errno($ch)) {
echo "cURL Error: " . curl_error($ch);
}
curl_close($ch);
?>
UI Elements: curl_init() initializes the cURL session, curl_setopt() sets options like headers and payload, and curl_exec() executes the request.
Guzzle is a PHP HTTP client that simplifies API requests. First, install it via Composer:
composer require guzzlehttp/guzzle
Then, use this code:
<?php
require 'vendor/autoload.php';
use GuzzleHttp\Client;
$apiUrl = "https://api.cubemaster.net/loads";
$tokenId = "YOUR_TOKEN_ID_HERE"; // Replace with your actual TokenID
$client = new Client();
$response = $client->post($apiUrl, [
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => "TokenID $tokenId"
],
'json' => $requestData // From Step 4
]);
$httpCode = $response->getStatusCode();
$body = $response->getBody()->getContents();
?>
UI Elements: Guzzle’s Client class handles the request, post() method sends the JSON payload, and headers are set in a clean, array-based syntax.
After making the request, handle the response. Below is the sample response JSON:
{
"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.",
"calculationError": "InvalidCargoSize",
"document": {
"title": "New Mixed Truck Load",
"description": "Hello Web API",
"isShared": true,
"isAutoSaved": true,
"isPending": false,
"calculationTimeInSeconds": 0.6152743,
"processId": "",
"batchId": "",
"createdBy": "CHANG@LOGEN.CO.KR",
"createdAt": "2023-02-11T01:17:01.7392204+09:00",
"updatedAt": "0001-01-01T00:00:00"
},
"loadSummary": {
"cargoesLoaded": 68,
"piecesLoaded": 68,
"cargoesLeft": 0,
"piecesLeft": 57,
"unitloadsLoaded": 0,
"volumeLoaded": 5261723.4606,
"weightLoaded": 42674.59999999999,
"priceLoaded": 0,
"containersLoaded": 1
},
"filledContainers": [ /* Truncated for brevity */ ],
"reportLinks": {
"overview": "https://cubemaster.net/source/report/openlink.asp?id=cc3717aa-3460-4af0-ae59-6908bc0a496e"
},
"uom": "UnitEnglish"
}
cURL Handling:
<?php
if ($httpCode === 200) {
$responseData = json_decode($response, true);
if ($responseData['status'] === 'succeed') {
echo "Load built successfully: " . $responseData['message'] . "\n";
echo "Report Link: " . $responseData['reportLinks']['overview'] . "\n";
echo "Total Weight Loaded: " . $responseData['loadSummary']['weightLoaded'] . "\n";
} else {
echo "Error: " . $responseData['message'] . "\n";
if (!empty($responseData['calculationError'])) {
echo "Calculation Error: " . $responseData['calculationError'] . "\n";
}
}
} else {
echo "HTTP Error: " . $httpCode . "\n";
echo "Response: " . $response . "\n";
}
?>
Guzzle Handling:
<?php
if ($httpCode === 200) {
$responseData = json_decode($body, true);
if ($responseData['status'] === 'succeed') {
echo "Load built successfully: " . $responseData['message'] . "\n";
echo "Report Link: " . $responseData['reportLinks']['overview'] . "\n";
echo "Total Weight Loaded: " . $responseData['loadSummary']['weightLoaded'] . "\n";
} else {
echo "Error: " . $responseData['message'] . "\n";
if (!empty($responseData['calculationError'])) {
echo "Calculation Error: " . $responseData['calculationError'] . "\n";
}
}
} else {
echo "HTTP Error: " . $httpCode . "\n";
echo "Response: " . $body . "\n";
}
?>
Check the status, display success messages, or handle errors like InvalidCargoSize.
To monitor and debug API calls effectively:
<?php
require 'vendor/autoload.php';
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
$log = new Logger('api');
$log->pushHandler(new StreamHandler('api.log', Logger::DEBUG));
$log->info('Request', ['url' => $apiUrl, 'data' => $requestData]);
$log->info('Response', ['code' => $httpCode, 'body' => $response]);
?>
CURLOPT_VERBOSE to true and log output.<?php
$verbose = fopen('php://temp', 'w+');
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_STDERR, $verbose);
$response = curl_exec($ch);
rewind($verbose);
$verboseLog = stream_get_contents($verbose);
echo "cURL Debug: " . $verboseLog;
?>
debug option.<?php
$response = $client->post($apiUrl, [
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => "TokenID $tokenId"
],
'json' => $requestData,
'debug' => true
]);
?>
These techniques help identify issues like authentication failures, malformed JSON, or server errors.