Giter Site home page Giter Site logo

wc-api-php's Introduction

WooCommerce API - PHP Client

A PHP wrapper for the WooCommerce REST API. Easily interact with the WooCommerce REST API securely using this library. If using a HTTPS connection this library uses BasicAuth, else it uses Oauth to provide a secure connection to WooCommerce.

CI status Scrutinizer Code Quality PHP version

Installation

composer require automattic/woocommerce

Getting started

Generate API credentials (Consumer Key & Consumer Secret) following this instructions http://docs.woocommerce.com/document/woocommerce-rest-api/ .

Check out the WooCommerce API endpoints and data that can be manipulated in https://woocommerce.github.io/woocommerce-rest-api-docs/.

Setup

Setup for the new WP REST API integration (WooCommerce 2.6 or later):

require __DIR__ . '/vendor/autoload.php';

use Automattic\WooCommerce\Client;

$woocommerce = new Client(
  'http://example.com',
  'ck_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
  'cs_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
  [
    'version' => 'wc/v3',
  ]
);

Client class

$woocommerce = new Client($url, $consumer_key, $consumer_secret, $options);

Options

Option Type Required Description
url string yes Your Store URL, example: http://woo.dev/
consumer_key string yes Your API consumer key
consumer_secret string yes Your API consumer secret
options array no Extra arguments (see client options table)

Client options

Option Type Required Description
version string no API version, default is wc/v3
timeout int no Request timeout, default is 15
verify_ssl bool no Verify SSL when connect, use this option as false when need to test with self-signed certificates, default is true
follow_redirects bool no Allow the API call to follow redirects
query_string_auth bool no Force Basic Authentication as query string when true and using under HTTPS, default is false
oauth_timestamp string no Custom oAuth timestamp, default is time()
oauth_only bool no Only use oauth for requests, it will disable Basic Auth, default is false
user_agent string no Custom user-agent, default is WooCommerce API Client-PHP
wp_api_prefix string no Custom WP REST API URL prefix, used to support custom prefixes created with the rest_url_prefix filter
wp_api bool no Set to false in order to use the legacy WooCommerce REST API (deprecated and not recommended)
method_override_query bool no If true will mask all non-GET/POST methods by using POST method with added query parameter ?_method=METHOD into URL
method_override_header bool no If true will mask all non-GET/POST methods (PUT/DELETE/etc.) by using POST method with added X-HTTP-Method-Override: METHOD HTTP header into request

Client methods

GET

$woocommerce->get($endpoint, $parameters = []);

POST

$woocommerce->post($endpoint, $data);

PUT

$woocommerce->put($endpoint, $data);

DELETE

$woocommerce->delete($endpoint, $parameters = []);

OPTIONS

$woocommerce->options($endpoint);

Arguments

Params Type Description
endpoint string WooCommerce API endpoint, example: customers or order/12
data array Only for POST and PUT, data that will be converted to JSON
parameters array Only for GET and DELETE, request query string

Response

All methods will return arrays on success or throwing HttpClientException errors on failure.

use Automattic\WooCommerce\HttpClient\HttpClientException;

try {
  // Array of response results.
  $results = $woocommerce->get('customers');
  // Example: ['customers' => [[ 'id' => 8, 'created_at' => '2015-05-06T17:43:51Z', 'email' => ...
  echo '<pre><code>' . print_r($results, true) . '</code><pre>'; // JSON output.

  // Last request data.
  $lastRequest = $woocommerce->http->getRequest();
  echo '<pre><code>' . print_r($lastRequest->getUrl(), true) . '</code><pre>'; // Requested URL (string).
  echo '<pre><code>' .
    print_r($lastRequest->getMethod(), true) .
    '</code><pre>'; // Request method (string).
  echo '<pre><code>' .
    print_r($lastRequest->getParameters(), true) .
    '</code><pre>'; // Request parameters (array).
  echo '<pre><code>' .
    print_r($lastRequest->getHeaders(), true) .
    '</code><pre>'; // Request headers (array).
  echo '<pre><code>' . print_r($lastRequest->getBody(), true) . '</code><pre>'; // Request body (JSON).

  // Last response data.
  $lastResponse = $woocommerce->http->getResponse();
  echo '<pre><code>' . print_r($lastResponse->getCode(), true) . '</code><pre>'; // Response code (int).
  echo '<pre><code>' .
    print_r($lastResponse->getHeaders(), true) .
    '</code><pre>'; // Response headers (array).
  echo '<pre><code>' . print_r($lastResponse->getBody(), true) . '</code><pre>'; // Response body (JSON).
} catch (HttpClientException $e) {
  echo '<pre><code>' . print_r($e->getMessage(), true) . '</code><pre>'; // Error message.
  echo '<pre><code>' . print_r($e->getRequest(), true) . '</code><pre>'; // Last request data.
  echo '<pre><code>' . print_r($e->getResponse(), true) . '</code><pre>'; // Last response data.
}

