Search code examples
phprestapitokenmarketo

Does the Marketo REST API asset Token work?


I am following this part of the documentation: http://developers.marketo.com/rest-api/assets/tokens/ and I always get the following an error: Fields cannot be empty.

Have anyone make it worked?

public function create_token($folder_id,$name,$content,$folder_type = 'Program')
{
    $folder_id = intval($folder_id);
    $endpoint = 'rest/asset/v1/folder/'.$folder_id.'/tokens';
    $body = new stdClass();
    $body->folderType = $folder_type;
    $body->name = $name;
    $body->type = 'rich text';
    $body->value = $content;
    $body_encoded = json_encode($body);

    echo $url = $this->url . $endpoint . ".json?access_token=" . self::$token;

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: x-www-form-urlencoded'));
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $body_encoded);
    $response = curl_exec($ch);
    curl_close($ch);
    return json_decode($response);
}

The reason for the Content-Type header was a suggestion from Marketo: https://www.screencast.com/t/CL5ZtPo1o

This is the answer from the request I keep getting:

object(stdClass)#1934 (4) {


["success"]=>
  bool(false)
  ["warnings"]=>
  array(0) {
  }
  ["errors"]=>
  array(4) {
    [0]=>
    object(stdClass)#1935 (2) {
      ["message"]=>
      string(20) "name cannot be null."
      ["code"]=>
      string(3) "701"
    }
    [1]=>
    object(stdClass)#1936 (2) {
      ["message"]=>
      string(20) "type cannot be null."
      ["code"]=>
      string(3) "701"
    }
    [2]=>
    object(stdClass)#1937 (2) {
      ["message"]=>
      string(101) "Token type is either null, blank or invalid. Please refer to the documentation for valid token types."
      ["code"]=>
      string(3) "701"
    }
    [3]=>
    object(stdClass)#1938 (2) {
      ["message"]=>
      string(21) "value cannot be null."
      ["code"]=>
      string(3) "701"
    }
  }
  ["requestId"]=>
  string(16) "11d1#15b49284636"
}

Solution

  • You don't have to post token fields as JSON object: json_encode($body)
    Fields are passed as request parameters or as a regular form

    This request with works well for me:

    POST https://123-FOO-456.mktorest.com/rest/asset/v1/folder/1039/tokens.json?value=TestTokenValue&folderType=Program&name=TestToken&type=text
    

    In this case, you also don't have to specify content type Content-Type: x-www-form-urlencoded

    I'm not PHP dev, but you can look here for examples how to post form data - PHP + curl, HTTP POST sample code?