调用Mailchimp v3 API获取自动化列表返回401(API密钥缺失)求助
Answer
Let's break down the issues here—there are two main problems causing that 401 error:
Wrong request method
You mentioned you intended to use a GET request, but your code setsCURLOPT_POST, 1which forces a POST request. The Mailchimp/automationsendpoint requires a GET request to retrieve the list of automations. You can fix this by either removing that line entirely (since cURL defaults to GET) or explicitly settingCURLOPT_HTTPGET, true.Incorrect API key delivery
Mailchimp's API doesn't accept the API key as a POST parameter—you need to send it via HTTP Basic Authentication. That means using theCURLOPT_USERPWDoption, where the format isany-string:your-api-key(the "any-string" part can literally be anything, like "user"—Mailchimp ignores the username part, only cares about the key).
Also, double-check your API key: it should end with -us13 to match the us13 server you're targeting. If your key doesn't have that suffix, add it—this is a common gotcha.
Here's the corrected code that should work:
$apiKey = 'xxxxxxxxwqew3423xxxxx-us13'; // Ensure your key includes the server suffix $curl = curl_init(); // Use curl_setopt_array for cleaner code curl_setopt_array($curl, [ CURLOPT_URL => 'https://us13.api.mailchimp.com/3.0/automations', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPAUTH => CURLAUTH_BASIC, CURLOPT_USERPWD => "user:$apiKey" // Basic Auth setup ]); $result = curl_exec($curl); $info = curl_getinfo($curl); print_r($info); echo 'content type: ' . $info['content_type'] . '<br />'; echo 'http code: ' . $info['http_code'] . '<br />'; curl_close($curl); echo $result;
To sum it up: your original code was sending a POST request with the API key in the wrong place, which is why Mailchimp couldn't authenticate your request. Fixing the request method and using Basic Auth should resolve the 401 error.
内容的提问来源于stack exchange,提问作者Mohammad Shahnewaz Sarker

