function civicrm_api3_mailchimp_synchronize($params) { $return = $tags = $createdContact = array(); $apiKey = CRM_Core_BAO_Setting::getItem('MailChimp Preferences', 'api_key', NULL, FALSE); $tagsCount = civicrm_api3('Tag', 'getcount', array('sequential' => 1)); $tagsGet = civicrm_api3('Tag', 'get', array('sequential' => 1, 'rowCount' => $tagsCount)); foreach ($tagsGet['values'] as $tagIds => $tagsValues) { $tags[$tagsValues['id']] = $tagsValues['name']; } $mcClient = new Mailchimp($apiKey); $mcLists = new Mailchimp_Lists($mcClient); $lists = $mcLists->getList(); foreach ($lists['data'] as $listsDetails) { if (!in_array($listsDetails['name'], $tags)) { $tagsCreate = civicrm_api3('Tag', 'create', array('sequential' => 1, 'name' => $listsDetails['name'])); } $tagsCount = civicrm_api3('Tag', 'getcount', array('sequential' => 1)); $tagsGet = civicrm_api3('Tag', 'get', array('sequential' => 1, 'rowCount' => $tagsCount)); foreach ($tagsGet['values'] as $tagIds => $tagsValues) { $tags[$tagsValues['id']] = $tagsValues['name']; } if (in_array($listsDetails['name'], $tags)) { $keyTags = array_search($listsDetails['name'], $tags); $members = $mcLists->members($listsDetails['id']); foreach ($members['data'] as $key => $value) { try { $createdContact = civicrm_api3('Contact', 'create', array('sequential' => 1, 'contact_type' => "Individual", 'first_name' => $value['merges']['FNAME'], 'last_name' => $value['merges']['LNAME'], 'email' => $value['merges']['EMAIL'], 'api.EntityTag.create' => array('entity_id' => "\$value.id", 'entity_table' => "civicrm_contact", 'tag_id' => $keyTags), 'dupe_check' => true)); } catch (CiviCRM_API3_Exception $e) { $result = civicrm_api3('EntityTag', 'create', array('contact_id' => $e->getExtraParams()['ids'][0], 'tag_id' => $keyTags)); } } } } return civicrm_api3_create_success(); }
/** * Function to actually build the form * * @return None * @access public */ public function buildQuickForm() { $this->addFormRule(array('CRM_Mailchimp_Form_Setting', 'formRule'), $this); CRM_Core_Resources::singleton()->addStyleFile('uk.co.vedaconsulting.mailchimp', 'css/mailchimp.css'); $webhook_url = CRM_Utils_System::url('civicrm/mailchimp/webhook', 'reset=1', TRUE, NULL, FALSE, TRUE); $this->assign('webhook_url', 'Webhook URL - ' . $webhook_url); // Add the API Key Element $this->addElement('text', 'api_key', ts('API Key'), array('size' => 48)); // Add the User Security Key Element $this->addElement('text', 'security_key', ts('Security Key'), array('size' => 24)); // Add Enable or Disable Debugging $enableOptions = array(1 => ts('Yes'), 0 => ts('No')); $this->addRadio('enable_debugging', ts('Enable Debugging'), $enableOptions, NULL); // Create the Submit Button. $buttons = array(array('type' => 'submit', 'name' => ts('Save & Test'))); $groups = CRM_Mailchimp_Utils::getGroupsToSync(array(), null, $membership_only = TRUE); foreach ($groups as $group_id => $details) { $list = new Mailchimp_Lists(CRM_Mailchimp_Utils::mailchimp()); $webhookoutput = $list->webhooks($details['list_id']); if ($webhookoutput[0]['sources']['api'] == 1) { CRM_Mailchimp_Utils::checkDebug('CRM_Mailchimp_Form_Setting - API is set in Webhook setting for listID', $details['list_id']); $listID = $details['list_id']; CRM_Core_Session::setStatus(ts('API is set in Webhook setting for listID %1', array(1 => $listID)), ts('Error'), 'error'); break; } } // Add the Buttons. $this->addButtons($buttons); }
function subscribe_to_mailchimp($user_id) { $api_key = get_option('bbconnect_mailchimp_api_key'); $list_id = get_option('bbconnect_mailchimp_list_id'); $user = get_user_by('id', $user_id); $firstname = get_user_meta($user_id, 'first_name', true); $lastname = get_user_meta($user_id, 'last_name', true); $address1 = get_user_meta($user_id, 'bbconnect_address_one_1', true); $city = get_user_meta($user_id, 'bbconnect_address_city_1', true); $state = get_user_meta($user_id, 'bbconnect_address_state_1', true); $postal_code = get_user_meta($user_id, 'bbconnect_address_postal_code_1', true); $country = get_user_meta($user_id, 'bbconnect_address_country_1', true); $bbconnect_helper_country = bbconnect_helper_country(); $country = $bbconnect_helper_country[$country]; $email = $user->user_email; $mailchimp = new Mailchimp($api_key); $Mailchimp_Lists = new Mailchimp_Lists($mailchimp); try { $params = array('id' => $list_id, 'emails' => array(array('email' => $email))); $is_User_Registered = $mailchimp->call('lists/member-info', $params); if ($is_User_Registered['success_count'] == 0 || $is_User_Registered['success_count'] != 0 && $is_User_Registered['data'][0]['status'] != 'subscribed' && $is_User_Registered['data'][0]['status'] != 'unsubscribed') { $mc_email = array('email' => $email); $merge_vars = array('FNAME' => $firstname, 'LNAME' => $lastname, 'addr1' => $address1, 'city' => $city, 'state' => $state, 'zip' => $postal_code, 'country' => $country); $subscriber = $Mailchimp_Lists->subscribe($list_id, $mc_email, $merge_vars, '', false, false, false, false); if (empty($subscriber['leid'])) { wp_mail('*****@*****.**', 'CW Contact subscription to MailChimp failed 001', $email . ',' . $firstname . ' ' . $lastname . ' has failed to subscribe to mailchimp.'); } } } catch (\Mailchimp_Error $e) { wp_mail('*****@*****.**', 'CW Contact subscription to MailChimp failed 002', $email . ',' . $firstname . ' ' . $lastname . ' has failed to subscribe to mailchimp.'); return; } }
public function addToMailchimp($list_id, $email) { $api_key = $this->option('mailchimp_api'); $mail = new Mailchimp($api_key); $lists = new Mailchimp_Lists($mail); $subscriber = $lists->subscribe($list_id, array('email' => htmlentities($email))); if (empty($subscriber['leid'])) { return FALSE; } return $subscriber['leid']; }
function add_user_to_mailchimp($order_id) { /* * signup user for mailchimp newsletter */ if (isset($_POST['newsletter_signup'])) { if (class_exists('GF_MailChimp_Bootstrap')) { require_once ABSPATH . '/wp-content/plugins/gravityformsmailchimp/api/Mailchimp.php'; $api_key = "ed4ac31debf0bed4a0d710639aa1d3a3-us3"; $list_id = "d41e211c8f"; $Mailchimp = new Mailchimp($api_key); $Mailchimp_Lists = new Mailchimp_Lists($Mailchimp); $subscriber = $Mailchimp_Lists->subscribe($list_id, array('email' => htmlentities($_POST['billing_email'])), array(), 'html', true, true, true, false); } } }
$l_name = strip_tags($l_name); $email = strip_tags($email); $phone = strip_tags($phone); $comp_name = strip_tags($comp_name); $website = strip_tags($website); $address = strip_tags($address); $address_2 = strip_tags($address_2); $city = strip_tags($city); $postal_code = strip_tags($postal_code); $country = strip_tags($country); $state = strip_tags($state); mysqli_query($db, "\r\n\t\t\t\t\t\tINSERT INTO {$dbinfo[pre]}members \r\n\t\t\t\t\t\t(\r\n\t\t\t\t\t\t\tumem_id,\r\n\t\t\t\t\t\t\tf_name,\r\n\t\t\t\t\t\t\tl_name,\r\n\t\t\t\t\t\t\temail,\r\n\t\t\t\t\t\t\tpassword,\r\n\t\t\t\t\t\t\tphone,\r\n\t\t\t\t\t\t\tcomp_name,\r\n\t\t\t\t\t\t\twebsite,\r\n\t\t\t\t\t\t\tmembership,\r\n\t\t\t\t\t\t\tsignup_date,\r\n\t\t\t\t\t\t\tip_signup,\r\n\t\t\t\t\t\t\treferrer,\r\n\t\t\t\t\t\t\tstatus,\r\n\t\t\t\t\t\t\ttrialed_memberships,\r\n\t\t\t\t\t\t\tms_end_date,\r\n\t\t\t\t\t\t\tlanguage\r\n\t\t\t\t\t\t) \r\n\t\t\t\t\t\tVALUES \r\n\t\t\t\t\t\t(\r\n\t\t\t\t\t\t\t'{$umem_id}',\r\n\t\t\t\t\t\t\t'{$f_name}',\r\n\t\t\t\t\t\t\t'{$l_name}',\r\n\t\t\t\t\t\t\t'{$email}',\r\n\t\t\t\t\t\t\t'{$passwordEnc}',\r\n\t\t\t\t\t\t\t'{$phone}',\r\n\t\t\t\t\t\t\t'{$comp_name}',\r\n\t\t\t\t\t\t\t'{$website}',\r\n\t\t\t\t\t\t\t'{$membershipID}',\r\n\t\t\t\t\t\t\t'{$signupDate}',\r\n\t\t\t\t\t\t\t'{$ipsignup}',\r\n\t\t\t\t\t\t\t'{$_SESSION['initReferrerURL']}',\r\n\t\t\t\t\t\t\t'{$accountStatus}',\r\n\t\t\t\t\t\t\t'{$trialMembership}',\r\n\t\t\t\t\t\t\t'{$trialEndDate}',\r\n\t\t\t\t\t\t\t'{$selectedLanguage}'\r\n\t\t\t\t\t\t)\r\n\t\t\t\t\t"); // Save member $saveID = mysqli_insert_id($db); $Mailchimp = new Mailchimp($mailchimp_api_key); $Mailchimp_Lists = new Mailchimp_Lists($Mailchimp); $Mailchimp_Lists->subscribe($mailchimp_list_id, array('email' => $email)); mysqli_query($db, "\r\n\t\t\t\t\t\tINSERT INTO {$dbinfo[pre]}members_address \r\n\t\t\t\t\t\t(\r\n\t\t\t\t\t\t\tmember_id,\r\n\t\t\t\t\t\t\taddress,\r\n\t\t\t\t\t\t\taddress_2,\r\n\t\t\t\t\t\t\tcity,\r\n\t\t\t\t\t\t\tstate,\r\n\t\t\t\t\t\t\tpostal_code,\r\n\t\t\t\t\t\t\tcountry\r\n\t\t\t\t\t\t) \r\n\t\t\t\t\t\tVALUES \r\n\t\t\t\t\t\t(\r\n\t\t\t\t\t\t\t'{$saveID}',\r\n\t\t\t\t\t\t\t'{$address}',\r\n\t\t\t\t\t\t\t'{$address_2}',\r\n\t\t\t\t\t\t\t'{$city}',\r\n\t\t\t\t\t\t\t'{$state}',\r\n\t\t\t\t\t\t\t'{$postal_code}',\r\n\t\t\t\t\t\t\t'{$country}'\r\n\t\t\t\t\t\t)\r\n\t\t\t\t\t"); // Save member address $signupGroups = explode(",", $config['settings']['signup_groups']); // Assign any signup groups if ($signupGroups) { foreach ($signupGroups as $key => $value) { mysqli_query($db, "INSERT INTO {$dbinfo[pre]}groupids (mgrarea,item_id,group_id) VALUES ('members','{$saveID}','{$value}')"); } } //$_SESSION['testing']['step3'] = '3'; try { $memberObj = new memberTools($saveID); $member = $memberObj->getMemberInfoFromDB($umem_id); // Get all the member info from the database
/** * Mailchimp in their wisdom changed all the Ids for interests. * * So we have to map on names and then update our stored Ids. * * Also change cronjobs. */ public function upgrade_20() { $this->ctx->log->info('Applying update to v2.0 Updating Mailchimp Interest Ids to fit their new API'); // New $api = CRM_Mailchimp_Utils::getMailchimpApi(); // Old $mcLists = new Mailchimp_Lists(CRM_Mailchimp_Utils::mailchimp()); // Use new API to get lists. Allow for 10,000 lists so we don't bother // batching. $lists = []; foreach ($api->get("/lists", ['fields' => 'lists.id,lists.name', 'count' => 10000])->data->lists as $list) { $lists[$list->id] = ['name' => $list->name]; } $queries = []; // Loop lists. foreach (array_keys($lists) as $list_id) { // Fetch Interest categories. $categories = $api->get("/lists/{$list_id}/interest-categories", ['count' => 10000, 'fields' => 'categories.id,categories.title'])->data->categories; if (!$categories) { continue; } // Old: fetch all categories (groupings) and interests (groups) in one go: $old = $mcLists->interestGroupings($list_id); // New: fetch interests for each category. foreach ($categories as $category) { // $lists[$list_id]['categories'][$category->id] = ['name' => $category->title]; // Match this category by name with the old 'groupings' $matched_old_grouping = FALSE; foreach ($old as $old_grouping) { if ($old_grouping['name'] == $category->title) { $matched_old_grouping = $old_grouping; break; } } if ($matched_old_grouping) { // Found a match. $cat_queries[] = ['list_id' => $list_id, 'old' => $matched_old_grouping['id'], 'new' => $category->id]; // Now do interests (old: groups) $interests = $api->get("/lists/{$list_id}/interest-categories/{$category->id}/interests", ['fields' => 'interests.id,interests.name', 'count' => 10000])->data->interests; foreach ($interests as $interest) { // Can we find this interest by name? $matched_old_group = FALSE; foreach ($matched_old_grouping['groups'] as $old_group) { if ($old_group['name'] == $interest->name) { $int_queries[] = ['list_id' => $list_id, 'old' => $old_group['id'], 'new' => $interest->id]; break; } } } } } } foreach ($cat_queries as $params) { CRM_Core_DAO::executeQuery('UPDATE civicrm_value_mailchimp_settings ' . 'SET mc_grouping_id = %1 ' . 'WHERE mc_list_id = %2 AND mc_grouping_id = %3;', [1 => [$params['new'], 'String'], 2 => [$params['list_id'], 'String'], 3 => [$params['old'], 'String']]); } foreach ($int_queries as $params) { CRM_Core_DAO::executeQuery('UPDATE civicrm_value_mailchimp_settings ' . 'SET mc_group_id = %1 ' . 'WHERE mc_list_id = %2 AND mc_group_id = %3;', [1 => [$params['new'], 'String'], 2 => [$params['list_id'], 'String'], 3 => [$params['old'], 'String']]); } // Now cron jobs. Delete all mailchimp ones. $result = civicrm_api3('Job', 'get', array('sequential' => 1, 'api_entity' => "mailchimp")); if ($result['count']) { // Should only be one, but just in case... foreach ($result['values'] as $old) { // Double check id exists! if (!empty($old['id'])) { civicrm_api3('Job', 'delete', ['id' => $old['id']]); } } } // Create Push Sync job. $params = array('sequential' => 1, 'name' => 'Mailchimp Push Sync', 'description' => 'Sync contacts between CiviCRM and MailChimp, assuming CiviCRM to be correct. Please understand the implications before using this.', 'run_frequency' => 'Daily', 'api_entity' => 'Mailchimp', 'api_action' => 'pushsync', 'is_active' => 0); $result = civicrm_api3('job', 'create', $params); // Create Pull Sync job. $params = array('sequential' => 1, 'name' => 'Mailchimp Pull Sync', 'description' => 'Sync contacts between CiviCRM and MailChimp, assuming Mailchimp to be correct. Please understand the implications before using this.', 'run_frequency' => 'Daily', 'api_entity' => 'Mailchimp', 'api_action' => 'pullsync', 'is_active' => 0); $result = civicrm_api3('job', 'create', $params); return TRUE; }
function et_pb_submit_subscribe_form() { if (!wp_verify_nonce($_POST['et_load_nonce'], 'et_load_nonce')) { die(json_encode(array('error' => __('Configuration error', 'Divi')))); } $service = sanitize_text_field($_POST['et_service']); $list_id = sanitize_text_field($_POST['et_list_id']); $email = array('email' => sanitize_email($_POST['et_email'])); $firstname = sanitize_text_field($_POST['et_firstname']); if ('' === $firstname) { die(json_encode(array('error' => __('Please enter first name', 'Divi')))); } if (!is_email(sanitize_email($_POST['et_email']))) { die(json_encode(array('error' => __('Incorrect email', 'Divi')))); } if ('' == $list_id) { die(json_encode(array('error' => __('Configuration error: List is not defined', 'Divi')))); } $success_message = __('<h2 class="et_pb_subscribed">Subscribed - look for the confirmation email!</h2>', 'Divi'); switch ($service) { case 'mailchimp': $lastname = sanitize_text_field($_POST['et_lastname']); if (!class_exists('Mailchimp')) { require_once get_template_directory() . '/includes/subscription/mailchimp/Mailchimp.php'; } $mailchimp_api_key = et_get_option('divi_mailchimp_api_key'); if ('' === $mailchimp_api_key) { die(json_encode(array('error' => __('Configuration error: api key is not defined', 'Divi')))); } try { $mailchimp = new Mailchimp($mailchimp_api_key); $mailchimp_lists = new Mailchimp_Lists($mailchimp); $merge_vars = array('FNAME' => $firstname, 'LNAME' => $lastname); $retval = $mailchimp_lists->subscribe($list_id, $email, $merge_vars); $result = json_encode(array('success' => $success_message)); } catch (Exception $e) { if ($e == 'List_AlreadySubscribed') { $error_code = $e->code; } if ($error_code = '214') { $error_message = str_replace('Click here to update your profile.', '', $e->getMessage()); $result = json_encode(array('success' => $error_message)); } else { $result = json_encode(array('success' => $e->getMessage())); } } die($result); break; case 'aweber': if (!class_exists('AWeberAPI')) { require_once get_template_directory() . '/includes/subscription/aweber/aweber_api.php'; } $account = et_pb_get_aweber_account(); try { $list_url = "/accounts/{$account->id}/lists/{$list_id}"; $list = $account->loadFromUrl($list_url); $new_subscriber = $list->subscribers->create(array('email' => $email, 'name' => $firstname)); echo $success_message; } catch (Exception $exc) { die($exc); } break; } die; }
/** * Get Mailchimp group ID group name */ public static function getMailchimpGroupIdFromName($listID, $groupName) { CRM_Mailchimp_Utils::checkDebug('Start-CRM_Mailchimp_Utils getMailchimpGroupIdFromName $listID', $listID); CRM_Mailchimp_Utils::checkDebug('Start-CRM_Mailchimp_Utils getMailchimpGroupIdFromName $groupName', $groupName); if (empty($listID) || empty($groupName)) { return NULL; } $mcLists = new Mailchimp_Lists(CRM_Mailchimp_Utils::mailchimp()); try { $results = $mcLists->interestGroupings($listID); } catch (Exception $e) { return NULL; } foreach ($results as $grouping) { foreach ($grouping['groups'] as $group) { if ($group['name'] == $groupName) { CRM_Mailchimp_Utils::checkDebug('End-CRM_Mailchimp_Utils getMailchimpGroupIdFromName= ', $group['id']); return $group['id']; } } } }
} } } return false; } public function castError($result) { if ($result['status'] !== 'error' || !$result['name']) { throw new Mailchimp_Error('We received an unexpected error: ' . json_encode($result)); } $class = isset(self::$error_map[$result['name']]) ? self::$error_map[$result['name']] : 'Mailchimp_Error'; return new $class($result['error'], $result['code']); } public function log($msg) { if ($this->debug) { error_log($msg); } } } $form = $_POST; if (!empty($form['email']) && !empty($form['city'])) { $mailchimp = new Mailchimp(MAILCHIMP_API_KEY); $lists = new Mailchimp_Lists($mailchimp); $email = ['email' => $form['email']]; $merge = [MAILCHIMP_CITY_TAG => $form['city']]; $lists->subscribe(MAILCHIMP_LIST_ID, $email, $merge, 'html', false); echo 'Newsletter assinada!'; } else { echo 'Por favor preencha os campos. <a href="newsletter.php">Voltar</a>'; }
$socialLoginObject = new SocialLoginAPI(LR_API_KEY, LR_API_SECRET, array('authentication' => false, 'output_format' => 'json')); $accesstoken = $socialLoginObject->exchangeAccessToken($request_token['token']); //$request_token loginradius token get from social/traditional interface after success authentication. $accesstoken = $accesstoken->access_token; $userProfileData = $socialLoginObject->getUserProfiledata($accesstoken); if (!empty($userProfileData->Email)) { $responseArr = ['status' => "success", "msg" => "Successfully logged in"]; /* * Call MailChimp here */ $userData = ['FNAME' => $userProfileData->FirstName, 'LNAME' => $userProfileData->LastName]; foreach ($userProfileData->Email as $email) { $userData['EMAIL'] = $email->Value; } $mailChimpObj = new Mailchimp(MAILCHIMP_API_KEY); $mailChimpListsObj = new Mailchimp_Lists($mailChimpObj); //(MAILCHIMP_API_KEY); $allList = $mailChimpListsObj->getList(); if (intval($allList["total"]) >= 1) { $subscriberListId = null; foreach ($allList['data'] as $lists) { if (stristr($lists['name'], "test")) { $subscriberListId = $lists['id']; } if (!empty($subscriberListId)) { break; } } if (!empty($subscriberListId)) { foreach ($userProfileData->Email as $email) { try {
function run() { $my_key = CRM_Core_BAO_Setting::getItem(self::MC_SETTING_GROUP, 'security_key', NULL, FALSE); CRM_Mailchimp_Utils::checkDebug('CRM_Mailchimp_Page_WebHook run $my_key= ', $my_key); if (CRM_Core_Config::singleton()->userPermissionClass->isModulePermissionSupported() && !CRM_Mailchimp_Permission::check('allow webhook posts')) { CRM_Core_Error::fatal(); } // Check the key // @todo is this a DOS attack vector? seems a lot of work for saying 403, go away, to a robot! if (!isset($_GET['key']) || $_GET['key'] != $my_key) { CRM_Core_Error::fatal(); } if (!empty($_POST['data']['list_id']) && !empty($_POST['type'])) { $requestType = $_POST['type']; $requestData = $_POST['data']; // Return if API is set in webhook setting for lists $list = new Mailchimp_Lists(CRM_Mailchimp_Utils::mailchimp()); $webhookoutput = $list->webhooks($requestData['list_id']); if ($webhookoutput[0]['sources']['api'] == 1) { CRM_Mailchimp_Utils::checkDebug('CRM_Mailchimp_Page_WebHook run API is set in Webhook setting for listID', $requestData['list_id']); return; } switch ($requestType) { case 'subscribe': case 'unsubscribe': case 'profile': // Create/Update contact details in CiviCRM $delay = $requestType == 'profile'; $contactID = CRM_Mailchimp_Utils::updateContactDetails($requestData['merges'], $delay); $contactArray = array($contactID); // Subscribe/Unsubscribe to related CiviCRM groups self::manageCiviCRMGroupSubcription($contactID, $requestData, $requestType); CRM_Mailchimp_Utils::checkDebug('Start - CRM_Mailchimp_Page_WebHook run $_POST= ', $_POST); CRM_Mailchimp_Utils::checkDebug('Start - CRM_Mailchimp_Page_WebHook run $contactID= ', $contactID); CRM_Mailchimp_Utils::checkDebug('Start - CRM_Mailchimp_Page_WebHook run $requestData= ', $requestData); CRM_Mailchimp_Utils::checkDebug('Start - CRM_Mailchimp_Page_WebHook run $requestType= ', $requestType); break; case 'upemail': // Mailchimp Email Update event // Try to find the email address $email = new CRM_Core_BAO_Email(); $email->get('email', $requestData['old_email']); CRM_Mailchimp_Utils::checkDebug('CRM_Mailchimp_Page_WebHook run- case upemail $requestData[old_email]= ', $requestData['old_email']); // If the Email was found. if (!empty($email->contact_id)) { $email->email = $requestData['new_email']; $email->save(); CRM_Mailchimp_Utils::checkDebug('CRM_Mailchimp_Page_WebHook run- case upemail inside condition $requestData[new_email]= ', $requestData['new_email']); } break; case 'cleaned': // Try to find the email address $email = new CRM_Core_BAO_Email(); $email->get('email', $requestData['email']); CRM_Mailchimp_Utils::checkDebug('CRM_Mailchimp_Page_WebHook run - case cleaned $requestData[new_email]= ', $requestData['email']); // If the Email was found. if (!empty($email->contact_id)) { $email->on_hold = 1; $email->holdEmail($email); $email->save(); CRM_Mailchimp_Utils::checkDebug('CRM_Mailchimp_Page_WebHook run - case cleaned inside condition $email= ', $email); CRM_Mailchimp_Utils::checkDebug('CRM_Mailchimp_Page_WebHook run - case cleaned inside condition $requestData[new_email]= ', $requestData['email']); } break; default: // unhandled webhook CRM_Mailchimp_Utils::checkDebug('End- CRM_Mailchimp_Page_WebHook run $contactID= ', $contactID); CRM_Mailchimp_Utils::checkDebug('End- CRM_Mailchimp_Page_WebHook run $requestData= ', $requestData); CRM_Mailchimp_Utils::checkDebug('End- CRM_Mailchimp_Page_WebHook run $requestType= ', $requestType); CRM_Mailchimp_Utils::checkDebug('End - CRM_Mailchimp_Page_WebHook run $email= ', $email); } } // Return the JSON output header('Content-type: application/json'); $data = NULL; // We should ideally throw some status print json_encode($data); CRM_Utils_System::civiExit(); }
/** * Mailchimp Get all Mailchimp Lists & Groups API * * @param array $params * @return array API result descriptor * @see civicrm_api3_create_success * @see civicrm_api3_create_error * @throws API_Exception */ function civicrm_api3_mailchimp_getlistsandgroups($params) { $mcLists = new Mailchimp_Lists(CRM_Mailchimp_Utils::mailchimp()); $results = $mcLists->getList(); $lists = array(); foreach ($results['data'] as $list) { $lists[$list['id']]['name'] = $list['name']; $lists[$list['id']]['id'] = $list['id']; $params = array('id' => $list['id']); $group_results = civicrm_api3_mailchimp_getgroups($params); if (!empty($group_results)) { $lists[$list['id']]['grouping'] = $group_results['values']; } } return civicrm_api3_create_success($lists); }
static function subscribeOrUnsubsribeToMailchimpList($groupDetails, $contactID, $action) { CRM_Mailchimp_Utils::checkDebug('Start-CRM_Mailchimp_Utils subscribeOrUnsubsribeToMailchimpList $groupDetails', $groupDetails); CRM_Mailchimp_Utils::checkDebug('Start-CRM_Mailchimp_Utils subscribeOrUnsubsribeToMailchimpList $contactID', $contactID); CRM_Mailchimp_Utils::checkDebug('Start-CRM_Mailchimp_Utils subscribeOrUnsubsribeToMailchimpList $action', $action); if (empty($groupDetails) || empty($contactID) || empty($action)) { return NULL; } // We need to get contact's email before subscribing in Mailchimp $contactParams = array('version' => 3, 'id' => $contactID); $contactResult = civicrm_api('Contact', 'get', $contactParams); // This is the primary email address of the contact $email = $contactResult['values'][$contactID]['email']; if (empty($email)) { // Its possible to have contacts in CiviCRM without email address // and add to group offline return; } // Optional merges for the email (FNAME, LNAME) $merge = array('FNAME' => $contactResult['values'][$contactID]['first_name'], 'LNAME' => $contactResult['values'][$contactID]['last_name']); $listID = $groupDetails['list_id']; $grouping_id = $groupDetails['grouping_id']; $group_id = $groupDetails['group_id']; if (!empty($grouping_id) and !empty($group_id)) { $merge_groups[$grouping_id] = array('id' => $groupDetails['grouping_id'], 'groups' => array()); $merge_groups[$grouping_id]['groups'][] = CRM_Mailchimp_Utils::getMCGroupName($listID, $grouping_id, $group_id); // remove the significant array indexes, in case Mailchimp cares. $merge['groupings'] = array_values($merge_groups); } // Send Mailchimp Lists API Call. $list = new Mailchimp_Lists(CRM_Mailchimp_Utils::mailchimp()); switch ($action) { case "subscribe": // http://apidocs.mailchimp.com/api/2.0/lists/subscribe.php try { $result = $list->subscribe($listID, array('email' => $email), $merge, $email_type = 'html', $double_optin = FALSE, $update_existing = FALSE, $replace_interests = TRUE, $send_welcome = FALSE); } catch (Exception $e) { // Don't display if the error is that we're already subscribed. $message = $e->getMessage(); if ($message !== $email . ' is already subscribed to the list.') { CRM_Core_Session::setStatus($message); } } break; case "unsubscribe": // https://apidocs.mailchimp.com/api/2.0/lists/unsubscribe.php try { $result = $list->unsubscribe($listID, array('email' => $email), $delete_member = false, $send_goodbye = false, $send_notify = false); } catch (Exception $e) { CRM_Core_Session::setStatus($e->getMessage()); } break; } CRM_Mailchimp_Utils::checkDebug('End-CRM_Mailchimp_Utils subscribeOrUnsubsribeToMailchimpList $groupDetails', $groupDetails); CRM_Mailchimp_Utils::checkDebug('End-CRM_Mailchimp_Utils subscribeOrUnsubsribeToMailchimpList $contactID', $contactID); CRM_Mailchimp_Utils::checkDebug('End-CRM_Mailchimp_Utils subscribeOrUnsubsribeToMailchimpList $action', $action); }
public function createUserNewsletter($email) { try { $sql = "INSERT INTO " . $this->_TABLES['public']['UserNewsletter'] . " (email) VALUES (:email)"; $req = $this->bdd->prepare($sql); $req->bindValue('email', $email, PDO::PARAM_STR); $req->execute(); } catch (PDOException $e) { error_log($sql); error_log($e->getMessage()); die; } $Mailchimp = new Mailchimp($this->config->mailchimp->config->api_key); $Mailchimp_Lists = new Mailchimp_Lists($Mailchimp); $subscriber = $Mailchimp_Lists->subscribe($this->config->mailchimp->list->lid, array('email' => $email)); if (!empty($subscriber['leid'])) { error_log("Subscribe Mailchimp success"); } else { error_log("Subscribe Mailchimp fail"); } }
/** * CiviCRM to Mailchimp Sync * * @param array $params * @return array API result descriptor * @see civicrm_api3_create_success * @see civicrm_api3_create_error * @throws API_Exception */ function civicrm_api3_mailchimp_sync($params) { $groups = CRM_Mailchimp_Utils::getGroupsToSync(array(), null, $membership_only = TRUE); foreach ($groups as $group_id => $details) { $list = new Mailchimp_Lists(CRM_Mailchimp_Utils::mailchimp()); $webhookoutput = $list->webhooks($details['list_id']); if ($webhookoutput[0]['sources']['api'] == 1) { return civicrm_api3_create_error('civicrm_api3_mailchimp_sync - API is set in Webhook setting for listID ' . $details['list_id'] . ' Please uncheck API'); } } $result = $pullResult = array(); // Do pull first from mailchimp to CiviCRM $pullRunner = CRM_Mailchimp_Form_Pull::getRunner($skipEndUrl = TRUE); if ($pullRunner) { $pullResult = $pullRunner->runAll(); } // Do push from CiviCRM to mailchimp $runner = CRM_Mailchimp_Form_Sync::getRunner($skipEndUrl = TRUE); if ($runner) { $result = $runner->runAll(); } if ($pullResult['is_error'] == 0 && $result['is_error'] == 0) { return civicrm_api3_create_success(); } else { return civicrm_api3_create_error(); } }
/** * Batch update Mailchimp with new contacts that need to be subscribed, or have changed data. * * This also does the clean-up tasks of removing the temporary tables. */ static function syncPushAdd(CRM_Queue_TaskContext $ctx, $listID) { CRM_Mailchimp_Utils::checkDebug('Start-CRM_Mailchimp_Form_Sync syncPushAdd $ctx= ', $ctx); CRM_Mailchimp_Utils::checkDebug('Start-CRM_Mailchimp_Form_Sync syncPushAdd $listID= ', $listID); // @todo take the remaining details from tmp_mailchimp_push_c // and construct a batchUpdate (do they need to be batched into 1000s? I can't recal). $dao = CRM_Core_DAO::executeQuery("SELECT * FROM tmp_mailchimp_push_c;"); $stats = array(); // Loop the $dao object to make a list of emails to subscribe/update $batch = array(); while ($dao->fetch()) { $merge = array('FNAME' => $dao->first_name, 'LNAME' => $dao->last_name); // set the groupings. $groupings = unserialize($dao->groupings); // this is a array(groupingid=>array(groupid=>bool membership)) $merge_groups = array(); foreach ($groupings as $grouping_id => $groups) { // CRM_Mailchimp_Utils::checkDebug('get groups $groups= ', $groups); $merge_groups[$grouping_id] = array('id' => $grouping_id, 'groups' => array()); CRM_Mailchimp_Utils::checkDebug('End-CRM_Mailchimp_Form_Sync $merge_groups[$grouping_id]', $merge_groups[$grouping_id]); foreach ($groups as $group_id => $is_member) { if ($is_member) { $merge_groups[$grouping_id]['groups'][] = CRM_Mailchimp_Utils::getMCGroupName($listID, $grouping_id, $group_id); } } } // remove the significant array indexes, in case Mailchimp cares. $merge['groupings'] = array_values($merge_groups); $batch[] = array('email' => array('email' => $dao->email), 'email_type' => 'html', 'merge_vars' => $merge); $stats[$listID]['added']++; } if (!$batch) { // Nothing to do return CRM_Queue_Task::TASK_SUCCESS; } // Log the batch subscribe details CRM_Core_Error::debug_var('Mailchimp syncPushAdd batchUnsubscribe $listID= ', $listID); CRM_Core_Error::debug_var('Mailchimp syncPushAdd batchSubscribe $batch= ', $batch); // Send Mailchimp Lists API Call. // http://apidocs.mailchimp.com/api/2.0/lists/batch-subscribe.php $list = new Mailchimp_Lists(CRM_Mailchimp_Utils::mailchimp()); $result = $list->batchSubscribe($listID, $batch, $double_optin = FALSE, $update = TRUE, $replace_interests = TRUE); // debug: file_put_contents(DRUPAL_ROOT . '/logs/' . date('Y-m-d-His') . '-MC-push.log', print_r($result,1)); CRM_Mailchimp_Utils::checkDebug('CRM_Mailchimp_Form_Sync syncPushAdd $result= ', $result); $get_GroupId = CRM_Mailchimp_Utils::getGroupsToSync(array(), $listID); CRM_Mailchimp_Utils::checkDebug('$get_GroupId= ', $get_GroupId); // @todo check result (keys: error_count, add_count, update_count) $stats[$listID]['group_id'] = array_keys($get_GroupId); $stats[$listID]['error_count'] = $result['error_count']; $stats[$listID]['error_details'] = $result['errors']; static::updatePushStats($stats); // Finally, finish up by removing the two temporary tables CRM_Core_DAO::executeQuery("DROP TABLE tmp_mailchimp_push_m;"); CRM_Core_DAO::executeQuery("DROP TABLE tmp_mailchimp_push_c;"); CRM_Mailchimp_Utils::checkDebug('get groupsss $grouping_id= ', $grouping_id); CRM_Mailchimp_Utils::checkDebug('get groupssss $group_id= ', $group_id); CRM_Mailchimp_Utils::checkDebug('End-CRM_Mailchimp_Form_Sync syncPushAdd $result= ', $result); CRM_Mailchimp_Utils::checkDebug('End-CRM_Mailchimp_Form_Sync syncPushAdd $ctx= ', $ctx); CRM_Mailchimp_Utils::checkDebug('End-CRM_Mailchimp_Form_Sync syncPushAdd $listID= ', $listID); return CRM_Queue_Task::TASK_SUCCESS; }
<?php $api_key = "287b468abb599876d73131fc750d0baa-us9"; $list_id = "148b3facc9"; require 'Mailchimp.php'; $Mailchimp = new Mailchimp($api_key); $Mailchimp_Lists = new Mailchimp_Lists($Mailchimp); $subscriber = $Mailchimp_Lists->subscribe($list_id, array('email' => htmlentities($_POST['emailsuscripcion']))); if (!empty($subscriber['leid'])) { echo "success"; } else { echo "fail"; }
<?php $api_key = "b730af8a90fd17c7ff8dbfebdd896745-us11"; $list_id = "32c9514d22"; require 'Mailchimp.php'; $Mailchimp = new Mailchimp($api_key); $Mailchimp_Lists = new Mailchimp_Lists($Mailchimp); $subscriber = $Mailchimp_Lists->subscribe($list_id, array('email' => htmlentities($_POST['email']), 'merge_vars' => array('FNAME' => 'Davy', 'LNAME' => 'Jones'))); if (!empty($subscriber['leid'])) { echo "success"; } else { echo "fail"; }
public function postSubscribe() { $cre = ['email' => Input::get('email')]; $rules = ['email' => 'required|email']; $validator = Validator::make($cre, $rules); if ($validator->passes()) { include app_path() . '/includes/Mailchimp.php'; $api_key = "caeff30696120d96d875bd3cfbc2b890-us10"; $list_id = "80bbc474a1"; // set up our mailchimp object, and list object $Mailchimp = new Mailchimp($api_key); $Mailchimp_Lists = new Mailchimp_Lists($Mailchimp); $email = Input::get('email'); try { $subscriber = $Mailchimp_Lists->subscribe($list_id, array('email' => $email)); } catch (Exception $e) { $response["success"] = false; $response["message"] = "can not add to list"; } if (!empty($subscriber['leid'])) { $response["success"] = true; $response["message"] = "You have successfully subscribed to CorperLife"; } } else { $response["success"] = false; $response["message"] = "Please fill a valid email"; } return json_encode($response); }
function mailchimp_subscribe() { $ret = array('success' => false, 'message' => ''); $email = isset($_POST['mailchimp_email']) ? trim($_POST['mailchimp_email']) : ''; $nonce = isset($_POST['_wpnonce']) ? trim($_POST['_wpnonce']) : ''; $mc_api_key = null; $mc_list_id = null; $error_message = ''; $widget_id = isset($_POST['widget_id']) ? trim($_POST['widget_id']) : ''; if ($widget_settings = $this->get_widget_settings($widget_id)) { $mc_api_key = isset($widget_settings['mailchimp_api_key']) ? $widget_settings['mailchimp_api_key'] : null; $mc_list_id = isset($widget_settings['mailchimp_list_id']) ? $widget_settings['mailchimp_list_id'] : null; $error_message = isset($widget_settings['error_message']) ? $widget_settings['error_message'] : ''; $double_optin = !empty($widget_settings['mailchimp_double_optin']) ? true : false; } if ($email && $widget_settings && $mc_api_key != null && $mc_list_id != null && wp_verify_nonce($nonce, 'wp-subscribe-mailchimp')) { try { $list = new Mailchimp_Lists(new Mailchimp($mc_api_key)); $resp = $list->subscribe($mc_list_id, array('email' => $email), null, 'html', (bool) $double_optin, true); if ($resp) { $ret['success'] = true; $ret['message'] = $widget_settings['success_message']; } else { $ret['message'] = $widget_settings['error_message']; } } catch (Exception $ex) { $ret['message'] = $widget_settings['error_message']; } } else { $ret['message'] = $error_message; } return $ret; }
function sendMailchimp($formData, $config) { $validated = GUMP::is_valid($formData, array('newsletter-name' => 'required', 'newsletter-email' => 'required|valid_email')); if ($validated === true) { $Mailchimp = new Mailchimp($config['mailchimp_api_key']); $Mailchimp_Lists = new Mailchimp_Lists($Mailchimp); $email = $formData['newsletter-email']; //replace with a test email $name = $formData['newsletter-name']; //replace with a test email try { $subscriber = $Mailchimp_Lists->subscribe($config['mailchimp_list_id'], array('email' => $email, 'name' => $name)); //pass the list id and email to mailchimp } catch (Exception $e) { $result = array('result' => 'error', 'msg' => $e->getMessage()); return json_encode($result); } // check that we've succeded if (!empty($subscriber['leid'])) { $result = array('result' => 'success', 'msg' => array('Success! Thank you for signing up to our newsletter.')); return json_encode($result); } } else { $result = array('result' => 'error', 'msg' => $validated); return json_encode($result); } }
<?php $api_key = "e5d1d4797a2c82813cc7cf1b1ca8e6b3-us13"; $list_id = "5148a8524e"; require 'MailChimp.php'; $Mailchimp = new Mailchimp($api_key); $Mailchimp_Lists = new Mailchimp_Lists($Mailchimp); $merge_vars = array('FNAME' => 'Zelel', 'LNAME' => 'Quentin'); $subscriber = $Mailchimp_Lists->subscribe($list_id, array('email' => htmlentities($_POST['email'])), $merge_vars, 'html', true, true, true, false); if (!empty($subscriber['leid'])) { echo "success"; } else { echo "fail"; }
function userSubscribe() { $formDetails = $_REQUEST['formDetails']; $userEmail = $formDetails['subscribeEmail']; $api_key = '2b9d521c86de7f2ae79618eaffd95947-us10'; $list_id = 'cd7b3dcefe'; $Mailchimp = new Mailchimp($api_key); $Mailchimp_Lists = new Mailchimp_Lists($Mailchimp); $subscriber = $Mailchimp_Lists->subscribe($list_id, array('email' => htmlentities($userEmail))); if (!empty($subscriber['leid'])) { $result = 1; } else { $result = 0; } $result = json_encode($result, TRUE); echo $result; die; }
<?php $api_key = "782b1ee199207e065daa9dcb0a2ce38e-us11"; $list_id = "b0d209edc3"; require './Mailchimp.php'; $Mailchimp = new Mailchimp($api_key); $Mailchimp_Lists = new Mailchimp_Lists($Mailchimp); $subscriber = $Mailchimp_Lists->subscribe($list_id, array('email' => $_POST['email'])); if (!empty($subscriber['leid'])) { echo "success"; } else { echo "fail"; }