We all started somewhere! Share your experience on the Get Advice: Let's Get Started Sweepstakes thread and be entered to win a $100 credit on your Constant Contact account.

I am getting a 401 error within PHP but not while using Postman. What could be the error?

JeremyR53
Participant

I am getting a 401 error within PHP but not while using Postman. What could be the error?

public function register_contact($email, $first_name, $country, $zip)
{
// Initialize a cURL object

$payload = json_encode(array(
"email_address" => array("address" => $email, "permission_to_send" => "implicit"),
"first_name" => $first_name,
"create_source" => "Account"
));

// Define base URL

// Create full request URL with chosen parameters
$url = $base;

// Set the URL
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);

// Set authorization header
$authorization = 'Authorization: Bearer ' . get_option('constant_token');
curl_setopt($ch, CURLOPT_HTTPHEADER, array($authorization));

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));

curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);

// Make the call
$result = curl_exec($ch);

// Close cURL
curl_close($ch);

echo $result;
}
1 REPLY 1
David_B.
Moderator

Hello,

 

Thank you for reaching out to Constant Contact API Developer Support.

 

There are a few reasons that you may get a 401 error response, and more detail should be included in the error response message. In order to troubleshoot this further, I'd recommend capturing any error messages. For example:

 

public function register_contact($email, $first_name, $country, $zip)
{
// Initialize a cURL object

$payload = json_encode(array(
"email_address" => array("address" => $email, "permission_to_send" => "implicit"),
"first_name" => $first_name,
"create_source" => "Account"
));

// Define base URL
$base = 'https://api.cc.email/v3/contacts';

// Create full request URL with chosen parameters
$url = $base;

// Set the URL
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);

// Add option to capture the error response
curl_setopt($ch, CURLOPT_FAILONERROR, true); 

// Set authorization header
$authorization = 'Authorization: Bearer ' . get_option('constant_token');
curl_setopt($ch, CURLOPT_HTTPHEADER, array($authorization));

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));

curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);

// Make the call
$result = curl_exec($ch);

// Check for error
if (curl_errno($ch)) {
$error = curl_error($ch);
}

// Close cURL
curl_close($ch);

// Display results
if (isset($error)) {
echo $error;
} else {
echo $result;
}

}

 

Please have a look and let me know what the error response message you are seeing is, so that we can look into this in more detail.

 

Regards,

David B.
Tier II API Support Engineer

Developer Portal

View API documentation, code samples, get your API key.

Visit Page