[SalesForce] (400) – Bad Request when requesting auth token using WordPress

We're using some house-built wordpress plugins to create emails in SFMC from wordpress content. The original plugin used the Fuel SDK, which from what I can tell, does not support remote sending, only campaign creation.

So I'm trying to get the REST API / oauth workflow working, using the wordpress HTTP api wp_remote_post() function.

$tokens is an array of tokens just like the SFMC docs require, and the WP docs say should go in the body field.

Here's my code:

public function send_campaign() {
  $sf_token_url = 'https://auth.exacttargetapis.com/v1/requestToken';
  $tokens = require_once('oauth-config.php');
  $headers = array('Content-Type' => 'application/json');

  try {
    $res = wp_remote_post($sf_token_url, array(
      'httpversion' => '1.1',
      'body' => $tokens,
      'headers' => $headers
    ));

    if(is_wp_error($res)) {
      $error_message = $res->get_error_message();
      echo "Error: " . $error_message;
    } else {
      echo '<pre>';
       var_dump($res);
      echo '</pre>';
    }
  }

  catch(Exception $e) {
    wp_send_json_error($e->getMessage());
  }
}

Unfortunately all this gets me is a 400 - Bad request error.

To make sure there wasn't a problem on the salesforce side, I created a simple nodejs script to send a post request with clientId/secret and I get a successful auth token back.

I also tried testing my PHP code against http://httpbin.org/post and I get successful responses, so it's not my syntax from what I can tell.

Only thing I can think of is the PHP calls are going out from a remote server – a WP Engine staging server, which doesn't share our domain. My nodeJS script is running on my local machine.

Are there domain restrictions going to the SF rest API?

Anyone else run into issues like this?

Best Answer

So I got it working.

I had to change the Content-Type header to application/x-www-form-urlencoded, which I tried because of this answer.

Unfortunately the docs don't tell you that. In fact they say the opposite, which is super frustrating.