【问题标题】:Unable to delete product from commercetools api无法从 commercetools api 中删除产品
【发布时间】:2017-08-04 08:07:39
【问题描述】:

我正在尝试通过 HTTP 请求从商业工具 API 中删除。

以下是我的代码:

$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);

来自服务器的响应:

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

我在参数中发送版本号,但仍然出现错误。接下来我可以尝试什么?

【问题讨论】:

    标签: php curl http-delete commercetools


    【解决方案1】:

    我的第一个建议是使用商务工具 PHP SDK。在这里找到 https://github.com/commercetools/commercetools-php-sdk 或使用 Composer 时 https://packagist.org/packages/commercetools/php-sdk

    使用 SDK 删除产品如下所示:

    <?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);
    

    如果您真的想坚持直接与 API 对话,您必须按照http://dev.commercetools.com/http-api-projects-products.html#delete-product-by-id 的文档中所述将版本作为查询参数发送。因此,您示例中的 URL 将是:

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

    【讨论】:

    • 我不想使用任何SDK,使用http api我必须这样做。
    • 那么这就是要走的路:$url = 'api.sphere.io/test/products/xxxx?version=1'; $curl = curl_init($url); 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);
    猜你喜欢
    • 1970-01-01
    • 2020-12-25
    • 1970-01-01
    • 2021-10-07
    • 1970-01-01
    • 1970-01-01
    • 2021-08-08
    • 2018-04-03
    • 2020-04-28
    相关资源
    最近更新 更多