Post body not working with wp_remote_post()

I’m trying to post with with the following code

    $userTokenApi = 'https://api.mindbodyonline.com/public/v6/usertoken/issue';

    $args = array(
        'headers' => array(
            'Content-Type' => 'application/json',
            'SiteId' => '6387',
            'Api-Key' => '7bba39594b4d460293abdfd64c8eea48'
        ),
        'body' => array(
            'Username' => 'myusername',
            'Password' => 'mypassword'
        )
    );

    $request = wp_remote_post($userTokenApi, $args);
    $responseCode = wp_remote_retrieve_response_code( $request );
    $body = wp_remote_retrieve_body($request);

    if ( is_wp_error( $request ) ) {
        return false; // Bail Early
    }

    $pretty = json_decode( $body ); ?>

But the response I’m getting back from the API is

Error:
Code: "MissingRequiredFields"
Message: "The following parameters are required: Username, Password"

The standard HTTP request for the same action (with PHP) is seen here https://developers.mindbodyonline.com/PublicDocumentation/V6#user-tokens and using postman I’m able to post and receive my response fine with PHP – HTTP Request2, PHP – cURL, and any other type of code.

I’m not sure what I’m missing here or what I don’t understand in the documentation

Any help would be amazing. Live issue can be seen here – error’s in console.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You’re setting the Content-Type header to application/json and wp_remote_post() doesn’t intelligently JSON-encode the request data (the body array), so you should manually do it. So for example:

'body' => json_encode( array(
    'Username' => 'myusername',
    'Password' => 'mypassword'
) )


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x