WBKNLWBKNL MemberComments: 3 Received thanks: 0 Member since: January 23

I'm adding products through the Admin API but I can't find anything on how to add product images. Can anybody explain to me how I can add product images through the api?

Answers

  • oliverriskeoliverriske MemberComments: 66 Received thanks: 13 Member since: November 2019

    Folgende Reihenfolge:

    1. Post um eine MediaID zu erhalten

    2. Post um Bild hochzuladen

    3. 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;
                    }
     

    Thanked by 1WBKNL
  • WBKNLWBKNL MemberComments: 3 Received thanks: 0 Member since: January 23

    Where is this from, a package? I'm not working from Shopware or any other existing software but I'm building my own middleware.

  • oliverriskeoliverriske MemberComments: 66 Received thanks: 13 Member since: November 2019

    My code 

    php with guzzle http 

    rest is on you

  • WBKNLWBKNL MemberComments: 3 Received thanks: 0 Member since: January 23

    Thanks for the code but I'm trying to understand how the api works. Can I upload an image or do I have to give it a url? Is there any documentation on this?

    Apart from the uploading, if I understand it correctly:

    1. I make a post to /media (createMedia) to create a new Media Resource
    2. Somehow get the image to Shopware
    3. Update the Product and give it the media ID
  • oliverriskeoliverriske MemberComments: 66 Received thanks: 13 Member since: November 2019

    Look at the code everything is there

    Step 2:

    $url = $this->baseUrl . '/api/v1/_action/media/' . $mediaId . '/upload?extension=' . $image[1] . '&fileName=' . $image[0];
                        $response = $this->postData($url, $data);

     

  • na15fabiankoenigna15fabiankoenig MemberComments: 1 Received thanks: 0 Member since: March 16

    @oliverriske‍ Could you write me your variables, which you are using in your code?

    $this->cacheMediaFolder
    $this->productMediaFolder
    $this->apiEndpoints
    $this->baseUrl
    $this->log
Sign In or Register to comment.