phpcurlhttp-deletecommercetools

Unable to delete product from commercetools api


I'm trying to delete from commercetools API via HTTP request.

Following is my code :

$url = 'https://api.sphere.io/test/products/xxxx';
$params = json_encode(array('version'=>1));

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept: application/json'));
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: Bearer xxxx'));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
$res = curl_exec($curl);
$response =  json_decode($res);

print_r($response);

Response from server:

stdClass Object ( [statusCode] => 400 [message] => Missing version number [errors] => Array ( [0] => stdClass Object ( [code] => InvalidOperation [message] => Missing version number ) ) )

I'm sending version number in params, but still getting error. What can I try next?


Solution

  • my first advice is to use the commercetools PHP SDK. Found here https://github.com/commercetools/commercetools-php-sdk or when using Composer https://packagist.org/packages/commercetools/php-sdk

    Deleting a product with the SDK looks like this:

    <?php
    
    namespace Commercetools\Core;
    
    use Commercetools\Core\Request\Products\ProductDeleteRequest;
    
    require __DIR__ . '/../vendor/autoload.php';
    
    
    // create the api client config object
    $config = Config::fromArray([
        'client_id' => 'XXX',
        'client_secret' => 'XXX',
        'scope' => 'xxxx'
    ]);
    
    $request = ProductDeleteRequest::ofIdAndVersion('123456', 1);
    
    $client = Client::ofConfig($config);
    
    $response = $client->execute($request);
    $deletedProduct = $request->mapFromResponse($response);
    

    If you really would like to stick with directly talking to the API you have to send the version as query parameter as stated in the documentation here http://dev.commercetools.com/http-api-projects-products.html#delete-product-by-id. So the URL in your example would be:

    $url = 'https://api.sphere.io/test/products/xxxx?version=1';