-3

Question: How to update the price of a woocommerce product via API using Guzzle and guzzle/oauth-subscriber

I've used This Question as my reference to get oauth1 working for requesting data, which works well. Just haven't been able to workout out to send post variables.

Most tutorials and the guzzle docs use the $client->request('GET', 'http://httpbin.org', [ 'query' => ['foo' => 'bar'] ]); but that isn't working either:

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

This is my current code, with the get $client->get() commented out what successfully returns a product.

        $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())
        //);
Vega
  • 27,856
  • 27
  • 95
  • 103
Bradmage
  • 1,233
  • 1
  • 15
  • 41
  • You are sending a `POST` request, you should be sending a `PUT` request. `POST` means "create", `PUT` means "update". – yivi Sep 26 '21 at 12:02

1 Answers1

0

There were three issues with my code:

  1. Using POST to update, not PUT. As stated POST is to create, not update.

  2. Reading Woocommerce docs I found that 'price' is read only, so no combination of parameters I was trying were going to work. regular_price is the correct parameter to use here.

  3. None of the options I was passing to $client-> were working, it needs to be a query string. Which I appended to the $endpoint variable.

$endpoint .= "?stock_quantity=456";
$response = $client->put( $endpoint, [ 'auth' => 'oauth' ] );
Bradmage
  • 1,233
  • 1
  • 15
  • 41