repost: php w/c api, simple http request using guzzle

composer require guzzlehttp/guzzle
woocommerce api
<?php
require_once "vendor/autoload.php";
 
use GuzzleHttp\Client;
 
define('WC_CONSUMER_KEY', 'PASTE_CONSUMER_KEY_HERE');
define('WC_CONSUMER_SECRET', 'PASTE_CONSUMER_SECRET_HERE');
 
$client = new Client([
  'base_uri' => 'YOUR_DOMAIN_BASE_URL',
]);
 
try {
  $response = $client->request('GET', '/wp-json/wc/v3/products/PRODUCT_ID_HERE', [
  'headers' => [
         "Authorization" => "Basic ". base64_encode(WC_CONSUMER_KEY.':'.WC_CONSUMER_SECRET)
   ],
   'verify' => false, //only needed if you are facing SSL certificate issue
]);
 
$body = $response->getBody();
$arr_body = json_decode($body);
 
$response = $client->request('GET', '/wp-json/wc/v3/products', [
      'headers' => [
            "Authorization" => "Basic ". base64_encode(WC_CONSUMER_KEY.':'.WC_CONSUMER_SECRET)
       ],
        'query' => [ 'include' => $arr_body->related_ids, ],
            'verify' => false,
]);
 
$body = $response->getBody();
$arr_products = json_decode($body);
 
   if (!empty($arr_products)) {
      foreach ($arr_products as $product) {
?>
  <p>
    <a href="<?php echo $product->permalink; ?>"><?php echo $product->name; ?></a>
  </p>
<?php
      }
  }  
} catch (Exception $e) {
echo $e->getMessage();
}

If you use Laravel and prefer not to reinvent the wheel, this lib is pretty good too: GitHub – Codexshaper/laravel-woocommerce: WooCommerce Rest API for Laravel


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *