Search code examples
phpwordpresscurlmultipartform-data

Send form-data in wp_remote_post


I have this curl request, which works:

curl -X POST "https://peyk.uk/api/v1/get-auth-token"
     -F "client_id=xxxxx"
     -F "client_secret=xxxx"

But when trying to reproduce with wp_remote_post, I keep getting a code 0 response, which is not helpful at all.

I have tried a lot of different combinations, but currently my request looks like the below:

$body = json_encode(array(
  'client_id' => $this->settings['client_id'],
  'client_secret' => $this->settings['client_secret']
));

$result = wp_remote_post('https://peyk.uk/api/v1/get-auth-token', array(
  'method' => 'POST',
  'headers' => array('Content-Type' => 'multipart/form-data'),
  'body'=> array('formdata' => $body)
));

Any ideas?


Solution

  • You are sending body in JSON format, while your server expects it encoded like form fields. Type this:

    $result = wp_remote_post('https://peyk.uk/api/v1/get-auth-token', array(
      'method' => 'POST',
      'headers' => array('Content-Type' => 'multipart/form-data'),
      'body' => array(
        'client_id' => $this->settings['client_id'],
        'client_secret' => $this->settings['client_secret']
      )
    ));
    

    See documentation for details.