Release History

  • 2022-03-18 - 3.1.0 - Added new options to support _method and X-HTTP-Method-Override from WP, supports 7+, dropped support to PHP 5.
  • 2019-01-16 - 3.0.0 - Legacy API turned off by default, and improved JSON error handler.
  • 2018-03-29 - 2.0.1 - Fixed fatal errors on lookForErrors.
  • 2018-01-12 - 2.0.0 - Responses changes from arrays to stdClass objects. Added follow_redirects option.
  • 2017-06-06 - 1.3.0 - Remove BOM before decoding and added support for multi-dimensional arrays for oAuth1.0a.
  • 2017-03-15 - 1.2.0 - Added user_agent option.
  • 2016-12-14 - 1.1.4 - Fixed WordPress 4.7 compatibility.
  • 2016-10-26 - 1.1.3 - Allow set oauth_timestamp and improved how is handled the response headers.
  • 2016-09-30 - 1.1.2 - Added wp_api_prefix option to allow custom WP REST API URL prefix.
  • 2016-05-10 - 1.1.1 - Fixed oAuth and error handler for WP REST API.
  • 2016-05-09 - 1.1.0 - Added support for WP REST API, added method Automattic\WooCommerce\Client::options and fixed multiple headers responses.
  • 2016-01-25 - 1.0.2 - Fixed an error when getting data containing non-latin characters.
  • 2016-01-21 - 1.0.1 - Sort all oAuth parameters before build request URLs.
  • 2016-01-11 - 1.0.0 - Stable release.

wc-api-php's People

Contributors

bkuhl avatar bryceadams avatar chizdrel avatar claudiosanches avatar cristiangrama avatar fastdivision avatar gugglegum avatar mrohnstock avatar nicolasb827 avatar redelschaap avatar simoor avatar vishalkakadiya avatar westi avatar wiesys avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

wc-api-php's Issues

Client call returns [rest_no_route]

Hi,
my WordPress version is 4.5.2 with WooCommerce version 2.5.5 and I'm trying to make a call to the Rest API. I have installed and enabled the WordPress REST API (Version 2) and generated API Key for WooCommerce.

$woocommerce = new Client(
    'http://wp-rest-api.dev', // it's a local domain
    '...1235bd6', // consumer key
    '...ecb6412', // consumer secret
    [
        'wp_api' => true, // Enable the WP REST API integration
        'version' => 'wc/v1' // WooCommerce WP REST API version
    ]
);

and when I try to call an API endpoint, eg. products

$woocommerce->get('products');

I'm getting Error: No route was found matching the URL and request method [rest_no_route]

Can someone please point me on to the right direction.

Placing order for a specific customer

i'm building a mobile application to use with woocommerce, and my app should keep track of all the previous orders of the WP user (using the user id)
was reading the documentation and found that when we create an order we don't specify the customer_id or the WP_USER the only related field is the email

so my question is:
1- Woo.customer = WP.user (wp_user.id = woo commerce customer_id) ?
2- is it enaugh to specify the email of the WP user so that the order is created for this specific user ?

Thanks

Is there a problem with products route?

Hi!
Is there a problem with products route?
I have tested : orders, customers, coupons , products/categories and all of them have a responses.
But when i try return Woocommerce::get('products'); terminate the connection and i am getting a
No data received

ERR_EMPTY_RESPONSE

Thanks

Very nice job

Woocommerce Rest Api Syntax Error

Fatal error: Uncaught exception 'Automattic\WooCommerce\HttpClient\HttpClientException' with message 'Syntax error' in /home/u732858947/public_html/woo-api/vendor/automattic/woocommerce/src/WooCommerce/HttpClient/HttpClient.php:331

Here is my code calling...

true, 'version' => 'wc/v1' ] ); print_r($woocommerce->get('products')); ?>

Please help ?

Cannot filter product by category

It seems we cannot filter product by category. I sent the category id as a second parameter as an array but it doesn't work. And your DOC isn't clear about that.

Creating product with categories returns an error "Invalid JSON returned"

WC v2.5.5
API v3

I have a problem creating a new product with categories.
I am using the example from the API docs as follows:

$data = [
    'product' => [
        'title' => 'Premium Quality',
        'type' => 'simple',
        'regular_price' => '21.99',
        'description' => 'Pellentesque',
        'short_description' => 'Pellentesque habitant',
        'categories' => [
            64,
            193
        ]
    ]
];

print_r($woocommerce->post('products', $data));

The given categories ids exists, and still I get an error.
The weird thing is that the product gets created even though an exception is thrown.

The error:

Automattic\WooCommerce\HttpClient\HttpClientException: Invalid JSON returned in /Users/daniel/Sites/outsiders/wp-content/themes/outsiders-theme/lib/vendor/automattic/woocommerce/src/WooCommerce/HttpClient/HttpClient.php on line 303

