hublifyConnector
Folgende beispielhafte Implementierung eines PHP-basierten Hublify-Clients.
/**
* Class hublifyConnector ( DEMO CLASS ! )
*
* An easy to use class to call the hublify api to read or write data.
*
* This simple class uses only CURL-functions. It has no other other dependencies.
*
*/
class hublifyConnector {
/**
* @var string The url of your hublify-server, including the base path to api-resource.
* Example: "https://xyz.hublify.io/api/"
*/
protected $api_url = null;
/**
* @var string The required api-version addressed on the hublify-server.
* Leave this untouched. You actually will not have to change this, at all.
* Default: "eos_10"
*/
protected $api_version = 'eos_10';
/**
* @var string The username with which you want to connect to the hublify-server.
* Example: "foo.bar"
*/
protected $api_user = null;
/**
* @var string The dynamically acquired session-id-token provided from the hublify-server.
* We'll get this once we init the api-session and store it here for all further api-calls.
* As long as this hublifyConnector-instance lives.
*/
protected $api_sessId = null;
/**
* hublifyConnector constructor.
*
* Automatically initializes an api session.
*
* @param $url string The url of your hublify-server, including the base path to api-resource.
* Example: "https://xyz.hublify.io/api/"
*
* @param $username string The hublify-username with which you want to connect to the hublify-server.
* Example: "foo.bar"
*
* @param $userpwd string The password of that hublify-username.
* This ist not stored anywhere in this instance.
*/
function __construct($url, $username, $userpwd) {
$this->initSession($url, $username, $userpwd);
}
/**
* Init the api-session
*
* This is usually called only once and directly in the beginning of this instance's lifecycle.
*
* We will connect and login to the api with username and password and in case of success we will
* receive a api-session-id in return. This will be stored internally and needs to be used on all
* further api-calls for authentication.
*
* @param $url string The url of your hublify-server, including the base path to api-resource.
* Example: "https://xyz.hublify.io/api/"
*
* @param $username string The hublify-username with which you want to connect to the hublify-server.
* Example: "foo.bar"
*
* @param $userpwd string The password of that hublify-username.
* This ist not stored anywhere in this instance.
*
* @return bool Returns TRUE on login-success, else FALSE.
*/
public function initSession($url, $username, $userpwd) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url.'login');
$d = json_encode(array('username' => $username, 'userpwd' => $userpwd));
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $d);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$loginR = json_decode(curl_exec($ch),true);
curl_close($ch);
if(isset($loginR['data']['sessid'])) {
$this->api_sessId = $loginR['data']['sessid'];
$this->api_url = $url;
$this->api_username = $url;
return true;
} else {
$this->api_sessId = null;
echo "ERROR connecting to api: ".$url;
}
return false;
}
/**
* Calls an api-resource
*
* You need to have a valid API-Session instantiated...
*
* @param $function string The api-resource you want to call.
* Example: "product_getlist".
*
* @param $params array Optional parameters for the called function.
* Which parameters are possible or required depends on the function you call.
*
* @param $stream bool Optional. Set true, if you expect a stream instead of json as a result
*
* @return array|null
*/
public function call($function, $params = null, $stream = false)
{
if(strlen($this->api_url)>0 && strlen($this->api_sessId)>0) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->api_url . $this->api_version . '/' . $function);
curl_setopt($ch, CURLOPT_HTTPHEADER, array( "API-SessID: " . $this->api_sessId ));
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if (!is_null($params)) {
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
}
$response = curl_exec($ch);
curl_close($ch);
if ($stream == true) {
$r = $response;
} else {
$r = json_decode($response, true);
}
if (!is_null($r)) {
return ($r);
} else {
echo "CALL error.";
print_r($response);
}
} else {
echo "CALL error. No API-url and/or -sessId set.";
}
return null;
}
/**
* Upload a file to an endpoint that accepts file uploads.
*
* @param string $function The API function to call, e.g. "mam_asset_upload".
* @param string $filePath Absolute or relative path to the file on disk.
* @param array|null $params Additional params
*
* @return array|null Decoded JSON response, or null on error.
*/
public function upload(string $function, string $filePath, array $params = null)
{
if (!file_exists($filePath)) {
echo "File not found: {$filePath}\n";
return null;
}
if (empty($this->api_url) || empty($this->api_sessId)) {
echo "CALL error. No API-url and/or -sessId set.\n";
return null;
}
// Try to detect mime
$mime = 'application/octet-stream';
if (function_exists('finfo_open')) {
$fInfo = finfo_open(FILEINFO_MIME_TYPE);
$detected = finfo_file($fInfo, $filePath);
if ($detected) { $mime = $detected; }
finfo_close($fInfo);
}
// Use the provided filename or derive from a path
$filename = $params['filename'] ?? basename($filePath);
// Prepare multipart form fields
$postFields = [
// "file" field name is typical; adjust if your API expects a different key.
'file' => new CURLFile($filePath, $mime, $filename),
'filename' => $filename, // Include the filename in the params
'filetype' => $mime, // Include the detected mime type
];
// Pass additional parameters if provided
if (is_array($params)) {
foreach ($params as $key => $value) {
if ($key !== 'filename') { // Avoid overwriting the filename
if (is_array($value) || is_object($value)) {
$postFields[$key] = json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
} else {
$postFields[$key] = $value;
}
}
}
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->api_url . $this->api_version . '/' . $function);
// Auth header (keep, as in the default call method)
curl_setopt($ch, CURLOPT_HTTPHEADER, [ "API-SessID: " . $this->api_sessId ]);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields); // multipart/form-data will be set automatically
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// (Optional but recommended for large files)
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_TIMEOUT, 0); // 0 = no limit; or set a high value like 600
$response = curl_exec($ch);
if ($response === false) {
$err = curl_error($ch);
curl_close($ch);
echo "cURL error: {$err}\n";
return null;
}
curl_close($ch);
$decoded = json_decode($response, true);
if (is_array($decoded)) {
return $decoded;
}
// Fallback: return raw-response if JSON decoding failed
return ['raw' => $response];
}
}
Beispiel Call
Folgendes Beispiel benutzt die hublifyConnector Class, um eine Produktliste abzurufen.
index.php
/**
* C a l l i n g t h e H u b l i f y A P I
*
* Using the "hublifyConnector"-class
*/
require_once ('hublifyconnector.class.php');
// Provide your Hublify-server and -credentials
$hublifySrvUrl = 'https://{your-hublify-url}/api/';
$hublifyUserName = '<your username>';
$hublifyPwd = '<your pwd>';
// Create hublify-api-connector (and init connection):
$hublify = new hublifyConnector($hublifySrvUrl, $hublifyUserName, $hublifyPwd);
// Call api: "product list"
$r = $hublify->call(
'product_getlist',
[
"fields"=> [ "name","pcode" ],
'sql' => [ 'limit' => [ 'max' => 3]]]
);
print_r($r);
Ausgabe
Array
(
[0] => Array
(
[pcode] => GX00009
[name] => T-Shirt Skywalker
)
[1] => Array
(
[pcode] => SW00123
[name] => Laserschwert "Vader"
)
[2] => Array
(
[pcode] => SW00124
[name] => Yoda Cape XXS
)
)
Beispiel Upload
Folgendes Beispiel benutzt die hublifyConnector Class, um ein Bild im MAM zu speichern.
index.php
/** * C a l l i n g t h e H u b l i f y A P I * * Using the "hublifyConnector"-class */ require_once ('hublifyconnector.class.php'); // Provide your Hublify-server and -credentials $hublifySrvUrl = 'https://{your-hublify-url}/api/'; $hublifyUserName = '<your username>'; $hublifyPwd = '<your pwd>';
// Create hublify-api-connector (and init connection): $hublify = new hublifyConnector($hublifySrvUrl, $hublifyUserName, $hublifyPwd); // Call api: "mam asset upload"
$filePath = '<path-to-your-file>/example.png'; $r = $hublify->upload('mam_asset_upload', $filePath, [ "filter" => [ "dirname" => "upload-dir" ], ] ); print_r($r);
Ausgabe
Array
(
[status] => 1
[msg] => Array
(
[0] => Array
(
[type] => OK
[i18n] => Array
(
[string] => em_filesystem.files_uploaded
[params] =>
)
)
)
[data] => Array
(
[file] => Array
(
[0] => Array
(
[data] => Array
(
[mb_id] => 12345
[mb_label] => examplepng
[mb_path] => /upload-dir/example.png
[dirname] => /upload-dir/
[name] => example.png
[mb_extension] => png
[mb_preview] => /upload-dir/.hfy-preview/example.png___thumb.webp
[url] => /files/upload-dir/example.png
[link] => https://{your-hublify-url}/files/upload-dir/example.png
[ref_id] => mam_default::||upload-dir|example.png
... shortened for brevity ...
)
[status] => 1
[meta] =>
[sql] => Array
(
[limit] => 1
[having] =>
[group] => em_mam.mb_id
)
)
)
)
)