Folgende Reihenfolge:
-
Post um eine MediaID zu erhalten
-
Post um Bild hochzuladen
-
Bei Product Post MediaID und ggf. CoverID in den payload aufnehmen
public function uploadProductImage($imageUrl, $imageName)
{
try {
$this->log->info(„Connector/Shopware->uploadProductImage: " . $imageName);
$mediaId = null;
if ($this->cacheMediaFolder[$this->productMediaFolder][„id“]) {
$data = [„mediaFolderId“ => $this->cacheMediaFolder[$this->productMediaFolder][„id“]];
$url = $this->baseUrl . $this->apiEndpoints[‚media‘];
$response = $this->postData($url, $data);
$mediaId = $response->id;
if ($mediaId) {
$data = [
„url“ => $imageUrl,
];
$image = explode(“.", $imageName);
$url = $this->baseUrl . ‚/api/v1/_action/media/‘ . $mediaId . ‚/upload?extension=‘ . $image[1] . ‚&fileName=‘ . $image[0];
$response = $this->postData($url, $data);
if (!$response) {
$this->log->error(
new \Exception(„Upload Error try to delete MediaID: " . $mediaId . " for: " . $imageUrl)
);
$url = $this->baseUrl . $this->apiEndpoints[‚media‘];
$this->deleteData($url, $mediaId);
}
}
}
} catch (\Exception $exception) {
$this->log->error($exception);
}
}
public function postData($url, $data, $returnResponse = true)
{
try {
if ($returnResponse) {
if (strpos($url, „?“) === false) {
$url = $url . „?_response=true“;
} else {
$url = $url . „&_response=true“;
}
}
$token = $this->getToken();
$client = $this->getClient();
$response = $client->request(
‚POST‘,
$url,
[
‚headers‘ => [
‚Content-Type‘ => ‚application/json‘,
‚charset‘ => ‚utf-8‘,
‚Accept‘ => ‚application/json‘,
‚Authorization‘ => 'Bearer ’ . $token,
],
‚body‘ => json_encode($data),
]
);
if ($returnResponse) {
$data = json_decode($response->getBody()->getContents());
if (!$data) {
$location = $response->getHeader(„Location“)[0];
$id = explode(“/", $location);
$id = $id[sizeof($id) - 1];
return (object)[‚id‘ => $id];
}
return $data->data;
} else {
$location = $response->getHeader(„Location“)[0];
$id = explode("/", $location);
$id = $id[sizeof($id) - 1];
return $id;
}
} catch (\Exception $exception) {
$this->log->error($exception);
return null;
}
}
Product Payload:
$data = [
„active“ => true,
„isCloseout“ => true,
„taxId“ => $tax[„id“],
„productNumber“ => $product[‚identifier‘],
„name“ => $values[‚name‘][0][‚data‘],
„description“ => $values[‚beschreibung‘][0][‚data‘],
];
$data[‚media‘] = ;
foreach ($productImages as $index => $productImage) {
$dataImage = [
„mediaId“ => $productImage[‚id‘],
„position“ => $index,
];
if ($index == 0) {
$data[‚coverId‘] = md5($product[„identifier“] . $productImage[‚id‘], false);
$dataImage[„id“] = $data[‚coverId‘];
}
$data[‚media‘] = $dataImage;
}