JonnyHarper
JonnyHarper

Reputation: 363

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 '[email protected] 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.

Upvotes: 1

Views: 1618

Answers (2)

vafeLu
vafeLu

Reputation: 71

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();
}

Upvotes: 2

user2953607
user2953607

Reputation: 97

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'

Upvotes: 0

Related Questions