4

I am using the ExactTarget REST API.

I am able to get my access token successfully via OAuth and can make some GET requests (i.e. https://www.exacttargetapis.com/contacts/v1/schema) that return the expected results, but I get no response when I attempt to create a new contact.

(I have confirmed the app has write access).

What am I doing wrong? Thanks.

<?php
$url = 'https://www.exacttargetapis.com/contacts/v1/contacts';
$json = '{
    "contactKey": "test@example.com",
    "attributeSets": [{
        "name": "Email Addresses",
        "items": [{
            "values": [{
                "name": "Email Address",
                "value": "test@example.com"
            }]
        }]
    }]
}';

$options = array(
    'http' => array(
        'header' =>  "Content-Type: application/json\r\n" .
            "Accept: application/json\r\n" .
            "Authorization: Bearer " . $access_token . "\r\n",
        'method'  => 'POST',
        'content' => http_build_query($json)
    )
);
$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);

if ($result === FALSE) { echo "Result not returned"; }
print_r($result);
?>
1

If you look at http_build_query function:

Generate URL-encoded query string from array or json. 

But you're passing string. Then you're using file_get_contents which couldn't proceed with errors if any. e.g. if server couldn't proceed with request, you will see just:

Warning: file_get_contents(https://example.com): failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request

Try to use cURL instead:

<?php
$url = 'https://www.example.com';
//If will be easier to construct request as object and then convert to String.
$jsonData = array(
    'contactKey' => 'test@example.com'//,
    //'attributeSets' => array(
    //...
);

//Initiate cURL.
$ch = curl_init($url);

//Encode the array into JSON.
$jsonDataEncoded = json_encode($jsonData);

//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);

//Attach our JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);

//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 
    'Authorization: Bearer ' . $access_token)); 

//Ignore SSL verification 
//curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
//curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

//Execute the request
$result = curl_exec($ch);
if(curl_errno($ch)){
    echo 'Request Error:' . curl_error($ch);
}
print_r($result);
?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.