【问题标题】:How to update woocommerce product via api with Symfony and Guzzle如何使用 Symfony 和 Guzzle 通过 api 更新 woocommerce 产品
【发布时间】:2021-11-18 19:27:26
【问题描述】:

问题:如何使用 Guzzle 和 guzzle/oauth-subscriber 通过 API 更新 woocommerce 产品的价格

我使用This Question 作为我的参考来让 oauth1 工作以请求数据,效果很好。只是无法锻炼以发送帖子变量。

大多数教程和 guzzle 文档都使用 $client->request('GET', 'http://httpbin.org', [ 'query' => ['foo' => 'bar'] ]);,但这也不起作用:

        $response = $client->request('POST', $endpoint, [
            'auth' => 'oauth',
            'form_params' => [
                'price' => '21'
            ]
        ]);

这是我当前的代码,get $client->get() 注释掉了成功返回产品的内容。

        $endpoint = 'products/12';

        $handler = new \GuzzleHttp\Handler\CurlHandler();
        $stack = \GuzzleHttp\HandlerStack::create($handler);

        $middleware = new \GuzzleHttp\Subscriber\Oauth\Oauth1([
            'consumer_key'    => $this->consumer_key,
            'consumer_secret' => $this->consumer_secret,
            'token_secret'    => '',
            'token'           => '',
            'request_method' => Oauth1::REQUEST_METHOD_QUERY,
            'signature_method' => Oauth1::SIGNATURE_METHOD_HMAC
        ]);
        $stack->push($middleware);

        $client = new \GuzzleHttp\Client([
            'base_uri' => $this->url . $this->api,
            'handler' => $stack
        ]);

        $response = $client->post( $endpoint, [ 'auth' => 'oauth' ], ['price' => '21'] );

        var_dump($response);

        //$response = $client->get( $endpoint, [ 'auth' => 'oauth' ] );
        //return array(
        //  'status' => $response->getStatusCode(),
        //  'header' => $response->getHeaderLine('content-type'),
        //  'body' => json_decode($response->getBody())
        //);

【问题讨论】:

  • 您正在发送POST 请求,您应该发送PUT 请求。 POST 表示“创建”,PUT 表示“更新”。

标签: php symfony woocommerce guzzle woocommerce-rest-api


【解决方案1】:

我的代码存在三个问题:

  1. 使用 POST 进行更新,而不是 PUT。如前所述,POST 是创建,而不是更新。

  2. 阅读Woocommerce docs 我发现“价格”是只读的,所以我尝试的参数组合都不起作用。 regular_price 是此处使用的正确参数。

  3. 我传递给$client-> 的选项都不起作用,它必须是一个查询字符串。我将其附加到 $endpoint 变量中。

$endpoint .= "?stock_quantity=456";
$response = $client->put( $endpoint, [ 'auth' => 'oauth' ] );

【讨论】:

    猜你喜欢
    • 2018-04-22
    • 2021-07-01
    • 2018-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-22
    相关资源
    最近更新 更多