catalogProductAttributeMediaCreate() Exception: Product Does Not Exist – Magento 1 Fix

importsoap

I'm uploading images to my Magento server using the v2 SOAP web services.

My PHP code is:

// Session and other stuff...
//

$file = fopen ( "magento_art.txt" , "r" );
$data = fgetcsv ( $file , 2048, "$", "\\");

while (( $data = fgets ( $file , 2048)) !== false) {

    $data = str_replace('ยบ', '&deg', $data);
    $data = str_replace('"', '', $data);
    $data = str_getcsv( $data, "$");

    $path= 'fotos/'.$data[14];
    $type = pathinfo($path, PATHINFO_EXTENSION);
    $raw_image = file_get_contents($path);
    $base64 = base64_encode($raw_image);
    $image = array(
        'content' => $base64,
        'mime' => 'image/jpeg'
    );

    var_dump($image);
    echo "\n\n";

    try{
        print_r("SKU: ".$data[1]."\n\n");
        $result = $client->catalogProductAttributeMediaCreate(
            $session,
            (string)$data[1],
            array('file' => $image, 'label' => 'image', 'position' => '100', 'types' => ['image'], 'exclude' => 0)
        );
    }

    catch(Exception $e){
        echo "Exception: ".$e->getMessage()."\n\n";
    }

And every single time I get the exception 'product not exists'. I've checked myself that the product exists in my server and the SKU code is the same in my PHP script and in my server, but the API method is not working.

What can it be? I've tried also 'hard coding' a SKU of one of my products and that didn't work either.

Best Answer

If you are sure that your product exists could it be that you do want to pass a numeric SKU (e.g. 1234)?

If you cast the product ID/SKU to a string, it looks like a number and you don't declare the identifierType "sku", the product identifier will be treated like a ID and so the product won't be found.

The solution: after the data array, add a store parameter (as the fourth parameter) and "sku" as the fifth parameter.

You can find more information in the documentation:

Arguments:
Type    Name            Description
string  sessionId       Session ID
string  product         Product ID or code
array   data            Array of catalogProductAttributeMediaCreateEntity
string  storeView       Store view ID or code (optional)
string  identifierType  Defines whether the product ID or SKU is passed in the 'product' parameter 

Btw, the method responsible for this behaviour is Mage_Catalog_Helper_Product::getProduct().