When I try to create the product without the categories array, it works fine.
After trying all sorts of manipulations, I realized there is a problem to pass an array inside the $data variable.
Because when I tried adding the images array, it also threw an exception, but still created the product with the images.
I also tried an empty categories array, empty images array etc, and whenever I pass an array, the exception is thrown...

Any idea??

Use without composer

Sorry for the noobish question, but how do I use this library without the use of composer?

I'm trying:

require_once(__DIR__.'/WooCommerce/Client.php');

// WC
$woocommerce = new Client(
    'https://xxx', 
    'xxx', 
    'xxx',
    [
        'wp_api' => true,
        'version' => 'wc/v1',
    ]
);

print_r($woocommerce->get(''));

But this results in Fatal error: Class 'Client' not found in ...

Product is not posted on second API

Hello,
I have 2 websites and installed woocommerce on both websites. I have API keys of both the websites. The thing I want to do is when I get particular product details on the first website, the returned data should post on the another website. For example,

$site_main = new Client(
    'https://abc.biz/', 
    'ck_zbc', 
    'cs_zbc',
     [
        'version' => 'v3',
        'ssl_verify'=> 'false'
    ]

);

 $get_result = $site_main ->get('products/17640');

$site_another= new Client(
    'https://xyz.com/', 
    'ck_123', 
    'cs_456',
     [
        'version' => 'v3',
        'ssl_verify'=> 'false'
    ]
);

$site_another->post('products',$get_result);

So, Get data from one API and post into another one. Well, this do not create product on second website. It's keep saying that :

Undefined offset: 1 in /var/www/html/autosync/vendor/automattic/woocommerce/src/WooCommerce/HttpClient/HttpClient.php on line 242

I'm not asking for support but help. I have tried it many times and then decided to post here.

Thank you!

Woocommerce Rest Api Fatal Error Getting Issue

I have following errors :-

Fatal error: Uncaught exception 'Automattic\WooCommerce\HttpClient\HttpClientException' with message 'cURL Error: Failed to connect to sachinbasendra.com port 443: Connection refused' in /home/u732858947/public_html/app/vendor/automattic/woocommerce/src/WooCommerce/HttpClient/HttpClient.php:365 Stack trace: #0 /home/u732858947/public_html/app/vendor/automattic/woocommerce/src/WooCommerce/Client.php(82): Automattic\WooCommerce\HttpClient\HttpClient->request('products', 'GET', Array, Array) #1 /home/u732858947/public_html/app/api.php(16): Automattic\WooCommerce\Client->get('products') #2 {main} thrown in /home/u732858947/public_html/app/vendor/automattic/woocommerce/src/WooCommerce/HttpClient/HttpClient.php on line 365

please help me thanks in advanced

problem with https://

Hello,

i have problem with your API client. I trying to get products from my address with https:// but i got error: Error: Consumer Secret is invalid [woocommerce_api_authentication_error].

EDITED:

in oficial website http://woothemes.github.io/woocommerce-rest-api-docs/#authentication i found this:

"Occasionally some servers may not parse the Authorization header correctly (if you see a “Consumer key is missing” error when authenticating over SSL, you have a server issue). In this case, you may provide the consumer key/secret as query string parameters."

How to fix that?

Request parameters are not working.

Hi,

I've noticed that actually most of the parameters listed in WooCommerce Api docs are not working for me.

I can filter product results by category using:
$woocommerce->get('products', ['filter[category]' =>'my-category'])

but when I'm trying parameters such as order/orderby, search (among other) I just get back basic response and the parameters are being ignored.

Filters not Working

<?php
$woocommerce = new Client(
    'http://mywpsite.com', 
    'ck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', 
    'cs_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
    [
        'wp_api' => true,
        'version' => 'wc/v1',
    ]);

