0

I'm writing a Wordpress Plugin that sends requests via WooCommerce API. I need to send multiple GET requests to the API and instead of using a for loop and sending each request one after another, I was looking for a multiple request alternative and came across this class. A single request call via WooCommerce API basically looks like this (i.e. to list all products):

$headers = array( 'Content-Type' => 'application/json' );
// We may use HTTP Basic Auth for Authentication over HTTPS. 
$options = array(
   'auth' => array( 'ck000', 'cs000' ),
)
$response = Requests::request('https://mysite.xy/wp-json/wc/v3/products', $headers, null, $options);

This sends an authorized request (via the $options array with a consumer key and consumer secret to access the shop site) and retrieves a list with all products available. Looking at Requests::request_multiple, the method takes in an array of requests and options, with the following description of the parameter $options:

If the $options parameter is specified, individual requests will inherit options from it.

Now let's say I want to send 3 requests for different products (AAA, BBB and CCC):

// This is how you should create individual requests for request_multiple method
$req1 = array( 'url' => 'https://mysite.xy/wp-json/wc/v3/product/AAA' );
$req2 = array( 'url' => 'https://mysite.xy/wp-json/wc/v3/product/BBB' );
$req3 = array( 'url' => 'https://mysite.xy/wp-json/wc/v3/product/CCC' );
// Create requests array
$requests = array( $req1, $req2, $req3 );
// Send multiple requests
$responses = Requests::request_multiple( $requests, $options );

Each response in $responses has status code 401 (Unauthorized Access), although each request should inherit the same authentication from the $options array.

Is this something I should open an issue about on GitHub or is there something that I'm not fully getting?

1 Answer 1

2

Apparently, this already is a known issue on GitHub. Still open and not patched from May 16, 2016. Based on the suggestion from the comments, creating a new Hooks instance and registering the hook curl.before_multi_add with a callback that sets the cURL authentication options should solve the [401] Unauthorized Access problem.

use WpOrg\Requests\Hooks;

$hooks = new Hooks();
$hooks->register( 'curl.before_multi_add', function( &$curl_subhandle ) {
        // curl_setopt can fail => Still [401] then, so take care of that
        curl_setopt( $curl_subhandle, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
        curl_setopt( $curl_subhandle, CURLOPT_USERPWD, YOUR_CK . ":" . YOUR_CS );
    });

Afterwards, set the following in the $options array:

$options []= 'hooks' => $hooks;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.