[英]using MailChimp API without cURL
我正在嘗試使用MailChimp API將訂閱者添加到列表,一旦他們選中了表單上的復選框。 我可以使用cURL做到這一點,並且工作正常,但是將要啟用的服務器未啟用它。 我正在嘗試使用file_get_contents(),但這給了我401錯誤。 我檢查了API密鑰和列表ID,它們都是正確的。 我猜想我的語法搞砸了,或者我在錯誤的地方放了東西,但是我沒有看到問題。 我嘗試過的如下。 有人有想法么?
if (isset($_POST['mailtest']) == 'value1'){
$email = $_POST['email'];
$fname = $_POST['firstname'];
$lname = $_POST['lastname'];
$mailchimp_api_key = 'apikey';
$mailchimp_list_id = 'listid';
$data = array(
'apikey' => $mailchimp_api_key,
'id' => $mailchimp_list_id,
'email' => $email
'status'=>'subscribed'
);
$memberId = md5(strtolower($email));
$dataCenter = substr($mailchimp_api_key ,strpos($mailchimp_api_key, '-')+1);
$endpoint = 'https://' . $dataCenter . '.api.mailchimp.com/3.0/lists/' . $mailchimp_list_id . '/members/' . $memberId;
if ($fname && $lname) $data['merge_vars '] = array('FNAME' => $fname, 'LNAME' => $lname);
$json_data = json_encode($data);
$options = array(
'http' => array(
'method' => 'POST',
'header' => "Content-type: application/json",
"Connection: close\r\n" .
"Content-length: " . strlen($json_data) . "\r\n",
'data' => $json_data,
),);
$context = stream_context_create($options);
$result = file_get_contents($endpoint, false, $context);
}
您需要設置基本身份驗證標頭。 同樣,您似乎也在api鍵中包含了dataCentre,因此以下代碼可能需要進行一些調整,因為我實際上並不知道$mailchimp_api_key
設置為什么。
// this is improper usage of isset. isset returns a boolean
// since you're not doing a strict match it'll always work,
// unless mailtest is null or isn't set.
if (isset($_POST['mailtest']) == 'value1') {
$email = $_POST['email'];
$fname = $_POST['firstname'];
$lname = $_POST['lastname'];
$mailchimp_api_key = 'apikey';
$mailchimp_list_id = 'listid';
$data = array(
'apikey' => $mailchimp_api_key,
'id' => $mailchimp_list_id,
'email' => $email
'status'=>'subscribed'
);
$memberId = md5(strtolower($email));
$dataCenter = substr($mailchimp_api_key ,strpos($mailchimp_api_key, '-')+1);
$endpoint = 'https://' . $dataCenter . '.api.mailchimp.com/3.0/lists/' . $mailchimp_list_id . '/members/' . $memberId;
if ($fname && $lname) {
$data['merge_vars '] = array('FNAME' => $fname, 'LNAME' => $lname);
}
$json_data = json_encode($data);
$options = array(
'http' => array(
'method' => 'POST',
'header' => implode(
"\r\n",
[
"Content-type: application/json",
"Content-length: " . strlen($json_data),
"Authorization: Basic " . base64_encode("anystring:$mailchimp_api_key") // see note above
]
),
'content' => $json_data,
)
);
$context = stream_context_create($options);
$result = file_get_contents($endpoint, false, $context);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.