try {
$params = [
  'filter' => [
    'limit' => '2'
  ],
];
$getData = $woocommerce->get("/products/", $param);
echo json_encode($getData, JSON_PRETTY_PRINT);
} catch (HttpClientException $e) {
    $data['status'] = 'error';
    echo json_encode($data, JSON_PRETTY_PRINT);

// OUTPUTS ALL PRODUCTS (Filters not working)

Filters just doesn't work

Woocommerce = v2.6.0 beta 2
WC API = 3.1.0
WP REST API = v1.1.1 (Latest from Github) [https://github.com/woothemes/wc-api-php]

Filter encoding

Hi, I have some products with these SKUs:

  • CAB.SAU.M.VIL.S&M.10
  • CAB.SAU.M.VIL.10

This is the line of code that I use for retrieving products via the APIs:

$existing_products = $woocommerce->get('products', array('sku' => rawurlencode($product->code), 'status' => 'any'));

where $product->code is one of the SKUs.

The problem is that the api find the second product, but not the first one.
I think the problem is the "&" character inside the SKU, but i don't understand why there is a problem, i'm encoding the skus with rawurlencode function.

How use it?

Hello,
i download your script but how we can use it? have an example (php files)?
thanks

Rest API always returning oauth_consumer_key missing

I'm using the packagist latest version. On a HTTPS, i can login using Basic Auth without issues, but on my staging server which obviously doesn't feature HTTPs, i can't seem to login and constantly get:

{
"errors": [
{
"code": "woocommerce_api_authentication_error",
"message": "Le paramètre oauth_consumer_key est manquant"
}
]
}

I'm using this to initialize my client:

$credentials = $this->credentialStorage->retrieveCredentials();
        return new Client(
            env('WC_HOSTNAME', 'https://www.boutiquepourbebe.com'),
            $credentials->apikey,
            $credentials->secret
        );

Where $credentials is an object that stores valid API key credentials taken from key creation panel in wp-admin.

Where am i failing?

Thanks

duplicated variations data and images when update products

Hi, all works great but if i try to update a product all variations data including images are doubling. to prevent data duplicated i created this function:

public function reset_product_variations($product_id)
{
    global $wpdb;
  $args = array(
    'post_parent' => $product_id,
    'post_type'   => 'product_variation', 
    'numberposts' => -1,
    'post_status' => 'any' 
); 
$childrens = get_children( $args);
if($childrens):
    foreach($childrens as $product_variation):    
     $wpdb->query("DELETE FROM {$wpdb->postmeta} WHERE post_id = ".$product_variation->ID);
     wp_delete_post($product_variation->ID,true ); 
    endforeach;

endif;
}

Is there a simple way to delete variations images before insert to look like an update?
Thank you

Invalid JSON returned

I would like to list all products, therefore I used the filter[limit] like this

$woocommerce->get('products', array('filter[limit]' => 10000, 'fields' => 'id,title,sku,variations'));

Unfortunately I get PHP-error message saying

Fatal error: Uncaught exception 'Automattic\WooCommerce\HttpClient\HttpClientException' with message 'Invalid JSON returned' in /var/www/html/wcapi/src/WooCommerce/HttpClient/HttpClient.php:303 Stack trace: #0 /var/www/html/wcapi/src/WooCommerce/HttpClient/HttpClient.php(346): Automattic\WooCommerce\HttpClient\HttpClient->lookForErrors(NULL) #1 /var/www/html/wcapi/src/WooCommerce/HttpClient/HttpClient.php(382): Automattic\WooCommerce\HttpClient\HttpClient->processResponse() #2 /var/www/html/wcapi/src/WooCommerce/Client.php(82): Automattic\WooCommerce\HttpClient\HttpClient->request('products', 'GET', Array, Array) #3 /var/www/html/wcapi/wcapi.php(1189): Automattic\WooCommerce\Client->get('products', Array) #4 {main} thrown in /var/www/html/wcapi/src/WooCommerce/HttpClient/HttpClient.php on line 303

Is there a way to list all products?

Get data and post it to another woocommerce API website.

Hello,
I have 2 websites and installed woocommerce on both websites. I have API keys of both the websites. The thing I want to do is when I request for the particular ID on the first website, the returned data should post that item on the another website. For example,

$site_main = new Client(
    'https://abc.biz/', 
    'ck_zbc', 
    'cs_zbc',
     [
        'version' => 'v3',
        'ssl_verify'=> 'false'
    ]

);

 $get_result = $site_main ->get('products/17640');

$site_another= new Client(
    'https://xyz.com/', 
    'ck_123', 
    'cs_456',
     [
        'version' => 'v3',
        'ssl_verify'=> 'false'
    ]
);

$site_another->post('products',$get_result);

Basically get data from one API and post into another one. The problem is the data are filed but some are not like images and other stuffs! Any solution?

Posting product works but always comes back with "no response from server"

try{ print_r($woocommerce->post('products',$data)); }catch(HttpClientException $e){ $e->getMessage(); // Error message. $e->getRequest(); // Last request data. $e->getResponse(); // Last response data. }

is returning "no response from server" and response code 0 but when it posts show up on the front end.

Always getting a woocommerce_rest_authentication_error

Hello.

I've been trying to use this wrapper to connect to a wordpress + woocommerce page but I always get an authentication error. I followed the steps described here to generate the key and secret for the application.

PHP: v7.0.9
Laravel Framework: v5.2.41
WC-API-PHP: v1.1.1

Code:

try {
  $woocommerce = new Client(
    'http://localhost:8000',
    'ck_792b5ebdea08a6edb6d3c415ac4f8e0bc7221553',
    'cs_f56b03cbe7536cb4c0215f476d5a4e119dbc78ab',
    [
      'wp_api' => true,
      'version' => 'wc/v1',
      'verify_ssl' => false,
      'timeout' => 120,
    ]
  );
  print_r($woocommerce->get('products'));
} catch ( HttpClientException $e ) {
  print_r($e->getMessage().PHP_EOL); // Error message.
  $lastRequest = $woocommerce->http->getRequest();
  print_r($lastRequest->getUrl().PHP_EOL); // Requested URL (string).
  print_r($lastRequest->getParameters()); // Request parameters (array).
  print_r($lastRequest->getHeaders()); // Request headers (array).
}

Output:

Error: Invalid Signature - provided signature does not match. [woocommerce_rest_authentication_error]
http://localhost:8000/wp-json/wc/v1/products?oauth_consumer_key=ck_792b5ebdea08a6edb6d3c415ac4f8e0bc7221553&oauth_nonce=64b9aeeedfdb37b08085a02c0fe549273def9ec5&oauth_signature=Xy2bUyBjEYXr10n7HbK2eQptg%2FwxRrxnwgyWETxIN5o%3D&oauth_signature_method=HMAC-SHA256&oauth_timestamp=1470306720
Array
(
    [oauth_consumer_key] => ck_792b5ebdea08a6edb6d3c415ac4f8e0bc7221553
    [oauth_nonce] => 64b9aeeedfdb37b08085a02c0fe549273def9ec5
    [oauth_signature] => Xy2bUyBjEYXr10n7HbK2eQptg/wxRrxnwgyWETxIN5o=
    [oauth_signature_method] => HMAC-SHA256
    [oauth_timestamp] => 1470306720
)
Array
(
    [Accept] => application/json
    [Content-Type] => application/json
    [User-Agent] => WooCommerce API Client-PHP/1.1.1
)

Wordpress System:

`
### WordPress Environment ###

Home URL: http://localhost:8000
Site URL: http://localhost:8000
WC Version: 2.6.2
Log Directory Writable: ✔
WP Version: 4.5.3
WP Multisite: –
WP Memory Limit: 256 MB
WP Debug Mode: –
WP Cron: ✔
Language: es_ES

### Server Environment ###

Server Info: Apache/2.4.10 (Debian)
PHP Version: 5.6.24
PHP Post Max Size: 8 MB
PHP Time Limit: 30
PHP Max Input Vars: 1000
cURL Version: 7.38.0
OpenSSL/1.0.1t

SUHOSIN Installed: –
Max Upload Size: 2 MB
Default Timezone is UTC: ✔
fsockopen/cURL: ✔
SoapClient: ❌ Tu servidor no tiene la clase SoapClient habilitada - puede que algunos plugins de puerta de enlace que utilizan SOAP no funcionen como se espera.
DOMDocument: ✔
GZip: ✔
Multibyte String: ✔
Publicar remoto: ✔
Obtén remoto: ✔

### Database ###

WC Database Version: 2.6.2
: 
woocommerce_sessions: ✔
woocommerce_api_keys: ✔
woocommerce_attribute_taxonomies: ✔
woocommerce_downloadable_product_permissions: ✔
woocommerce_order_items: ✔
woocommerce_order_itemmeta: ✔
woocommerce_tax_rates: ✔
woocommerce_tax_rate_locations: ✔
woocommerce_shipping_zones: ✔
woocommerce_shipping_zone_locations: ✔
woocommerce_shipping_zone_methods: ✔
woocommerce_payment_tokens: ✔
woocommerce_payment_tokenmeta: ✔
MaxMind GeoIP Database: ✔

### Active Plugins (22) ###

Akismet: por Automattic – 3.1.11
Asesor de Cookies: por Carlos Doral Pérez – 0.21
Contact Form 7: por Takayuki Miyoshi – 4.4.2
Content Manager: por Pixel Industry Ltd. – 1.1.9
Elvyre Core plugin: por Pixel Industry – 1.5
Google Analytics by MonsterInsights: por MonsterInsights – 5.5.2
Hello Dolly: por Matt Mullenweg – 1.6
Instagram Feed: por Smash Balloon – 1.4.6.2
Newsletter: por Stefano Lissa & The Newsletter Team – 4.5.6
Recent posts Widget: por Pixel Industry – 1.2
Regenerate Thumbnails: por Alex Mills (Viper007Bond) – 2.2.6
Revolution Slider: por ThemePunch – 4.6.93
Simple Share Buttons Adder: por Simple Share Buttons – 6.2.2
TweetScroll Widget: por Pixel Industry – 1.3.7
Social Media and Share Icons (Ultimate Social Media): por UltimatelySocial – 1.5.2
WooCommerce Customizer: por SkyVerge – 2.3.1
WooCommerce Pay for Payment: por Jörn Lund – 1.3.8
WooCommerce Redsys payment gateway: por Jesús Ángel del Pozo Domínguez – 1.0.11
WooCommerce: por WooThemes – 2.6.2
Importador de WordPress: por wordpresspuntoorg – 0.6.1
YITH Newsletter Popup: por Your Inspiration Themes – 1.0.2
YITH WooCommerce Wishlist: por YITHEMES – 2.0.16

### Settings ###

Force SSL: –
Currency: EUR (€)
Currency Position: right
Thousand Separator: .
Decimal Separator: ,
Number of Decimals: 2

### API ###

API Enabled: ✔

### WC Pages ###

Base de la tienda: #936 - /tienda/
Carrito: #937 - /carro/
Finalizar compra: #938 - /finalizar-comprar/
Mi cuenta: #939 - /mi-cuenta/

### Taxonomies ###

Product Types: external (external)
grouped (grouped)
simple (simple)
variable (variable)


### Theme ###

Name: Elvyre - Retina Ready Wordpress Theme
Version: 1.5
Author URL: http://pixel-industry.com
Child Theme: ❌ – Si estás modificando WooCommerce en un tema padre que no has creado personalmente
te recomendamos utilizar un tema hijo. Ver: : Cómo crear un tema hijo

WooCommerce Support: ✔

### Templates ###

Overrides: elvyre/woocommerce/archive-product.php
elvyre/woocommerce/content-product.php versión1.6.4 no está actualizado. La versión del sistema es2.6.1
elvyre/woocommerce/notices/error.php
elvyre/woocommerce/notices/notice.php
elvyre/woocommerce/notices/success.php
elvyre/woocommerce/single-product/product-image.php
elvyre/woocommerce/single-product.php

: Aprende cómo actualizar plantillas obsoletas
`

What am I doing wrong or what did I miss? Thanks in advance

Invalid Consumer Secret

I get a fatal error that my consumer secret should be invalid:

Fatal error: Uncaught Automattic\WooCommerce\HttpClient\HttpClientException: Error: Consumer Secret ist ungültig [woocommerce_api_authentication_error]

But consumer key and secret are correct (readonly) and the same keys working finde with other v3 API wrappers.

Cannot update order with line item,fee line,shipping line from json. Error: Fatal error: Uncaught exception 'Automattic\WooCommerce\HttpClient\HttpClientException' with message 'Invalid JSON returned' in /home/builhsqv/public_html/test/wc/src/WooCommerce/HttpClient/HttpClient.php:332

EXPLANATION OF THE ISSUE

I am integrating woocommerce with external application and trying to update an order from external system. I convert the json which i get from external application to data array and pass that array in order update put method.

STEPS TO REPRODUCE THE ISSUE

json string - '{
"status":"pending",
"shipping_lines":[
{
"total":"12.00",
"method_title":"Train transport",
"method_id":"awd_shipping",
"id":1386

}],
"shipping":{
"state":"",
"postcode":"123445",
"last_name":"Thakur",
"first_name":"Yashwant",
"country":"SG",
"company":"Scholastic",
"city":"",
"address_2":"",
"address_1":"22c"
},
"set_paid":false,
"payment_method_title":"N/A",
"payment_method":"",
"customer_note":"",
"customer_id":1,
"billing":{
"state":"CH",
"postcode":"123445",
"phone":"7814024414",
"last_name":"Thakur",
"first_name":"Yashwant",
"email":"[email protected]",
"country":"SG",
"company":"Scholastic",
"city":"Chandigarh",
"address_2":"#2688",
"address_1":"22c75"
}
}
'
$entityBody=decode that into data array by json_decode().
$woocommerce-&gt;put($'orders/'.$id, $entityBody);
//IF i Remove shipping lines part in json ,order is update successfully

SYSTEM STATUS REPORT

Warning: in_array() expects parameter 2 to be array, null given in /home/builhsqv/public_html/test/wp-content/plugins/woocommerce/includes/abstracts/abstract-wc-order.php on line 746

Warning: in_array() expects parameter 2 to be array, null given in /home/builhsqv/public_html/test/wp-content/plugins/woocommerce/includes/abstracts/abstract-wc-order.php on line 746

Fatal error: Uncaught exception 'Automattic\WooCommerce\HttpClient\HttpClientException' with message 'Invalid JSON returned' in /home/builhsqv/public_html/test/wc/src/WooCommerce/HttpClient/HttpClient.php:332 Stack trace: #0 /home/builhsqv/public_html/test/wc/src/WooCommerce/HttpClient/HttpClient.php(371): Automattic\WooCommerce\HttpClient\HttpClient->processResponse() #1 /home/builhsqv/public_html/test/wc/src/WooCommerce/Client.php(69): Automattic\WooCommerce\HttpClient\HttpClient->request('orders/9920', 'PUT', Array) #2 /home/builhsqv/public_html/test/wc/RestUpdateOrder.php(50): Automattic\WooCommerce\Client->put('orders/9920', Array) #3 {main} thrown in /home/builhsqv/public_html/test/wc/src/WooCommerce/HttpClient/HttpClient.php on line 332

About Usage

Hi,

Thank you for this comprehensive library.

Can you explain usage of this library more detailed? For example how to setup, how to get or delete a order, usage of methods etc.

I newly started to use Woocommerce api and I stuck at beginning.

Thank you!

Updating variation image by ID of existing image

I am not sure if this is a bug or a support issue:
I create a product with two variations. The first variation has an image, the second has no image. So far, all good.
I GET the product and can see the id of the uploaded variation image. All good.
I want both variations to have the same image, so I update (PUT) the product, adding the image ID of the first variation to the second variation, and set position=0. But nothing happens. Other changed parameters are updated, just not the image. Am i doing something wrong, or is this a bug?

Missing products when retrieving all products

I am using this PHP library to connect Microsoft Access with WooCommerce. Nevertheless, when retrieving all products some of them are missing. This is the function I am using:

function getAllWCProducts(){
  //Get WooCommerce client
  $woocommerce = getWCClient();
  // 200 products per page
  $array = Array('posts_per_page' => 200);
  // Initialize counter
  $i = 1;
  // Initialize array
  $result = Array();
  // Execute a query while products are returned
  do{
      $page = $i;
      try {
        // Store every page in the array
        $result[$i] = $woocommerce->get('products', ['page'=>$page,'filter'=>$array]);
      } catch (Exception $e) {
        echo $e->getMessage();
      }
      $i++;
  }while(!empty($result[$i-1]));
  return $result;
}

In WooCommerce there are about 600 products. The function retrieves most of the products, but particularly, when post_per_page filter is set to 200 products with ID from 694 to 761 are not retrieved. And when post_per_page is set to 20, missing products ID goes from 694 to 818.

I have been debugging the code throroughly and my conclusions are that $woocommerce->get() is the culprit. Nonetheless, I do not know if the mistake is either on the filter parameters or in the function design.

Troubles with product categories actions

Hello everybody.
->post('products/categories') - doesnt return insert category. Its return always random category in system. It's your bug or WooCoommerce?
Why ->get('products/categories') not accept array args? If i want to get category with name 'Test' i always saw all categories in system. Bug or what?

$woocommerce->get params

using $products = $woocommerce->get('products',['per_page'=>1,'sku'=>'somesku']);
or $products = $woocommerce->get('products',array('per_page'=>1,'sku'=>'somesku'));
does not come back with a product with the sku 'somesku' but instead comes back with all products.

Notice: Undefined offset: 1 in HttpClient.php on line 244

Hi,

A notice appears when you update/create a product. I think it happens on all post/put method.

Problem: automattic/woocommerce/src/WooCommerce/HttpClient/HttpClient.php on line 244

list($key, $value) = \explode(': ', $line);

The header contains a line HTTP/1.1 200 OK and this string doesn't contains :.

Issue with authentication Consumer Key is missing

I am using this library v 1.1.1 under HTTP and disabled mod_security but the library always throw this exception:

Caught exception 'Automattic\WooCommerce\HttpClient\HttpClientException' with message 'Error: oauth_consumer_key parameter is missing [woocommerce_api_authentication_error]'

Here is my code:

    $woocommerce = new Client(
            SERVER_URL, API_KEY, API_SECRET, ['version' => 'v3', 'timeout' => 20, 'verify_ssl' => false, 'query_string_auth' => false]
    );

filter search not working

using $products = $woocommerce->get('products',['filter'=>['search'=>'somesearchterm']]);,
$products = $woocommerce->get('products',['search'=>'somesearchterm']);, and
$products = $woocommerce->get('products',['per_page'=>1]); do not return expected results

returns default results

Allow custom rest api url base

It's possible to filter the WP API's base url of wp-json to be something custom like api. Ideally it would be possible to set the URL that the client uses too, through the options.

I'll submit a PR for this.

api not work

Fatal error: Class 'Client' not found error occured and also use Automattic\WooCommerce\Client; not work please help how to solve this issue i include client.php file and autoload.php file.

Get "products" doesn't work with multiple filters

hello,

i'm trying to get products using multiple filters but i always get this message:
Error: Invalid Signature - provided signature does not match [woocommerce_api_authentication_error]

even though i'm using the same keys to get other data like orders successfully, but when i try to get products using filters like category, sku, page..etc i get that invalid signature message

any idea why i'm getting this message?

thanks

api returning 1

Hi,

I am hoping someone can help. I have a client using WooCommerce and I have just upgraded them to v3 api and integrated this client. I am having an issue with the /products request - it is always returning 1.

From what i have read the 1 is something to do with a callback - but i cannot find anything. my code is as follows:

$this->_wc = new Client(WOO_URL, WOO_KEY, WOO_SECRET, array('verify_ssl' => false));
$products = $this->_wc->get('products', array('filter[limit]' => 100, 'page' => $page));
echo "<pre>products: ";print_r($products);echo "</pre>";die;

any ideas?

IIS not accepting POST/PUT but GET works

Developing local with API v3 everything works fine. On production server, which is an IIS GET requests works fine but POST and PUT generates "woocommerce_api_authentication_error" => "Signature error, not matching" (free translating from Swedish).

The IIS server should be fine with POST (not absolutely sure about PUT). Any ideas?

Order Meta

We have created a custom order_meta value to tag specific orders and are trying to query only those specific orders without returning every order and then looping through them. I can not determine the correct parameters to retrieve order_meta value. I have tried adding url parameters:
&meta_key=meta_value. We also set the filter[meta]=true.

With the new API V1, I see there is a filter option, although unsure how to set the query args?
filter - Use WP Query arguments to modify the response; private query vars require appropriate authorization.

How can I retrieve only the orders with a set order_meta value? Thanks for your help.

Examples and Comparison

Hello,

Currently I've built a plugin that creates/updates/deletes products in WooCommerce based on this PHP library. I see that you have contributed there as well. Is this library these essentially doing the same thing as that one? I'm interested in using this one as it seems to be updated a little more often. Do you have any examples out there that show how to utilize this API to create products similar to this? Would your recommend one of these libraries over the other? Thanks for you assistance.

Have a great day,
patrick

'/vendor/autoload.php' missing

I am trying to setup WC-API; however i do not have /vendor/autoload.php in my directory structure. I have WP and WC installed. What am I missing?

Nonce invalid

Hi,

This my php code:

require __DIR__ . '/vendor/autoload.php';

use Automattic\WooCommerce\Client;

$woocommerce = new Client(
    $url, 
    $consumer_key, 
    $consumer_secret,
    [
        'version' => $version,
    ]
);

$parameters = array();
print_r($woocommerce->get('products', $parameters));

I always get this error:

PHP Fatal error: Uncaught exception 'Automattic\WooCommerce\HttpClient\HttpClientException' with message 'Error: Nonce invalide - le nonce a déjà été utilisé [woocommerce_api_authentication_error]' in C:\xampp\htdocs\Pour tests\woonlib\vendor\automattic\woocommerce\src\WooCommerce\HttpClient\HttpClient.php:315

Nonce is invalid.

Really strange. What happen ?

Thanks.

API - Invalid response json

Hi and thanks for this great API client for Woocommerce.
I'm getting 'Invalid JSON returned' because response is null when i do calls on live..
I'm using Versión 2.5.5 and this issue is related with issue #10

On localhost

  • it is working fine on localhost PUT, POST, GET...
  • It is working fine if i do calls under same domain setted up with vhost and xampp

On live server (InmotionHosting)

  • I created read/write API key and signature.
  • i tested url in browser to see if it is building endpoint properly and it is.
  • i only can get product count with API when i do requests under same domain.
  • Same issue with call methods GET, PUT, DELETE and POST
  • Server has enable allow_url_fopen = ON
  • Server has enable CURL
  • I can do calls with google API without issues

Kindly, help me if somebody has same issue.
Thank you very much 👍

ERR_CONNECTION_RESET when trying to get products

Hi,
I am trying to get all products but the request is aborted and I get a ERR_CONNECTION_RESET in Chrome.
Im using a very simple code and requests to "orders" are working.

use Automattic\WooCommerce\Client;
use Automattic\WooCommerce\HttpClient\HttpClientException;
try{
    $api = new Client(API_URL, API_KEY, API_SECRET);
    echo "<pre>", print_r($api), "</pre>";
    echo "<pre>", print_r($api->get('products')), "</pre>"; //Produces error
}
catch( Exception $e ){
    echo $e->getMessage();
}

undefined index 'position' in class-wc-api-products.php on r. 2524

While fetching products via the client-AP,I I got the many notices which breaks the valid json response. Probably because I programmatically import (many) products via methods like wp_insert_post and add_post_meta()/update_post_meta() (since saving via this client is, for some reason, so inconvenient in debugging and speed) . And since I never thought of giving my attributes some position, it throws these notices.

original:
'position' => (int) $attribute['position'],

My 'fix':
'position' => isset($attribute['position']) ? (int) $attribute['position'] : 0,

Erro 500

Boas,

Podemos falar em português ?
Antes de mais parabéns pelo teu trabalho.

Estava a tentar experimentar a tua wc-api-php mas não consigo obter nada. Sempre que tento fazer get ou post de alguma coisa recebo o erro 500. Será problema do lado do hosting ?

Com um client (postman) consigo obter os get request mas não consigo fazer post request, recebo um problema de autenticação.

Com a tua wc-api-php ao efectuar a ligação não recebo nenhum erro mas depois ao efectuar a query recebo sempre erro 500. Será que me podias ajudar?

Obrigado.

something is wrong when using filters

I'm trying to use filters with no luck, i keep getting

Error: Invalid Signature - provided signature does not match [woocommerce_api_authentication_error]

I get that error every time i try to use filters like this:

$params = [
    'filter' => [
        'created_at_min' => '2016-01-01',
        'created_at_max' => '2016-01-15',
    ],
    'page' => 1,
];

if i remove the dates filters it will work:

$params = [
    'filter' => [
        'limit' => 15,
    ],
    'page' => 1,
];

category filter show the same message:

$params = [
    'filter' => [
        'limit' => 15,
        'category' => 'Music',
    ],
    'page' => 1,
];

it will work if i remove it:

$params = [
    'filter' => [
        'limit' => 15,
    ],
    'page' => 1,
];

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.