Enter the Share Your Success Sweepstakes 2024 For the Chance to Win Great Prizes!

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

JeremyR53
Rookie
0 Votes
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.
Employee
0 Votes

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

Resources
Developer Portal

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

Visit Page

Announcements

API Updates

Join our list to be notified of new features and updates to our V3 API.

Sign Up