Search code examples
wordpressbasic-authenticationguzzlenoncewp-api

External request to Wordpress WP-API - Basic Authentication


I'm trying to hit my Wordpress API using Basic Auth with Guzzle (http tool) from my middleware (Laravel).

$username = 'myAdminUserName';
$password = 'myAdminPassword';
$uri = 'https://example.com/wp-json/mysite-api/cleared-action';
$response = $this->guzzle->put(
    $uri,
    [
        'headers' => [
            'Authorization' => 'Basic ' . base64_encode( $username . ':' . $password )
        ],
        'body' => [
            'user_id' => $wordpressId  //passed into this function
        ]
    ]
);

It then hits the route set up in my Wordpress API

$routes['/mysite-api/cleared-action'] = array(
        array(array($this, 'automatedClearing'), WP_JSON_Server::ACCEPT_JSON 
                                               | WP_JSON_Server::CREATABLE 
                                               | WP_JSON_Server::EDITABLE)
    );

However that is as far as it gets. It does not hit my automatedClearing endpoint which looks like this

public function automatedClearing() {
    global $container;

    \Groups_User_Group::create( array('user_id' => 2903, 'group_id' => 13));

    $mySiteServices = $container['services'];

    $this->$mySiteServices->sendClearedEmail(2903);  //2903 = user_id
} 

I've used hardcoded values for the users ID.

I keep getting a 200 response from my call, so it definitely hits the route, but does not execute the endpoint. The response is basically just an empty one.

My Wordpress access.log shows the route being hit, but my error.log doesn't show anything. By the way, this is a laravel Homestead (vagrant) box hitting a Wordpress vagrant box.

I'm wondering if this is because the WP-API requires a nonce? But I thought nonce was only needed within Wordpress, whereas this is an external app hitting Wordpress.

I'm pretty stuck on this. Any guidance is greatly appreciated


Solution

  • Try to test it using postman ... if this works via postman then you have the problem with laravel or guzzle