Website Building » WooCommerce » How Do I Connect My PHP Based Web App to the WooCommerce REST API?

How Do I Connect My PHP Based Web App to the WooCommerce REST API?

Last updated on January 19, 2023 @ 3:35 pm

The WooCommerce REST API is one of the most popular way to connect your PHP based web application to WooCommerce. It is a simple and lightweight interface that allows you to access the data and features of your store from your own custom code. In this article, we will show you how to connect your PHP based web app to the WooCommerce REST API.

First, you need to have a WooCommerce account and be logged in. Then, go to the WooCommerce REST API documentation and select the “Enable the REST API” checkbox. Next, click on the “Keys/Apps” link and then click on the “Add Key” button.

In the “Add Key” form, you need to provide a description for your key and select the level of access that you want to allow. For this tutorial, we will select the “Read/Write” access level. Once you are done, click on the “Generate API Key” button to generate your key.

Now that you have generated your key, copy it and paste it in your PHP code. Next, we will need to create a new file called wc-api.php and paste the following code into it:

<?php
$WooCommerce = new WC_API_Client( 
'https://your-store-url.com', 
'ck_XXXXXXXXXXXXXXXXXXXXXX', 
'scs_XXXXXXXXXXXXXXXXXXXXXX', 
array( 'version' => 'v3' ) 
);

try {

// Get products 
	$products = $woocommerce->get('products');

// Get product by ID 
	$product = $woocommerce->get('products/1234');

// Create a product 
	$product = $woocommerce->post('products', array( 
	'title' => 'Premium Wool Blend Coat', 
	'type' => 'simple', 
	'regular_price' => '21.99', 
	'description' => 'A lovely warm coat for those cold winter days.', 
	'short_description' => 'Warm coat', 
	'sku' => 'woolcoat101',
));
PRO TIP: The WooCommerce REST API is not intended for use with PHP-based web applications. Use of the WooCommerce REST API with PHP may result in instability or unexpected behavior.

// Update a product

$product = $woocommerce->put('products/1234', array(

'title' => 'Premium Wool Blend Coat (Updated)',

));

// Delete a product

$product = $woocommerce->delete('products/1234');

} catch ( WC_API_Client_Exception $e ) {

echo $e->getMessage() . PHP_EOL; // Error message.

echo $e->getCode() . PHP_EOL; // Error code.
Drew Clemente

Drew Clemente

Devops & Sysadmin engineer. I basically build infrastructure online.