简体   繁体   中英

Mailchimp_List_AlreadySubscribed Fatal Error using Mailchimp API 2 and PHP

I'm trying to use the Mailchimp API on my site to allow people to subscribe to my Mailchimp newsletter via a custom form.

The working code is as follows:

$message="";
if(isset($_POST) & !empty($_POST)){ 
    $emailsanit=filter_var($_POST['email'],FILTER_SANITIZE_EMAIL);
    $email=filter_var($emailsanit,FILTER_VALIDATE_EMAIL);

    $api_key = "my api key";
    $list_id = "my list id";

    require("Mailchimp.php");
    $Mailchimp = new Mailchimp( $api_key );
    $Mailchimp_Lists = new Mailchimp_Lists( $Mailchimp );
    $subscriber = $Mailchimp_Lists->subscribe( $list_id, array( 'email' => $email ) );

    if ( ! empty( $subscriber['leid'] ) ) {
        $message="<div id='message' class='text-success'>Please check your email inbox to         complete your subscription</div>";
    }
    else
    {
        $message="<div id='message' class='text-danger'>Failed to add email to database.   Please try again or email</div>";
    }
}
?>

As I say, this works fine, the problem I'm having is if somebody enters an email address that's already registered I get the following error and obviously nothing else loads:

Fatal error: Uncaught exception 'Mailchimp_List_AlreadySubscribed' with message 'example@example.com is already subscribed to list XX.

Any suggestions as to how I could go about making a rule so that if an email is already registered the message variable is updated (the form is processed on the same page)?

This post MailChimp API 2.0 and PHP Subscribe Form had someone with the same problem but I didn't really understand the solution.

I catch the error with the code:

try {
    $api->lists->subscribe('[LIST_ID]', array('email' => $_POST['email']));
    echo 'success';
} catch(Mailchimp_Error $e) {
    echo 'fail';
    //echo $e->getMessage();
}

This seems a bit old now, but since I'm working on MailChimp, the way to catch the error is as follows:

begin 
  # code for subscribing email to the list
rescue Mailchimp::ListAlreadySubscribedError
  # code with flash error and redirection
end

This assumes the use of the following gem:

 gem 'mailchimp-api', require: 'mailchimp'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM