Mailchimp API - 订阅列表

时间:2014-03-18 18:42:53

标签: php json mailchimp

我正在为我的网站添加一个脚本以获取MailChimp订阅表单。我认为我的设置正确,但是当我点击订阅按钮时,我得到一个空白页面。

这是我目前的脚本

<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);

require_once 'Mailchimp.php';

$apikey = "XXXXXXXXXXXXXXX";
$Mailchimp = new Mailchimp($apikey);

if (!empty($_POST)) {

    $id = "XXXXXXXXXX";
    $email = array(
        'email' => trim($_POST['email'])
    );

    $result = $Mailchimp->$lists->subscribe($id, $email, $double_optin=false, $replace_interests=false);

    var_dump($result);

}

echo "TESTING";

所以我现在没有得到$ result变量或&#34; TESTING echo,所以我认为我必须做一些简单的错误。有谁看到明显的东西?我相信我使用了正确的默认JSON格式。 (键已经X出来了,但我使用的那个是正确的)

非常感谢任何帮助。

谢谢!

编辑:我已将代码更新为我认为更正确的内容,但它仍然无法正常工作。我真的可以帮上忙。

1 个答案:

答案 0 :(得分:0)

以下是我过去为MailChimp的API(MCAPI)处理AJAX电子邮件提交的方式:

define("MC_API_KEY", "Your mailchimp API key");
define("MC_API_LIST", "The list ID to subscribe user to");
define("EMAIL_TO", "email address in case subscription fails");

require "MailChimp.API.class.php";

function json($error = true, $message = "Unknown error") { 
  die(json_encode(array("error" => $error, "message" => $message)));
}

if(!empty($_POST)) {
  $email = !empty($_POST['email']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) ? $_POST['email'] : false;

  if($email !== false) {    
    $api = new MCAPI(MC_API_KEY);
    $result = $api->listSubscribe(MC_API_LIST, $email);

    if($api->errorCode || !$result) {
      if(isset($api->errorCode) && $api->errorCode == 214) { // already subscribed
        json(true, "You are already subscribed!");
      } else {
        $error = "Unable to save user email via MailChimp API!\n\tCode=".$api->errorCode."\n\tMsg=".$api->errorMessage."\n\n";
        $headers = "From: your@email.com\r\nReply-to: <{$email}>\r\nX-Mailer: PHP/".phpversion();

        mail(EMAIL_TO, "Newsletter Submission FAIL [MC API ERROR]", "{$error}Saved info:\nFrom: {$email}\n\nSent from {$_SERVER['REMOTE_ADDR']} on ".date("F jS, Y \@ g:iA e"), $headers);

        json(false, "Thank you - your email will be subscribed shortly!");
      }
    } else {
      json(false, "Thanks - A confirmation link has been sent to your email!");
    }
  } else {
    json(true, "Please enter your valid email address");
  }
} else json();