/** * Record sales on InfusionSoft */ private function _infusion_sales($product, $plan, $email, $first_name, $last_name, $affiliate_id, $paid_amount = NULL) { // Add or Get buyer from InfusionSoft require_once app_path() . "/libraries/infusionsoft/isdk.php"; // Add InfusionSoft Library $isapp = new iSDK(); // Create Connection if ($isapp->cfgCon("comissionTracker")) { // find contact by email $contacts = $isapp->findByEmail($email, array('Id', 'Email')); // If contact found if (!empty($contacts[0]['Id'])) { $contact_id = $contacts[0]['Id']; } else { // Create new contact $contactData = array('Email' => $email, 'FirstName' => $first_name, 'LastName' => $last_name); $contact_id = $isapp->addCon($contactData); } // Sets current date $currentDate = date("d-m-Y"); $oDate = $isapp->infuDate($currentDate); // Creates blank order $newOrder = $isapp->blankOrder($contact_id, "{$product->name} - {$plan->name} ({$contact_id})", $oDate, NULL, $affiliate_id); // Add Order Item - Product ID // type = 4 or 9 (Product or Subscription) $infusion_product_type = $product->type == 1 ? 4 : 9; if ($paid_amount === NULL or $paid_amount === '') { $paid_amount = $plan->price; } $orderPrice = $paid_amount; //$paid_amount ? $paid_amount : $plan->price; $orderPrice = floatval(round($orderPrice, 2)); $result = $isapp->addOrderItem($newOrder, $plan->infusion_id, $infusion_product_type, $orderPrice, 1, "Sales Made From DK Solution", "Generated Through API"); // Add Manual Payment - since CC charged with Stripe $payment = $isapp->manualPmt($newOrder, $orderPrice, $oDate, "Credit Card", "Payment via DK Solution", false); //credit // Add Affiliate in our database if ($affiliate_id) { // Get Affiliate $affiliate = Affiliate::find($affiliate_id); if (!$affiliate or empty($affiliate->email)) { $affData = $isapp->dsFind('Affiliate', 1, 0, 'Id', $affiliate_id, array('AffName', 'ContactId')); } if (!$affiliate) { $affName = !empty($affData[0]['AffName']) ? $affData[0]['AffName'] : NULL; // Save Affiliate name $affiliate = new Affiliate(); $affiliate->id = $affiliate_id; $affiliate->name = $affName; $affiliate->save(); } if ($affiliate and empty($affiliate->email)) { $affContactId = !empty($affData[0]['ContactId']) ? $affData[0]['ContactId'] : NULL; if ($affContactId) { $affContactData = $isapp->dsFind('Contact', 1, 0, 'Id', $affContactId, array('Email')); $affEmail = !empty($affContactData[0]['Email']) ? $affContactData[0]['Email'] : NULL; $affiliate->email = $affEmail; $affiliate->save(); } } // Send Commission Email to Affiliate if ($affiliate->email) { // Get earned commission $from = strtotime("midnight", time()); $to = strtotime("tomorrow", time()) - 1; $start = date('Ymd\\TH:i:s', $from); $finish = date('Ymd\\TH:i:s', $to); $commissions = $isapp->affCommissions($affiliate->id, $start, $finish); if (!empty($commissions) and is_array($commissions)) { foreach ($commissions as $commission) { if ($commission['InvoiceId'] == $newOrder) { $AffEarnedCommission = $commission['AmtEarned']; } } } // Send email to Affiliate if (!empty($AffEarnedCommission)) { $this->_send_email_commission($product->name, $plan->name, $affiliate->email, $affiliate->name, $AffEarnedCommission); } } } return $newOrder; } else { // Error // echo "Connection Failed"; return FALSE; } }
public function getClient() { if (null === $this->client) { $this->client = new iSDK(); $this->client->cfgCon($this->accountId, $this->apiKey); } return $this->client; }
public static function donation_button_infusionsoft_handler($posted) { $is_api_key = get_option("infusionsoft_api_key"); $app_name = get_option("infusionsoft_api_app_name"); $is_list_id = get_option("infusionsoft_lists"); $fname = isset($posted['first_name']) ? $posted['first_name'] : ''; $lname = isset($posted['last_name']) ? $posted['last_name'] : ''; $email = isset($posted['payer_email']) ? $posted['payer_email'] : $posted['receiver_email']; $debug = get_option('log_enable_infusionsoft') == 'yes' ? 'yes' : 'no'; if ('yes' == $debug) { $log = new Donation_Button_Logger(); } if (isset($is_api_key) && !empty($is_api_key) && (isset($app_name) && !empty($app_name)) && (isset($is_list_id) && !empty($is_list_id))) { include_once DBP_PLUGIN_DIR_PATH . '/admin/partials/lib/infusionsoft/isdk.php'; $app = new iSDK(); try { if ($app->cfgCon($app_name, $is_api_key)) { $contactid = $app->addCon(array('FirstName' => $fname, 'LastName' => $lname, 'Email' => $email)); $infusionsoft_result = $app->campAssign($contactid, $is_list_id); if ('yes' == $debug) { $log->add('Infusionsoft', print_r($infusionsoft_result, true)); } } } catch (Exception $e) { if ('yes' == $debug) { $log->add('Infusionsoft', print_r($e, true)); } } } }
/** * Subscribes to Infusionsoft list. Returns either "success" string or error message. * @return string */ function subscribe_infusionsoft($api_key, $app_id, $list_id, $email, $name = '', $last_name = '') { if (!function_exists('curl_init')) { return __('curl_init is not defined ', 'rapidology'); } if (!class_exists('iSDK')) { require_once RAD_RAPIDOLOGY_PLUGIN_DIR . 'subscription/infusionsoft/isdk.php'; } try { $infusion_app = new iSDK(); $infusion_app->cfgCon($app_id, $api_key, 'throw'); } catch (iSDKException $e) { $error_message = $e->getMessage(); } $contact_details = array('FirstName' => $name, 'LastName' => $last_name, 'Email' => $email); $new_contact_id = $infusion_app->addWithDupCheck($contact_details, $checkType = 'Email'); $infusion_app->optIn($contact_details['Email']); $response = $infusion_app->grpAssign($new_contact_id, $list_id); if ($response) { $error_message = 'success'; } else { $error_message = esc_html__('Already In List', 'rapidology'); } return $error_message; }
public function register(Application $app) { $app['isdk'] = $app->share(function () use($app) { $isdk = new \iSDK(); $isdk->cfgCon($app['isdk.appName'], $app['isdk.key']); return $isdk; }); }
public function getTest() { //require_once app_path() . DIRECTORY_SEPARATOR . ""; require_once app_path() . "/libraries/infusionsoft/isdk.php"; $isapp = new iSDK(); // Get Affiliate ID from Cookie $affiliate_id = Cookie::get('_dks_isa'); // Create Connection if ($isapp->cfgCon("comissionTracker")) { // find contact by email $contacts = $isapp->findByEmail('*****@*****.**', array('Id', 'Email')); // If contact found if (!empty($contacts[0]['Id'])) { $contact_id = $contacts[0]['Id']; } else { // Create new contact $contactData = array('Email' => '*****@*****.**'); $contact_id = $isapp->addCon($contactData); } echo $contact_id; echo "<br><br>"; // Testing Order Through Invoice //Sets current date $currentDate = date("d-m-Y"); $oDate = $isapp->infuDate($currentDate); echo "date set<br/>"; //Creates blank order $newOrder = $isapp->blankOrder($contact_id, "New Order for Contact {$contact_id}", $oDate, NULL, $affiliate_id); echo "newOrder=" . $newOrder . "<br/>"; //$newOrder = 710; // Add Order Item - Product ID // type = 4 or 9 (Product or Subscription) $result = $isapp->addOrderItem($newOrder, 24, 4, 50.0, 1, "Sale Made From API", "Generated Through API"); echo "item added<br/>"; //print_r($result); // Add Manual Payment - since CC charged with Stripe $payment = $isapp->manualPmt($newOrder, 50.0, $oDate, "credit", "Order done through API / Stripe", false); print_r($payment); } else { echo "Connection Failed"; } //$affiliate_id = Cookie::get('_dks_isa'); //echo "hi " . app_path(); }
/** * Total paid to affiliates */ public function paidToAffiliates() { return "0"; $from = strtotime("midnight", strtotime($this->_search_params['from'])); $to = strtotime("tomorrow", strtotime($this->_search_params['to'])) - 1; if ($this->_search_params['affiliate'] and $this->_search_params['affiliate'] != "no-affiliate") { $cache_key = "paidToAffiliates_" . $from . "_" . $to . "_" . $this->_search_params['affiliate']; } else { $cache_key = "paidToAffiliates_" . $from . "_" . $to; } if (Cache::has($cache_key)) { return Cache::get($cache_key); } $amount = 0; $start = date('Ymd\\TH:i:s', $from); $finish = date('Ymd\\TH:i:s', $to); // Get all affilaites from DK DB $affiliates = Affiliate::get(); // Add InfusionSoft Library require_once app_path() . "/libraries/infusionsoft/isdk.php"; $isapp = new iSDK(); // Create Connection if ($isapp->cfgCon("comissionTracker")) { if ($this->_search_params['affiliate'] and $this->_search_params['affiliate'] != "no-affiliate") { $pays = $isapp->affPayouts($this->_search_params['affiliate'], $start, $finish); foreach ($pays as $payout) { $amount = $amount + $payout['PayAmt']; } } else { foreach ($affiliates as $affiliate) { $affiliateId = $affiliate->id; $pays = $isapp->affPayouts($affiliateId, $start, $finish); foreach ($pays as $payout) { $amount = $amount + $payout['PayAmt']; } } } } $amount = number_format($amount); Cache::put($cache_key, $amount, 10); return $amount; }
//*================= //* INCLUDES //*================= //INFUSIONSOFT include 'includes/isdk.php'; //WISHLISTMEMBER include '../members/wp-config.php'; include '../members/wp-includes/pluggable.php'; //*================= //*================= //* CONFIGURATION //*================= //INFUSIONSOFT $connInfo = array('main:mojo:i:679c2a2a6aef93984f48e3ec4794db26:Mojo Video'); $infusion = new iSDK(); $infusion->cfgCon("main"); //*================= //* WISHLIST //*================= //WISHLISTMEMBER $wishlist = new wlmapiclass('http://www.mojoleadmastery.com/members', 'LXbfqw59CFNUWaexLXbfqw59CFNUWaex'); $wishlist->return_format = 'php'; // <- value can also be xml or json //*=============================== //* GET USER INFORMATION FROM IS //*=============================== $returnFields = array('contactId'); $query = array('Id' => $order_id); $contacts = $infusion->dsQuery("Job", 1, 0, $query, $returnFields); $fields = array('FirstName', 'LastName', 'Email', 'Phone1', 'Company', 'Username', 'Password'); $IS_DATA = $infusion->loadCon($contacts[0]['contactId'], $fields);
{ return number_format(round($value * 20, 0) / 20, 2, '.', ''); } $_SESSION['hargaLG'] = $hargaLG; $_SESSION['hargaKB'] = $hargaKB; $_SESSION['hargaXS'] = $hargaXS; $_SESSION['hargaXST'] = $hargaXST; $_SESSION['hargaMT'] = $hargaMT; $_SESSION['pos'] = $pos; $_SESSION['posDiskaun'] = $posDiskaun; $_SESSION['jumlah'] = $jumlah; if ($_SESSION['details']['Id']) { if (!$app) { require "iSDK/isdk.php"; $app = new iSDK(); $app->cfgCon("mtouch"); } if ($kuantitiXS > 0) { $action = $app->runAS($_SESSION['details']['Id'], 288); } if ($kuantitiXST > 0) { $action = $app->runAS($_SESSION['details']['Id'], 535); } if ($kuantitiKB > 0) { $action = $app->runAS($_SESSION['details']['Id'], 203); } if ($kuantitiLG > 0) { $action = $app->runAS($_SESSION['details']['Id'], 201); } if ($kuantitiMT == 1) { $action = $app->runAS($_SESSION['details']['Id'], 137);
<?php //include the SDK require_once "../../src/isdk.php"; //build our application object $app = new iSDK(); //connect to the API - change demo to be whatever your connectionName is! if ($app->cfgCon("demo")) { //action set Id number to run on the posted contact $actionId = 123; //grab our posted contact fields $contact = array('Email' => $_POST['Contact0Email'], 'FirstName' => $_POST['Contact0FirstName'], 'LastName' => $_POST['Contact0LastName']); //grab the returnURL $returnURL = $_POST['returnURL']; //dup check on email if it exists. if (!empty($contact['Email'])) { //check for existing contact; $returnFields = array('Id'); $dups = $app->findByEmail($contact['Email'], $returnFields); if (!empty($dups)) { //update contact $app->updateCon($dups[0]['Id'], $contact); //run an action set on the contact $app->runAS($dups[0]['Id'], $actionId); } else { //Add new contact $newCon = $app->addCon($contact); //run an action set on the contact $app->runAS($newCon, $actionId); } //Send them to the success page
******************************************************************************/ // Include required support files require_once 'Infusionsoft/infusionsoft.php'; require_once 'src/isdk.php'; // Instantiate all required objects $app = new iSDK(); $products = new Infusionsoft_Product(); $orderitems = new Infusionsoft_OrderItem(); $invoices = new Infusionsoft_Invoice(); $invoiceitems = new Infusionsoft_InvoiceItem(); $invoicepayments = new Infusionsoft_InvoicePayment(); $invoiceservice = new Infusionsoft_InvoiceService(); $contact = new Infusionsoft_Contact(); $contactgroup = new Infusionsoft_ContactGroupAssign(); // Global initializations $app->cfgCon('yo243', 'c959c2b28a10eb74a2d5af154ba1986d'); $tName = 'Product'; $query = array('Id' => '%'); $limit = 1000; $page = 0; $rFields = array('ShortDescription'); $count = 0; $prodcount = 0; $concount = 0; $found = false; /****************************************************************************** * * Pre-load all data that is necessary for comparisons to determine if an item * already exists within the Infusionsoft app. * * Example : Load all product id's to compare with products being read so that
$contactId = $_REQUEST['Id']; if ($contactId == "") { die("No contact ID was specified."); } //*================= //* INCLUDES //*================= //INFUSIONSOFT include 'includes/isdk.php'; //*================= //* CONFIGURATION //*================= //INFUSIONSOFT $connInfo = array('main:mojo:i:679c2a2a6aef93984f48e3ec4794db26:Mojo Video'); $app = new iSDK(); $app->cfgCon("main"); //*=============================== //* GET USER INFORMATION FROM IS //*=============================== $fields = array('FirstName', 'LastName', 'Email', 'Phone1', 'Company', '_PlanCode', '_UserId', '_WishListId', '_WishListLevels'); $IS_DATA = $app->loadCon((int) $contactId, $fields); //*============================================== //* CANCEL MOJO VIDEO UNIVERSITY ACCOUNT //* http://mojovideouniversity.com/ //*============================================== //KEY $Secret = "LXbfqw59CFNUWaex"; //PARAMETERS $fxn = 'DeleteUserLevels'; $WishListId = $IS_DATA['_WishListId']; $levels = $IS_DATA['_WishListLevels'];
/** * @param null $id * Cette méthode permet d'editer et d'enregistrer, selon qu'on ait le ID ou pas */ public function admin_edit() { $this->loadModel('Post'); //on charge le model qu'on veut éditer //$this->Post->changeID(); // $d['id']=''; if ($this->request->data) { if ($this->Post->validates($this->request->data)) { $app = new iSDK(); if ($app->cfgCon("connectionName")) { if (isset($this->request->data->PREVENANCE) && $this->request->data->PREVENANCE == 1) { $tags = array(); $tags = explode(',', $this->request->data->TAGS); $newTagData = array('GroupName' => $tags[0], 'GroupCategoryId' => 51); for ($i = 1; $i < count($tags); $i++) { $tn = array('GroupName' => $tags[$i], 'GroupCategoryId' => 51); $app->dsAdd('ContactGroup', $tn); } $tagId = $app->dsAdd('ContactGroup', $newTagData); $this->request->data->TAGS = $tagId; $this->loadModel('Offreancia'); //on charge le controller qu'on veut éditer $this->Offreancia->changeID(); $this->redirect('admin/offreancias/edit/' . $this->Offreancia->save($this->request->data)); } elseif (isset($this->request->data->PREVENANCE) && $this->request->data->PREVENANCE == 2) { $tags = explode(',', $this->request->data->TAGS); $newTagData = array('GroupName' => $tags[0], 'GroupCategoryId' => 49); $tagId = $app->dsAdd('ContactGroup', $newTagData); $this->request->data->TAGS = $tagId; for ($i = 1; $i < count($tags); $i++) { $tn = array('GroupName' => $tags[$i], 'GroupCategoryId' => 49); $tagId = $app->dsAdd('ContactGroup', $tn); } $this->loadModel('Offrelf'); //on charge le controller qu'on veut éditer $this->Offrelf->changeID(); $this->redirect('admin/offrelfs/edit/' . $this->Offrelf->save($this->request->data)); } } else { die("vous n'êtes pas connecté à infusionsoft"); } // die($id=$this->Post->id); //echo("ajouté ou modifié"); $this->Session->setFlash('le contenu a bien été modifié'); } else { $this->Session->setFlash('Merci de corriger vos informations<ul><li>' . implode('<li>', $this->Post->errors) . '</ul>', 'danger'); } } /*if($id){ $id=intval($id); $this->request->data=$this->Post->findOne(array('conditions'=>array('id'=>$id))); $d['id']=$id; }$this->set($d);*/ $this->loadModel('Utilisateur'); $this->Utilisateur->changeID(); $d['utilisateurs'] = $this->Utilisateur->find(array()); $this->loadModel('Client'); $this->Client->changeID(); $d['clients'] = $this->Client->find(array()); $this->set($d); }
* Author : John W. Borelli with The Plan B Club, LLC for Rob Drummond and his * client, Ian Ashland of Ashland Chemicals. * * Inputs : All input is extracted via .csv file reads * * Outputs: All output will be found in the form of resulting data being * imported into the appropriate Infusionsoft app. * ******************************************************************************/ // Include required support files include_once 'EKMConfig.php'; require_once 'Infusionsoft/infusionsoft.php'; require_once 'src/isdk.php'; // Instantiate all required objects $thisapp = new iSDK(); $thisapp->cfgCon($appname, $appkey); $data = new Infusionsoft_DataService(); /*$order=new Infusionsoft_Job(); $order->JobTitle='This is a test order'; $order->ContactId=50005; $order->ShipCity='Phoenix'; $order->ShipFirstName='Joe'; $order->ShipLastName='Blow'; $order->ShipPhone='6026168008'; $order->ShipState='AZ'; $order->ShipStreet1='3825 W Anthem Way #3151'; $order->ShipZip='85086'; $order->save();*/ /* //$order=$thisapp->blankOrder(50005,'This is a test order',$thisapp->infuDate('20151111'),0,0);
/** * Get all the infusionsoft lists for specfic account * * @access public * @return void */ function nnr_new_int_get_infusionsoft_lists_v1() { do_action('nnr_news_int_before_get_infusionsoft_lists_v1'); if (!function_exists('curl_init')) { return __('curl_init is not defined ', 'bloom'); } if (!class_exists('iSDK')) { require_once dirname(dirname(__FILE__)) . '/services/infusionsoft/isdk.php'; } $options = ''; // Make sure the use entered in the api key if (isset($_POST['app_id']) && $_POST['app_id'] != '' && isset($_POST['api_key']) && $_POST['api_key'] != '') { try { $infusion_app = new iSDK(); $infusion_app->cfgCon($_POST['app_id'], $_POST['api_key'], 'throw'); } catch (iSDKException $e) { $error_message = $e->getMessage(); } if (empty($error_message)) { $need_request = true; $page = 0; $all_lists = array(); while (true == $need_request) { $error_message = 'success'; $lists_data = $infusion_app->dsQuery('ContactGroup', 1000, $page, array('Id' => '%'), array('Id', 'GroupName')); $all_lists = array_merge($all_lists, $lists_data); if (1000 > count($lists_data)) { $need_request = false; } else { $page++; } } } // Get all list information if (!empty($all_lists)) { foreach ($all_lists as $list) { if ($_POST['list'] == $list['Id']) { $options .= '<option value="' . $list['Id'] . '" selected="selected">' . $list['GroupName'] . '</option>'; } else { $options .= '<option value="' . $list['Id'] . '">' . $list['GroupName'] . '</option>'; } } } } do_action('nnr_news_int_after_get_infusionsoft_lists_v1'); echo apply_filters('nnr_news_int_get_infusionsoft_lists_v1', $options); die; // this is required to terminate immediately and return a proper response }
//recuperer le dernier élément du tableau qui correspond au niveaux } if (isset($presi_dg)) { $array = explode(',', $presi_dg); //Extraire les éléments séprés par des virgule et les mettre dans un tableau $niveau = $niveau . $array[count($array) - 1] . ", "; //recuperer le dernier élément du tableau qui correspond au niveaux } //pour l'anglais $array = explode(',', $anglais); //Extraire les éléments séprés par des virgule et les mettre dans un tableau $anglais_champs = $anglais_champs . $array[count($array) - 1] . ", "; //recuperer le dernier élément du tableau qui correspond au niveaux //echo "tous les niveaux".utf8_encode($niveau); $app = new iSDK(); if ($app->cfgCon("connectionName")) { if (find_id_by_email($email, $app) != 0) { $exist = true; $contactLeadId = ''; } else { $exist = false; $contactLeadId = 22; } if (is_uploaded_file($_FILES['fichiercv']['tmp_name'])) { $url = file_upload($filename, enlever_accents($nom), enlever_accents($prenom), $telephone1); } $contact = array("FirstName" => $nom, "LastName" => $prenom, "Email" => $email, "Phone1" => $telephone1, "Phone2" => $telephone2, "State" => $province, "StreetAddress1" => $adresse, "PostalCode" => $codepostal, "City" => $ville, "ContactNotes" => $commentaire, "Website" => $url, "ContactType" => 'ANCIA Candidat', "LeadSourceId" => $contactLeadId, "_Formation" => utf8_encode(remove_underscor($f)), "_Experienceprofessionnelle" => utf8_encode($tous_dpartement), "_Niveauhirarchique" => $niveau, "_Langue" => $anglais_champs); //$url_cv='http://emploi.lefebvrefortier.ca/'.file_upload($filename,$nom,$prenom,$telephone1); //$CID=ajoutContact($contact); //créer le tag pour postuler //check si c'est un nouveau candidat ou non
public static function donation_button_get_infusionsoft_lists() { $infusionsoft_lists = array(); $enable_infusionsoft = get_option('enable_infusionsoft'); if (isset($enable_infusionsoft) && $enable_infusionsoft == 'yes') { $infusionsoft_debug = get_option('log_enable_infusionsoft') == 'yes' ? 'yes' : 'no'; $log = new Donation_Button_Logger(); $infusionsoft_lists = unserialize(get_transient('donation_button_infusionsoft_list')); if (empty($infusionsoft_lists) || get_option('donation_button_infusionsoft_force_refresh') == 'yes') { include_once DBP_PLUGIN_DIR_PATH . '/admin/partials/lib/infusionsoft/isdk.php'; $infusionsoft_api_key = get_option('infusionsoft_api_key'); $infusionsoft_api_app_name = get_option('infusionsoft_api_app_name'); if (isset($infusionsoft_api_key) && !empty($infusionsoft_api_key) && (isset($infusionsoft_api_app_name) && !empty($infusionsoft_api_app_name))) { $app = new iSDK(); try { if ($app->cfgCon($infusionsoft_api_app_name, $infusionsoft_api_key)) { $returnFields = array('Id', 'Name'); $query = array('Id' => '%'); $lists = $app->dsQuery("Campaign", 1000, 0, $query, $returnFields); } } catch (Exception $e) { unset($infusionsoft_lists); $infusionsoft_lists['false'] = $e->getMessage(); } if (count($lists) > 0 and is_array($lists)) { unset($infusionsoft_lists); foreach ($lists as $list) { $infusionsoft_lists[$list['Id']] = $list['Name']; } delete_transient('donation_button_infusionsoft_list'); set_transient('donation_button_infusionsoft_list', serialize($infusionsoft_lists), 86400); if ('yes' == $infusionsoft_debug) { $log->add('Infusionsoft', 'Infusionsoft Get List Success..'); } update_option('donation_button_infusionsoft_force_refresh', 'no'); } else { if ('yes' == $infusionsoft_debug) { $log->add('Infusionsoft', 'Infusionsoft API Key And Application Name Please Check.'); } } } else { if ('yes' == $infusionsoft_debug) { $log->add('Infusionsoft', 'Required information is empty.'); } $infusionsoft_lists['false'] = __("Required information is empty.", 'donation-button'); } } } return $infusionsoft_lists; }
public function getInfusionSoftApi() { //include the SDK include_once Director::baseFolder() . '/mysite/code/isdk/src/isdk.php'; //build our application object $app = new iSDK(); //connect to the API - change demo to be whatever your connectionName is! if ($app->cfgCon("connectionName")) { } // Return the application return $app; }
function get_infusionsoft_lists($infusionsoft_api = '', $infusionsoft_app = '') { if ($infusionsoft_api != '' && $infusionsoft_app != '') { try { $myApp = new iSDK(); $res = $myApp->cfgCon($infusionsoft_app, $infusionsoft_api, "on"); $is_forms = $myApp->getWebFormMap(); return $is_forms; } catch (iSDKException $ex) { return array(); } } return array(); }
function process_payment($order_id, $pre_payment = false) { global $woocommerce; $order = new WC_Order($order_id); $items = $order->get_items(); include_once plugin_dir_path(__FILE__) . 'isdk.php'; $infusionApp = new iSDK(); $response = $infusionApp->cfgCon($this->is_application_name, $this->is_api_key); if ($this->debug_email) { wp_mail($this->debug_email, 'Pre-Infusionsoft Payment Debug Feedback', print_r($infusionApp, true) . "\n" . print_r($_GET, true) . "\n" . print_r($_POST, true) . "\n" . print_r($_SESSION, true) . "\n" . print_r($order, true)); } do_action('wc_is_pre_purchase', $infusionApp, $order_id); //hooks for other plugins $address_types = array('shipping', 'billing'); $address_fields = array('first_name', 'email', 'last_name', 'company', 'address_1', 'address_2', 'city', 'state', 'postcode', 'country'); $address_data = array(); foreach ($address_types as $address_type) { foreach ($address_fields as $address_field) { $class_field = $address_type . '_' . $address_field; $address_data[$class_field] = $order->{$class_field}; } } $contact = array(); $contact['Email'] = trim($address_data['billing_email']); $contact['FirstName'] = trim($address_data['billing_first_name']); $contact['LastName'] = trim($address_data['billing_last_name']); $contact['StreetAddress1'] = trim($address_data['billing_address_1']); $contact['StreetAddress2'] = trim($address_data['billing_address_2']); $contact['City'] = trim($address_data['billing_city']); $contact['State'] = trim($address_data['billing_state']); $contact['PostalCode'] = trim($address_data['billing_postcode']); $contact['Country'] = trim($this->translate_country($address_data['billing_country'])); $ship_prefix = 'shipping_'; if (@$_POST['shiptobilling'] == 1) { $ship_prefix = 'billing_'; } $shipping_address = array(); $shipping_address['ShipFirstName'] = trim($address_data[$ship_prefix . 'first_name']); $shipping_address['ShipLastName'] = trim($address_data[$ship_prefix . 'last_name']); $shipping_address['ShipCompany'] = trim($address_data[$ship_prefix . 'company']); $shipping_address['JobNotes'] = trim($order->customer_note); $shipping_address['ShipStreet1'] = trim($address_data[$ship_prefix . 'address_1']); $shipping_address['ShipStreet2'] = trim($address_data[$ship_prefix . 'address_2']); $shipping_address['ShipCity'] = trim($address_data[$ship_prefix . 'city']); $shipping_address['ShipState'] = trim($address_data[$ship_prefix . 'state']); $shipping_address['ShipZip'] = trim($address_data[$ship_prefix . 'postcode']); $shipping_address['ShipCountry'] = trim($this->translate_country($address_data[$ship_prefix . 'country'])); if (!$shipping_address['ShipCity']) { $ship_prefix = 'billing_'; //if there is no shipping info then use billing. $shipping_address = array(); $shipping_address['ShipFirstName'] = trim($address_data[$ship_prefix . 'first_name']); $shipping_address['ShipLastName'] = trim($address_data[$ship_prefix . 'last_name']); $shipping_address['ShipCompany'] = trim($address_data[$ship_prefix . 'company']); $shipping_address['JobNotes'] = trim($order->customer_note); $shipping_address['ShipStreet1'] = trim($address_data[$ship_prefix . 'address_1']); $shipping_address['ShipStreet2'] = trim($address_data[$ship_prefix . 'address_2']); $shipping_address['ShipCity'] = trim($address_data[$ship_prefix . 'city']); $shipping_address['ShipState'] = trim($address_data[$ship_prefix . 'state']); $shipping_address['ShipZip'] = trim($address_data[$ship_prefix . 'postcode']); $shipping_address['ShipCountry'] = trim($this->translate_country($address_data[$ship_prefix . 'country'])); } if (!$pre_payment) { $card = array(); $card['CardType'] = trim($_POST['is_card_type']); $card['CardNumber'] = trim($_POST['is_ccnum']); $card['ExpirationMonth'] = trim($_POST['is_expmonth']); $card['ExpirationYear'] = trim($_POST['is_expyear']); //$card['StartDateMonth'] = trim($_POST['CardStartDateMonth']); //$card['StartDateYear'] = trim($_POST['CardStartDateYear']); $card['CVV2'] = trim($_POST['is_cvv']); $card['NameOnCard'] = $contact['FirstName'] . " " . $contact['LastName']; $card['FirstName'] = $contact['FirstName']; $card['LastName'] = $contact['LastName']; $card['BillAddress1'] = $contact['StreetAddress1']; $card['BillAddress2'] = $contact['StreetAddress2']; $card['BillCity'] = $contact['City']; $card['BillState'] = $contact['State']; $card['BillCountry'] = $contact['Country']; $card['BillZip'] = $contact['PostalCode']; } // Query the software to see if the contact email exists. $queryEmail = array('Email' => $contact['Email']); $returnFields = array('Id'); $contactExists = $infusionApp->dsQuery("Contact", 1, 0, $queryEmail, $returnFields); // If the contact exists, we will set our contact ID if (!empty($contactExists)) { $contactID = $contactExists[0]['Id']; // Get the contact ID. //$response = $infusionApp->updateCon($contactID, $contact); // Update the contact details with the information from the form. } else { if ($this->debug == 'yes') { $this->log->add('infusionsoft', 'Adding new Contact for Order #' . $order_id . '. ' . print_r($contact, true)); } $contactID = $infusionApp->addCon($contact); // Add a new contact to the system. } if (!$pre_payment) { $card['ContactId'] = $contactID; // Set the card contact ID. $creditCardID = $infusionApp->dsAdd("CreditCard", $card); // Add the credit card data. $cardResult = $infusionApp->validateCard($creditCardID); // Validate the credit card. // If the card result was invalid, then report the problem. if ($cardResult['Valid'] == 'false') { if ($this->debug == 'yes') { $this->log->add('infusionsoft', 'Order failed. Card details not valid. Order #' . $order_id . '. ' . print_r($cardResult, true)); } $reason = 'Card Details are not valid'; $woocommerce->add_error('Transaction Failed: ' . $reason); // Transaction Failed Notice on Checkout return false; } } // Setup a new order. $orderType_FINANCECHARGE = 6; $orderType_PRODUCT = 4; $orderType_SERVICE = 3; $orderType_SHIPPING = 1; $orderType_SPECIAL = 7; $orderType_TAX = 2; $orderType_UNKNOWN = 0; $orderType_UPSELL = 5; $is_aff_id = 0; if (isset($_SESSION['is_aff_id'])) { $queryAff = array('AffCode' => $_SESSION['is_aff_id']); $returnFields = array('Id'); if ($getAff = $infusionApp->dsQuery("Affiliate", 1, 0, $queryAff, $returnFields)) { $is_aff_id = $getAff[0]['Id']; // Get the affiliate ID. } } if (!($orderID = $infusionApp->blankOrder($contactID, "New Order #" . $order_id . " from " . site_url(), date('Ymd\\TH:i:s'), 0, $is_aff_id))) { $msg = 'Unable to create order with Infusionsoft'; if ($this->debug == 'yes') { $this->log->add('infusionsoft', $msg); } $woocommerce->add_error($msg); return false; } if ($this->debug == 'yes') { $this->log->add('infusionsoft', 'WooCommerce Order #' . $order_id . ' is IS Order #' . $orderID); } $queryJob = array('Id' => $orderID); $returnFields = array('JobId', 'LeadAffiliateId', 'AffiliateId'); if (!($getJob = $infusionApp->dsQuery("Invoice", 1, 0, $queryJob, $returnFields))) { // grab the invoice id to update $msg = 'Unable to get Invoice ID from Infusionsoft'; if ($this->debug == 'yes') { $this->log->add('infusionsoft', $msg); } $woocommerce->add_error($msg); return false; } else { $job_id = $getJob[0]['JobId']; // Get the contact ID. } //$woocommerce->add_error(print_r($getJob, true)); //return false; if (!$infusionApp->dsUpdate("Job", $job_id, $shipping_address)) { $msg = 'Unable to update job with Infusionsoft'; if ($this->debug == 'yes') { $this->log->add('infusionsoft', $msg); } $woocommerce->add_error($msg); return false; } foreach ($items as $i => $item) { $product_obj = get_post($item['product_id']); $price = round(get_post_meta($item['product_id'], '_price', true), 2); if (!($productID = get_post_meta($item['product_id'], 'is_product_id', true))) { $query = array('ProductName' => $product_obj->post_title); $returnFields = array('Id'); $product_query = $infusionApp->dsQuery("Product", 1, 0, $query, $returnFields); if (!($sku = get_post_meta($item['product_id'], '_sku', true))) { $sku = $product_obj->post_name; } if (empty($product_query)) { //fall back to sku $query = array('Sku' => $sku); $returnFields = array('Id'); $product_query = $infusionApp->dsQuery("Product", 1, 0, $query, $returnFields); if (empty($product_query)) { $product = array('ProductName' => $product_obj->post_title, 'Sku' => $sku, 'ShortDescription' => $product_obj->post_excerpt, 'Description' => $product_obj->post_content, 'ProductPrice' => $price); $productID = $infusionApp->dsAdd("Product", $product); if ($this->debug == 'yes') { $this->log->add('infusionsoft', 'WooCommerce Order #' . $order_id . '. Added product to DB. Added Product ' . $productID); } update_post_meta($product_obj->ID, 'is_product_id', $productID); } else { $productID = $product_query[0]['Id']; } } else { if ($productID = $product_query[0]['Id']) { update_post_meta($product_obj->ID, 'is_product_id', $productID); } } } if ($this->debug == 'yes') { $this->log->add('infusionsoft', 'WooCommerce Order #' . $order_id . ' is IS Order #' . $orderID . '. Added item ' . $productID); } // Add products to the order. if (!($item_row = $infusionApp->addOrderItem($orderID, (int) $productID, $orderType_PRODUCT, (double) $price, (int) $item['qty'], $product_obj->post_title, $product_obj->post_title))) { $msg = 'Failed to add a product to the order: ' . $product_obj->post_title; if ($this->debug == 'yes') { $this->log->add('infusionsoft', $msg); } $woocommerce->add_error($msg); return false; } else { //achieve goal $callName = 'product' . $productID . 'Sold'; // product123sold $infusionApp->achieveGoal($this->is_application_name, $callName, $contactID); //apply tag per order item if ($tag_id = get_post_meta($item['product_id'], 'is_product_tag', true)) { $infusionApp->grpAssign($contactID, $tag_id); } } } if ((int) $order->order_tax) { $vat_amount = $order->order_tax + $order->order_shipping_tax; if (!($item_row = $infusionApp->addOrderItem($orderID, 0, $orderType_TAX, $vat_amount, (int) 1, "VAT", "VAT"))) { $msg = 'Failed to add the tax product to the order. Tax amount: ' . $vat_amount; if ($this->debug == 'yes') { $this->log->add('infusionsoft', $msg); } $woocommerce->add_error($msg); return false; } } if ((int) $order->order_shipping) { $shipping = (double) $order->order_shipping; if (!($item_row = $infusionApp->addOrderItem($orderID, 0, $orderType_SHIPPING, $shipping, (int) 1, "Shipping", "Shipping"))) { $msg = 'Failed to add the shipping product to the order. Shipping amount: ' . $shipping; if ($this->debug == 'yes') { $this->log->add('infusionsoft', $msg); } $woocommerce->add_error($msg); return false; } } if ((int) $order->get_total_discount()) { $discount = (double) $order->get_total_discount(); $discount *= -1; //make negative if (!($item_row = $infusionApp->addOrderItem($orderID, 0, 11, $discount, (int) 1, "Discount", "Discount"))) { $msg = 'Failed to add the discount product to the order. Discount amount: ' . $discount; if ($this->debug == 'yes') { $this->log->add('infusionsoft', $msg); } $woocommerce->add_error($msg); return false; } } if (!($amountOwed = $infusionApp->amtOwed($orderID))) { // Calculate the amount owed for this order. $msg = 'Infusionsoft amount owed returned zero for order: ' . $orderID; if ($this->debug == 'yes') { $this->log->add('infusionsoft', $msg); } $woocommerce->add_error($msg); return false; } else { if ($amountOwed < 0) { $msg = 'Infusionsoft amount owed returned zero (' . $amountOwed . ') for order: ' . $orderID; if ($this->debug == 'yes') { $this->log->add('infusionsoft', $msg); } $woocommerce->add_error($msg); return false; } } do_action('wc_is_post_purchase', $infusionApp, $order_id, $contactID, $productID, $orderID, $job_id); //hooks for other plugins update_post_meta((int) $order_id, 'IS amount owed', $amountOwed); update_post_meta((int) $order_id, 'IS Order (Job) ID', $job_id); update_post_meta((int) $order_id, 'IS Invoice ID', $orderID); update_post_meta((int) $order_id, 'Payment Method', $order->payment_method_title); $order->add_order_note(__('IS Order ID', 'woocommerce') . ' - ' . $orderID); $order->add_order_note(__('Payment Method', 'woocommerce') . ' - ' . $this->method_title); if ($this->test_mode == 'yes') { $woocommerce->add_error('At this point you have passed all forms of verification and your order should have been added to IS with the ID of ' . $orderID . ' for the value of ' . $amountOwed . '. Take the IS module out of test mode to make real transactions.'); return false; } if (!$pre_payment) { if ($this->is_merchant_id) { $paymentResult = $infusionApp->chargeInvoice($orderID, get_bloginfo('name') . " Payment", $creditCardID, $this->is_merchant_id, false); // Charge the Credit Card. } else { $woocommerce->add_error('You have not added your IS Merchant ID. Add it to the IS settings page within WooCommerce and this gateway will function properly.'); return false; } update_post_meta((int) $order_id, 'IS Ref Num', $paymentResult['RefNum']); // If we have failed, report the reason. if (!$paymentResult['Successful']) { if ($this->debug == 'yes') { $this->log->add('infusionsoft', 'WooCommerce Order #' . $order_id . ' is IS Order #' . $orderID . '. Payment failure: ' . print_r($paymentResult, true)); } if ($this->debug_email) { wp_mail($this->debug_email, 'Post-Infusionsoft Payment Debug Feedback - Payment FAILED', print_r($paymentResult, true) . "\n" . print_r($_POST, true) . "\n" . print_r($_SESSION, true) . "\n" . print_r($order, true)); } $woocommerce->add_error('Transaction Failed: ' . $paymentResult['Message']); // Transaction Failed Notice on Checkout return; } //From here the payment has been successful if ($this->debug_email) { wp_mail($this->debug_email, 'Post-Infusionsoft Payment Debug Feedback', print_r($paymentResult, true) . "\n" . print_r($_POST, true) . "\n" . print_r($_SESSION, true) . "\n" . print_r($order, true)); } } else { //mark the invoice as paid $payDate = $infusionApp->infuDate(date('d-m-Y')); $infusionApp->manualPmt($orderID, $amountOwed, $payDate, $order->payment_method_title, $order->payment_method_title, false); } //foreach ($transaction as $k=>$v) { //update_post_meta((int)$order_id, $k, $v); //} foreach ($paymentResult as $k => $v) { update_post_meta((int) $order_id, $k, $v); } // Check order not already completed if (in_array($order->status, array('processing', 'completed'))) { if ($this->debug == 'yes') { $this->log->add('infusionsoft', 'Aborting, Order #' . $order_id . ' is already complete.'); } return false; } if (!$pre_payment) { $order->add_order_note(__('Payment accepted - Order Successful', 'woocommerce')); $order->payment_complete(); $woocommerce->cart->empty_cart(); } $this->feedback_message = $this->thanks_message; return array('result' => 'success', 'redirect' => $this->get_return_url($order)); }
<?php require_once "../src/isdk.php"; $app = new iSDK(); if ($app->cfgCon("connectionName", "api-key", "throw")) { echo "connected<br/>"; echo "app connected<br/>"; $qry = array("FakeColumn" => "FakeValue"); try { $r = $app->dsQuery("FakeTable", 1, 0, $qry, array("FakeColumn")); } catch (iSDKException $e) { echo "iSDKException code {$e->getCode()}, message: {$e->getMessage()}\n"; exit; } echo "Test failed: exception should have been thrown\n"; exit(1); } else { echo "connection failed"; }
<?php require_once "src/isdk.php"; $app = new iSDK(); $app_name = ''; // Replace with Your Infusionsoft APP Name $app_key = ''; // Replace with Your Infusionsoft API Key if (empty($app_name)) { echo 'Your APP Name is empty. Please set your app name to your Infusionsoft API name.<br>'; return; } if (empty($app_key)) { echo 'Your APP key is empty. Please set your app key to your Infusionsoft API key.<br>'; return; } if ($app->cfgCon($app_name, $app_key)) { // Connected to Infusionsoft - Run Your Code Below echo 'Connected to Infusionsoft<br>'; } else { echo 'Error connecting to Infusionsoft. Please make sure your keys are correct.'; }
function NotifyCompleteProfileByInfusionsoftID($infusionsoft_id) { //this is used for appylying a infusionsoft group (tag) for customers who complete their profile. //auth.php will access this function require_once 'isdk.php'; $app = new iSDK(); if ($app->cfgCon("mps")) { $app->grpAssign($infusionsoft_id, 314); } }
/** * Subscribes to Infusionsoft list. Returns either "success" string or error message. * @return string */ function subscribe_infusionsoft($api_key, $app_id, $list_id, $email, $name = '', $last_name = '') { if (!function_exists('curl_init')) { return __('curl_init is not defined ', 'bloom'); } if (!class_exists('iSDK')) { require_once ET_BLOOM_PLUGIN_DIR . 'subscription/infusionsoft/isdk.php'; } try { $infusion_app = new iSDK(); $infusion_app->cfgCon($app_id, $api_key, 'throw'); } catch (iSDKException $e) { $error_message = $e->getMessage(); } if (empty($error_message)) { $contact_data = $infusion_app->dsQuery('Contact', 1, 0, array('Email' => $email), array('Id', 'Groups')); if (0 < count($contact_data)) { if (false === strpos($contact_data[0]['Groups'], $list_id)) { $infusion_app->grpAssign($contact_data[0]['Id'], $list_id); $error_message = 'success'; } else { $error_message = __('Already subscribed', 'bloom'); } } else { $contact_details = array('FirstName' => $name, 'LastName' => $last_name, 'Email' => $email); $new_contact_id = $infusion_app->dsAdd('Contact', $contact_details); $infusion_app->grpAssign($new_contact_id, $list_id); $error_message = 'success'; } } return $error_message; }
/** * Override of parent::cfgCon * * @see iSDK_enhanced::connect */ public function cfgCon($name, $key = '', $dbOn = 'on', $type = 'i') { return $this->connected = parent::cfgCon($name, $key, $dbOn, $type); }
public function shoppingcart() { if (isset($_POST['first_name'])) { $app = new \iSDK(); if ($app->cfgCon("connectionName")) { $qry = array('Email' => $_POST['emailAddress']); $ret = array("Id"); $dups = $app->dsQuery("Contact", 1, 0, $qry, $ret); if (empty($dups)) { $contact = array("FirstName" => $_POST['first_name'], "LastName" => $_POST['last_name'], "State" => $_POST['state'], "Phone1" => $_POST['phoneNumber'], "City" => $_POST['city'], "Email" => $_POST['emailAddress'], "Address1Type" => $_POST['addressLine1'], "ZipFour1" => $_POST['last_name'], "Country" => $_POST['last_name'], "Company" => $_POST['company']); $date = date('d/m/y'); $cid = $app->addCon($contact); } else { $cid = $dups[0]['Id']; $contact = array("FirstName" => $_POST['first_name'], "LastName" => $_POST['last_name'], "State" => $_POST['state'], "Phone1" => $_POST['phoneNumber'], "City" => $_POST['city'], "Email" => $_POST['emailAddress'], "Address1Type" => $_POST['addressLine1'], "ZipFour1" => $_POST['last_name'], "Country" => $_POST['last_name'], "Company" => $_POST['company']); $contact_ID = $app->updateCon($cid, $contact); } $fullname = explode(" ", $_POST['nameoncard']); $card['FirstName'] = $fullname[0]; $card['LastName'] = $fullname[1]; $card['CardNumber'] = $_POST['cnumber']; $card['ExpirationMonth'] = $_POST['cardmonth']; $card['ExpirationYear'] = $_POST['cardyear']; $card['CVV2'] = $_POST['CVV']; $result = $app->validateCard($card); if ($result['Valid'] == 'false') { $msg = "Order cancel due to credit card"; return view('licenses.shoppingcart', compact('msg')); } else { $ccid = $app->dsAdd("CreditCard", $card); //$timezone = new DateTimeZone( "America/New_York" ); //$date = new DateTime(); //$date->setTimezone( $timezone ); $currentDate = date('Y-m-d H:i:s'); $oDate = $app->infuDate($currentDate); try { $invID = $app->blankOrder($cid, "Order for Licenses" . $cid, $oDate, 0, 0); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; } $ord = $app->getOrderId($invID); $Quantity = $_POST['Quantity']; $subID = array(); for ($i = 1; $i <= $Quantity; $i++) { $app->addOrderItem((int) $invID, (int) 50, (int) 4, (double) 0.1, (int) 1, 'Licenses Item' . $i, ''); $_intproductid = $app->addRecurringAdv((int) $cid, true, (int) 34, (int) 1, (double) 0.1, false, (int) 2, (int) $ccid, (int) 0, (int) 30); $_nextBillDate = date("d-m-Y", strtotime("1 Months + 1 day")); $subID[$i] = $_intproductid; $thedate = $app->infuDate($_nextBillDate); $app->updateSubscriptionNextBillDate($_intproductid, $thedate); $service["Frequency"] = 1; $service["BillingCycle"] = 2; $app->dsUpdate("RecurringOrder", $_intproductid, $service); } $payStat = $app->chargeInvoice((int) $invID, "Payment Via API", (int) $ccid, (int) 2, false); if (substr($payStat['Message'], 0, 2) == "91") { $payStat = $app->chargeInvoice((int) $invID, "Payment Via API", (int) $ccid, (int) 2, false); } if ($payStat['RefNum'] != "E" && $payStat['Code'] == "APPROVED") { $msg = "Thanks For Order"; $user_id = Auth::user()->id; $users = User::findOrFail($user_id); for ($i = 1; $i <= $Quantity; $i++) { $date = new \DateTime(); $license = new License(); $license->life = 1; $license->license_key = $subID[$i]; $license->company_id = $users->company_id; $license->user_id = 0; $license->status = 'ACTIVE'; $license->created_by = Auth::user()->id; $license->created_at = $date; $license->updated_at = $date; $license->save(); } return view('licenses.shoppingcart', compact('msg')); } else { $msg = "Order cancel due payment"; return view('licenses.shoppingcart', compact('msg')); } } } } $msg = ""; return view('licenses.shoppingcart', compact('msg')); }
/** * Record an impression made by a optin fire * This function is called via PHP. * * @access public * @static * @return void */ function nnr_new_int_add_email_v1() { do_action('nnr_news_int_before_submission_add_email_v1'); // No First Name if (!isset($_POST['first_name'])) { $_POST['first_name'] = ''; } // No Last Name if (!isset($_POST['last_name'])) { $_POST['last_name'] = ''; } // Could not find Data ID if (!isset($_POST['data_id']) || $_POST['data_id'] == '') { echo json_encode(array('id' => $_POST['data_id'], 'status' => 'warning', 'message' => __('Could not find Data ID.', $_POST['text_domain']))); die; } // Get all newsletter data for this data instance $data_manager = new NNR_Data_Manager_v1($_POST['table_name']); $data_instance = $data_manager->get_data_from_id($_POST['data_id']); $success_action = isset($data_instance['args']['newsletter']['success_action']) ? stripcslashes($data_instance['args']['newsletter']['success_action']) : 'message'; $success_mesage = isset($data_instance['args']['newsletter']['success_message']) ? stripcslashes($data_instance['args']['newsletter']['success_message']) : __('Welcome to the community!', $_POST['text_domain']); $success_url = isset($data_instance['args']['newsletter']['success_url']) ? stripcslashes($data_instance['args']['newsletter']['success_url']) : ''; // No Email if (!isset($_POST['email']) || $_POST['email'] == '') { echo json_encode(array('id' => $_POST['data_id'], 'status' => 'warning', 'message' => __('No Email address provided.', $_POST['text_domain']))); die; } // Invalid Email Address if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) { echo json_encode(array('id' => $_POST['data_id'], 'status' => 'warning', 'message' => __('Invalid Email provided.', $_POST['text_domain']))); die; } // WordPress if ($_POST['type'] == 'wordpress') { $newsletter_db = new NNR_Newsletter_Integrations_Submission_v1($_POST['news_table_name']); $result = $newsletter_db->add_data(array('data_id' => $_POST['data_id'], 'email' => $_POST['email'], 'first_name' => $_POST['first_name'], 'last_name' => $_POST['last_name'])); if ($result) { echo json_encode(array('id' => $_POST['data_id'], 'status' => 'check', 'success_action' => $success_action, 'url' => $success_url, 'message' => $success_mesage, 'conversion' => apply_filters('nnr_news_int_submission_success_v1', array('data_id' => $_POST['data_id'], 'table_name' => $_POST['stats_table_name'])))); die; } else { echo json_encode(array('id' => $_POST['data_id'], 'status' => 'check', 'message' => __('We already have your email!', $_POST['text_domain']))); die; } } else { if ($_POST['type'] == 'mailchimp') { require_once dirname(dirname(__FILE__)) . '/services/mailchimp/MailChimp.php'; if (!isset($data_instance['args']['newsletter']['mailchimp']['api_key']) || $data_instance['args']['newsletter']['mailchimp']['api_key'] == '') { echo json_encode(array('id' => $_POST['data_id'], 'status' => 'warning', 'message' => __('MailChimp account is not setup properly.', $_POST['text_domain']))); die; } if (!isset($data_instance['args']['newsletter']['mailchimp']['list']) || $data_instance['args']['newsletter']['mailchimp']['list'] == '') { echo json_encode(array('id' => $_POST['data_id'], 'status' => 'warning', 'message' => __('MailChimp: No list specified.', $_POST['text_domain']))); die; } if (!isset($data_instance['args']['newsletter']['mailchimp']['optin'])) { $data_instance['args']['newsletter']['mailchimp']['optin'] = true; } $MailChimp = new NNR_New_Int_MailChimp($data_instance['args']['newsletter']['mailchimp']['api_key']); $result = $MailChimp->call('lists/subscribe', array('id' => $data_instance['args']['newsletter']['mailchimp']['list'], 'email' => array('email' => $_POST['email']), 'merge_vars' => array('FNAME' => $_POST['first_name'], 'LNAME' => $_POST['last_name']), 'double_optin' => $data_instance['args']['newsletter']['mailchimp']['optin'], 'update_existing' => false, 'replace_interests' => false, 'send_welcome' => true)); if ($result) { if (isset($result['email'])) { echo json_encode(array('id' => $_POST['data_id'], 'status' => 'check', 'success_action' => $success_action, 'url' => $success_url, 'message' => $success_mesage, 'conversion' => apply_filters('nnr_news_int_submission_success_v1', array('data_id' => $_POST['data_id'], 'table_name' => $_POST['stats_table_name'])))); die; } else { if (isset($result['status']) && $result['status'] == 'error') { echo json_encode(array('id' => $_POST['data_id'], 'status' => 'warning', 'message' => $result['error'])); die; } } } else { echo json_encode(array('id' => $_POST['data_id'], 'status' => 'warning', 'message' => __('Unable to subscribe.', $_POST['text_domain']))); die; } } else { if ($_POST['type'] == 'aweber') { require_once dirname(dirname(__FILE__)) . '/services/aweber/aweber_api.php'; $aweber = new AWeberAPI($data_instance['args']['newsletter']['aweber']['consumer_key'], $data_instance['args']['newsletter']['aweber']['consumer_secret']); try { $account = $aweber->getAccount($data_instance['args']['newsletter']['aweber']['access_key'], $data_instance['args']['newsletter']['aweber']['access_secret']); $list = $account->loadFromUrl('/accounts/' . $account->id . '/lists/' . $data_instance['args']['newsletter']['aweber']['list_id']); $subscriber = array('email' => $_POST['email'], 'name' => $_POST['first_name'] . ' ' . $_POST['last_name'], 'ip' => $_SERVER['REMOTE_ADDR']); $newSubscriber = $list->subscribers->create($subscriber); echo json_encode(array('id' => $_POST['data_id'], 'status' => 'check', 'success_action' => $success_action, 'url' => $success_url, 'message' => $success_mesage, 'conversion' => apply_filters('nnr_news_int_submission_success_v1', array('data_id' => $_POST['data_id'], 'table_name' => $_POST['stats_table_name'])))); die; } catch (AWeberAPIException $exc) { echo json_encode(array('id' => $_POST['data_id'], 'status' => 'warning', 'message' => $exc->message)); die; } } else { if ($_POST['type'] == 'getresponse') { require_once dirname(dirname(__FILE__)) . '/services/getresponse/jsonRPCClient.php'; $api = new jsonRPCClient('http://api2.getresponse.com'); try { $api->add_contact($data_instance['args']['newsletter']['getresponse']['api_key'], array('campaign' => $data_instance['args']['newsletter']['getresponse']['campaign'], 'name' => $_POST['first_name'] . ' ' . $_POST['last_name'], 'email' => $_POST['email'])); echo json_encode(array('id' => $_POST['data_id'], 'status' => 'check', 'success_action' => $success_action, 'url' => $success_url, 'message' => $success_mesage, 'conversion' => apply_filters('nnr_news_int_submission_success_v1', array('data_id' => $_POST['data_id'], 'table_name' => $_POST['stats_table_name'])))); die; } catch (RuntimeException $exc) { $msg = $exc->getMessage(); $msg = substr($msg, 0, strpos($msg, ";")); echo json_encode(array('id' => $_POST['data_id'], 'status' => 'warning', 'message' => $msg)); die; } } else { if ($_POST['type'] == 'campaignmonitor') { require_once dirname(dirname(__FILE__)) . '/services/campaignmonitor/csrest_subscribers.php'; $wrap = new CS_REST_Subscribers($data_instance['args']['newsletter']['campaignmonitor']['list'], $data_instance['args']['newsletter']['campaignmonitor']['api_key']); // Check if subscriber is already subscribed $result = $wrap->get($_POST['email']); if ($result->was_successful()) { echo json_encode(array('id' => $_POST['data_id'], 'status' => 'warning', 'message' => __('You are already subscribed to this list.', $_POST['text_domain']))); die; } $result = $wrap->add(array('EmailAddress' => $_POST['email'], 'Name' => $_POST['first_name'] . ' ' . $_POST['last_name'], 'Resubscribe' => true)); if ($result->was_successful()) { echo json_encode(array('id' => $_POST['data_id'], 'status' => 'check', 'success_action' => $success_action, 'url' => $success_url, 'message' => $success_mesage, 'conversion' => apply_filters('nnr_news_int_submission_success_v1', array('data_id' => $_POST['data_id'], 'table_name' => $_POST['stats_table_name'])))); die; } else { echo json_encode(array('id' => $_POST['data_id'], 'status' => 'warning', 'message' => $result->response->Message)); die; } } else { if ($_POST['type'] == 'madmimi') { require_once dirname(dirname(__FILE__)) . '/services/madmimi/MadMimi.class.php'; $mailer = new MadMimi($data_instance['args']['newsletter']['madmimi']['username'], $data_instance['args']['newsletter']['madmimi']['api_key']); try { // Check if user is already in list $result = $mailer->Memberships($_POST['email']); $lists = new SimpleXMLElement($result); if ($lists->list) { foreach ($lists->list as $l) { if ($l->attributes()->{'name'}->{0} == $data_instance['args']['newsletter']['madmimi']['list']) { echo json_encode(array('id' => $_POST['data_id'], 'status' => 'check', 'message' => __('You are already subscribed to this list.', $_POST['text_domain']))); die; } } } $result = $mailer->AddMembership($data_instance['args']['newsletter']['madmimi']['list'], $_POST['email'], array('first_name' => $_POST['first_name'], 'last_name' => $_POST['last_name'])); echo json_encode(array('id' => $_POST['data_id'], 'status' => 'check', 'success_action' => $success_action, 'url' => $success_url, 'message' => $success_mesage, 'conversion' => apply_filters('nnr_news_int_submission_success_v1', array('data_id' => $_POST['data_id'], 'table_name' => $_POST['stats_table_name'])))); die; } catch (RuntimeException $exc) { echo json_encode(array('id' => $_POST['data_id'], 'status' => 'warning', 'message' => $msg)); die; } } else { if ($_POST['type'] == 'infusionsoft') { require_once dirname(dirname(__FILE__)) . '/services/infusionsoft/isdk.php'; try { $infusion_app = new iSDK(); $infusion_app->cfgCon($data_instance['args']['newsletter']['infusionsoft']['app_id'], $data_instance['args']['newsletter']['infusionsoft']['api_key'], 'throw'); } catch (iSDKException $e) { echo json_encode(array('id' => $_POST['data_id'], 'status' => 'warning', 'message' => $e->getMessage())); die; } if (empty($error_message)) { $contact_data = $infusion_app->dsQuery('Contact', 1, 0, array('Email' => $_POST['email']), array('Id', 'Groups')); // Check if contact already exists if (0 < count($contact_data)) { if (false === strpos($contact_data[0]['Groups'], $data_instance['args']['newsletter']['infusionsoft']['list'])) { $infusion_app->grpAssign($contact_data[0]['Id'], $data_instance['args']['newsletter']['infusionsoft']['list']); echo json_encode(array('id' => $_POST['data_id'], 'status' => 'check', 'success_action' => $success_action, 'url' => $success_url, 'message' => $success_mesage, 'conversion' => apply_filters('nnr_news_int_submission_success_v1', array('data_id' => $_POST['data_id'], 'table_name' => $_POST['stats_table_name'])))); die; } else { echo json_encode(array('id' => $_POST['data_id'], 'status' => 'check', 'message' => __('You are already subscribed to this list.', $_POST['text_domain']))); die; } } else { $new_contact_id = $infusion_app->dsAdd('Contact', array('FirstName' => $_POST['first_name'], 'LastName' => $_POST['last_name'], 'Email' => $_POST['email'])); $infusion_app->grpAssign($new_contact_id, $data_instance['args']['newsletter']['infusionsoft']['list']); echo json_encode(array('id' => $_POST['data_id'], 'status' => 'check', 'success_action' => $success_action, 'url' => $success_url, 'message' => $success_mesage, 'conversion' => apply_filters('nnr_news_int_submission_success_v1', array('data_id' => $_POST['data_id'], 'table_name' => $_POST['stats_table_name'])))); die; } } } else { if ($_POST['type'] == 'mymail') { // Check if plugin is activated if (!function_exists('mymail')) { echo json_encode(array('id' => $_POST['data_id'], 'status' => 'warning', 'message' => __('MyMail is not activated.', $_POST['text_domain']))); die; } // Add subscriber $subscriber_id = mymail('subscribers')->add(array('email' => $_POST['email'], 'firstname' => $_POST['first_name'], 'lastname' => $_POST['last_name']), false); // Add to List if (!is_wp_error($subscriber_id)) { mymail('subscribers')->assign_lists($subscriber_id, array($data_instance['args']['newsletter']['mymail']['list'])); echo json_encode(array('id' => $_POST['data_id'], 'status' => 'check', 'success_action' => $success_action, 'url' => $success_url, 'message' => $success_mesage, 'conversion' => apply_filters('nnr_news_int_submission_success_v1', array('data_id' => $_POST['data_id'], 'table_name' => $_POST['stats_table_name'])))); die; } else { echo json_encode(array('id' => $_POST['data_id'], 'status' => 'check', 'message' => __('You are already subscribed to this list.', $_POST['text_domain']))); die; } } else { if ($_POST['type'] == 'activecampaign') { require_once dirname(dirname(__FILE__)) . '/services/activecampaign/ActiveCampaign.class.php'; $ac = new ActiveCampaign($data_instance['args']['newsletter']['activecampaign']['app_url'], $data_instance['args']['newsletter']['activecampaign']['api_key']); if (!(int) $ac->credentials_test()) { echo json_encode(array('id' => $_POST['data_id'], 'status' => 'warning', 'message' => __('Unable to to connect to Active Campaign.', $_POST['text_domain']))); die; } // Add subscriber $contact_sync = $ac->api("contact/add", array("email" => $_POST['email'], "first_name" => $_POST['first_name'], "last_name" => $_POST['last_name'], "p[" . $data_instance['args']['newsletter']['activecampaign']['list'] . "]" => $data_instance['args']['newsletter']['activecampaign']['list'], "status[" . $data_instance['args']['newsletter']['activecampaign']['list'] . "]" => 1)); if ((int) $contact_sync->success) { echo json_encode(array('id' => $_POST['data_id'], 'status' => 'check', 'success_action' => $success_action, 'url' => $success_url, 'message' => $success_mesage, 'conversion' => apply_filters('nnr_news_int_submission_success_v1', array('data_id' => $_POST['data_id'], 'table_name' => $_POST['stats_table_name'])))); die; } else { echo json_encode(array('id' => $_POST['data_id'], 'status' => 'warning', 'message' => $contact_sync->error)); die; } } } } } } } } } } do_action('nnr_news_int_after_submission_add_email_v1'); echo json_encode(apply_filters('nnr_news_int_submission_add_email_v1', array('id' => $_POST['data_id'], 'status' => 'warning', 'message' => __('Unable to subscribe user. Newsletter not setup properly.', $_POST['text_domain'])))); die; // this is required to terminate immediately and return a proper response }