| Server IP : 10.200.247.200 / Your IP : 216.73.217.19 Web Server : Apache System : Linux synergy-usa-sites 6.8.0-138-generic #138-Ubuntu SMP PREEMPT_DYNAMIC Fri Jul 31 22:41:49 UTC 2026 x86_64 User : jeremy ( 1001) PHP Version : 8.4.25 Disable Function : NONE MySQL : OFF | cURL : ON | WGET : ON | Perl : ON | Python : OFF | Sudo : ON | Pkexec : OFF Directory : /var/www/usa_sites/pcisecureform.com/lcapi/ |
Upload File : |
<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/php/db_config_lc_user.php');
require_once($_SERVER['DOCUMENT_ROOT'].'/lcapi/inc/Logger.php');
require_once($_SERVER['DOCUMENT_ROOT'].'/lcapi/inc/common.php');
require_once($_SERVER['DOCUMENT_ROOT'].'/php/phpCrypto.class.php');
require_once($_SERVER['DOCUMENT_ROOT'].'/php/NetworkMerchants.php');
require_once($_SERVER['DOCUMENT_ROOT'].'/php/MerchantProcessor/Processor.php');
require_once($_SERVER['DOCUMENT_ROOT'].'/php/MerchantProcessor/Site.php');
require_once($_SERVER['DOCUMENT_ROOT'].'/php/KVStore/KVStore.php');
$debug = false;
if(empty($_POST['site']) || empty($_POST['client_id'])) {
die('Error: Missing required info.');
}
$site = $_POST['site'];
$crypto = new phpCrypto();
$db = connect_lc2user_new('lc2admin');
//get the bad decline reasons from the db.
$marked_reasons_obj = $db->get_results("SELECT reason FROM lc2admin.decline_reasons WHERE cancel='1'");
$marked_reasons = array();
foreach($marked_reasons_obj as $reason) {
$marked_reasons[] = $reason->reason;
}
unset($marked_reasons_obj);
//$db->debug_all = true;
//$db->show_errors();
$cc_type = array('3'=>'amex', '4'=>'visa', '5'=>'mast', '6'=>'disc'); //set which type of card this is based on the first digit
$today = date( 'Y-m-d' );
$debug = (! isset($debug)) ? false : true;
$testing = (! isset($testing)) ? false : true;
$_REBILL_ATTEMPTS = (isset($rebill_attempts) && is_numeric($rebill_attempts)) ? $rebill_attempts : 5; //5 here means 6 attempts
$_REBILL_DAY_RANGE = (isset($rebill_day_range) && is_numeric($rebill_day_range)) ? $rebill_day_range : 7;
$_REBILL_CUSTOMER_LIMIT = (isset($rebill_customer_limit) && is_numeric($rebill_customer_limit)) ? 'LIMIT '.$rebill_customer_limit : '';
$totalbilled = 0.00;
$customersbilled = 0;
$totaldeclined = 0.00;
$customersdeclined = 0;
$decline_reasons = array();
$totalerrored = 0.00;
$customerserrored = 0;
$error_reasons = array();
$bill_time_of_day = (date('H')*1>12) ? 'night' : 'morning';
$selectsql = "
SELECT
r.id,
r.first,
r.last,
r.address1,
r.city,
r.state,
r.zip,
r.phone_1,
r.email,
r.cc_name,
r.cc_num,
r.cc_exp_month,
r.cc_exp_year,
r.total_charged,
r.referer,
r.cid,
r.sid,
r.tracking_code,
r.cc_last_charged,
r.rebill_proc_id,
r.resellerID,
r.total_rebills,
r.failures,
r.customer_vault_id,
cs.next_bill_date,
cs.order_date,
cs.amount,
cs.declines,
cs.rebills,
cs.terms,
cs.term_length,
s.subscription_id,
s.name,
s.description,
site.site_name
FROM lc2{$site}_lc.lc_reseller r
INNER JOIN lc2{$site}_lc.lc_clients_subscriptions cs ON r.id = cs.reseller_id AND cs.subscription_id=2
INNER JOIN lc2{$site}_lc.lc_subscriptions s ON cs.subscription_id = s.subscription_id
LEFT JOIN lc2admin.site site ON site.site_code = '".$db->clean($site)."'
WHERE r.id='".$db->clean($_POST['client_id'])."' AND cs.subscription_id=2";
$_REBILL_SELECT_SQL = (isset($rebill_select_sql) && $rebill_select_sql != '') ? $rebill_select_sql : $selectsql;
if (isset($_SERVER['HTTP_HOST'])) {
//This script MUST be run from the command line!
//die();
}
/* *
* Get client subscriptions to be billed
*/
$client_subscriptions = $db->get_results($_REBILL_SELECT_SQL);
if($db->errno() > 0) {
die("Database: '".$db->dbname."' MySQL Error: ".$db->error());
}
if($debug) { $debugmessage = "Rebill for $resellerID for $today\n";}
//if ($debug) { $debugmessage .= "SelectSQL: $_REBILL_SELECT_SQL\n";}
//if (! $result) { $debugmessage .= "Error in SelectSQL: " . $db->error() . "\n"; }
$rebillcount = count($client_subscriptions);
if ($debug) { $debugmessage .= "RebillCount: $rebillcount\n";}
if ($debug) { $debugmessage .= "Format: id|first last|email|sign up date|last charged date|# of failures\n";}
if (!empty($client_subscriptions))
{
foreach($client_subscriptions as $subscription)
{
//Client info
$id = $subscription->id;
$first = ucfirst(strtolower($subscription->first));
$last = ucfirst(strtolower($subscription->last));
$add = ucwords(strtolower($subscription->address1));
$city = ucwords(strtolower($subscription->city));
$state = strtoupper($subscription->state);
$zip = $subscription->zip;
$phone_1 = preg_replace('/[^0-9]','',$subscription->phone_1);
$email = strtolower($subscription->email);
$resellerID = strtolower($subscription->resellerID);
//Billing info
$subscription_id = $subscription->subscription_id;
$cc_name = $crypto->decrypt($subscription->cc_name);
$cc_num = preg_replace('/[^0-9]/','',$crypto->decrypt($subscription->cc_num)); //decrytp and remove any non digit chars
$bill_cc_type = ($cc_num == '' || !array_key_exists(substr($cc_num, 0, 1), $cc_type)) ? 'NONE' : $cc_type[substr($cc_num, 0, 1)];
$cc_exp = $subscription->cc_exp_month;
$cc_yr = $subscription->cc_exp_year;
$cc_amount = $subscription->amount;
//Check for teleseminars and coaching
$other_subscriptions_res = $db->get_results("SELECT SUM(amount) as s
FROM lc2{$site}_lc.lc_clients_subscriptions
WHERE reseller_id='".$db->clean($id)."'
AND subscription_id IN (3,4)
AND active=1");
if(!empty($other_subscriptions_res)) {
$cc_amount += $other_subscriptions_res[0]->s;
}
//check if this is a delayed billing
$dbres = $db->get_results("SELECT * FROM allocator.pending_sales WHERE site_code='".$db->clean($site)."' AND client_id='".$db->clean($subscription->id)."'");
if(!empty($dbres)) {
if($dbres[0]->charged==0) {
$cc_amount = $dbres[0]->initial_fee;
} else {
//not the first charge, it should be fine
}
}
if(!empty($_REQUEST['charge_amount'])) {
$cc_amount = $_REQUEST['charge_amount'];
}
$total_charged = $subscription->total_charged;
$order_date = $subscription->order_date;
$rebill_proc_id = (trim($subscription->rebill_proc_id != '')) ? $subscription->rebill_proc_id : null;
$failures = $subscription->failures;
$declines = $subscription->declines;
$rebills = $subscription->rebills;
$total_rebills = $subscription->total_rebills;
//$productid = ($subscription->site_name != "") ? trim($subscription->name." Billing for ".$subscription->site_name) : trim("Billing - ".$subscription->name);
$product_id = 'Monthly billing for '.$site;
if($subscription->terms > $subscription->rebills) {
//$nextbilldate = date('Y-m-d', strtotime("+".$subscription->term_length." days"));
$nextbilldate = date('Y-m-d', strtotime("+30 day"));
} else {
$nextbilldate = '0000-00-00';
}
//Tracking info
$referer = $subscription->referer;
$cid = $subscription->cid;
$sid = $subscription->sid;
$tracking_code = $subscription->tracking_code;
$last_charged = $subscription->cc_last_charged;
//echo "CC_Amount: $cc_amount\n";
// Setup our bill_type, which is a number indicating the rebill count plus the attempt
if ($declines == '0') {
$bill_type = ($rebills + 1) . "-1";
} else {
$bill_type = ($rebills + 1) . "-" . ($declines + 1);
}
// Fix 4 digit years
$ccYrLen = strlen( $cc_yr );
if( $ccYrLen > 2 ) {
$cc_yr = substr( $cc_yr, $ccYrLen-2 );
}
// fix 1 digit months
if(strlen($cc_exp) == 1) {
$cc_exp = str_pad($cc_exp, 2, "0", STR_PAD_LEFT);
}
if ($debug) {
$debugmessage .= "$id|$first $last|$email|$order_date|$last_charged|$declines\n";
}
//echo "$id|$first $last|$email|$order_date|$last_charged|$declines\n";
$merchant = "giso";
$gw = new gwapi();
if ($site == 'a2r') {
$gw->setLogin("autcion2riches","dustin123",$proc_id);
} else {
$gw->setLogin("synergyAPI", "Ep3Ypulg6M",$proc_id);
}
$ks = new KVStore("MerchantSettings");
$sitesettings = null;
if (isset($ks[$site]))
{
$sitesettings = $ks[$site];
$sitesettings->Acquire();
$rebill_proc = $sitesettings->GetRebillProcessor($cc_amount, $rebill_proc_id);
/*
While not perfect, here's where we can switch between gateways.
We'll default to using NMI/giso
Our first special case is 'Assertigy'
*/
/*if ($rebill_proc->gateway == 'Assertigy') {
$gw = new Assertigy();
// Assertigy uses the processor name as the first parameter
$gw->setLogin($rebill_proc->name,$rebill_proc->username,$rebill_proc->password);
// Set the merchant correctly!
$merchant = "Assertigy";
} else if ($rebill_proc->gateway == 'OptimalPayments') {
$gw = new OptimalPayments();
// Assertigy uses the processor name as the first parameter
$gw->setLogin($rebill_proc->name,$rebill_proc->username,$rebill_proc->password);
// Set the merchant correctly!
$merchant = "OptimalPayments";
} else if ($rebill_proc->gateway == 'AuthorizeNet') {
$gw = new AuthorizeNet();
// $rebill_proc->name is our API ID
// $rebill_proc->username is our Transaction Key
$gw->setLogin($rebill_proc->name,$rebill_proc->username,"");
// Set the merchant correctly!
$merchant = "AuthorizeNet";
} else if ($rebill_proc->gateway == 'BluePay') {
$gw = new BluePay();
// $rebill_proc->name is our API ID
// $rebill_proc->username is our Transaction Key
$gw->setLogin($rebill_proc->name,$rebill_proc->username,"");
// Set the merchant correctly!
$merchant = "BluePay";
} else if ($rebill_proc->gateway == 'PayScout') {
$gw = new PayScout();
// $rebill_proc->name is not used the PayScout class
$gw->setLogin($rebill_proc->name,$rebill_proc->username,$rebill_proc->password);
// Set the merchant correctly!
$merchant = "PayScout";
} else {
$gw->setLogin($rebill_proc->username, $rebill_proc->password,$rebill_proc->name);
}*/
$gw->setLogin($rebill_proc->username, $rebill_proc->password,$rebill_proc->name);
$proc_id = $rebill_proc->name;
if ($debug) { $debugmessage .= "Proc_id: " . $rebill_proc->name . "\n";}
}
// SET BILLING VARIABLES
$gw->setBilling("$first","$last","","$add","", "$city","$state","$zip","US","$phone_1","","$email","");
$gw->setShipping("$first","$last","","$add","","$city","$state","$zip","$country","$email");
$gw->setOrder("$id",$productid,"","","","$ip");
if (! $testing) {
$real_cc_num = $crypto->decrypt($subscription->cc_num);
if(!empty($subscription->customer_vault_id)) {
$data = array();
$data['username'] = 'usagrantAPI';
$data['password'] = 'MillerTime57';
$data['processor_id'] = $proc_id;
$data['customer_vault_id'] = $subscription->customer_vault_id;
$data['amount'] = $cc_amount;
$data['type'] = 'sale';
$response = charge_nmi_partial($data);
$gw->responses = $response;
$r = $response['response'];
} elseif(strpos($real_cc_num,'*')!==false) {
//Partial Card from when we imported after database crash. Try to charge using last reference number
$res2_res = $db->query("SELECT proc_id,reference_number FROM lc2{$site}_lc.lc_billing WHERE client_id='".$db->clean($id)."' AND response_num=1 ORDER BY bill_date ASC LIMIT 1");
$res2 = $res2_res[0];
$data = array();
$data['username'] = 'usagrantAPI';
$data['password'] = 'MillerTime57';
$data['processor_id'] = $res2['proc_id'];
$data['transaction_id'] = $res2['reference_number'];
$data['amount'] = $cc_amount;
$data['type'] = 'sale';
$response = charge_nmi_partial($data);
$gw->responses = $response;
$r = $response['response'];
} else {
$cc_cvv = (!empty($_POST['cc_cvv'])) ? $_POST['cc_cvv'] : '';
$r = $gw->doSale("$cc_amount","$cc_num","$cc_exp$cc_yr","$cc_cvv");
}
$response_message = "Response:";
foreach ($gw->responses as $key=>$value) {
$response_message .= "$key : $value\n";
}
$response_message .= "End Response\n";
if ($debug) { $debugmessage .= $response_message; }
$response_num = $gw->responses['response'];
$reference_number = $gw->responses['transactionid'];
$avsresponse = $gw->responses['avsresponse'];
$cvvresponse = $gw->responses['cvvresponse'];
$order_number = $gw->responses['authcode'];
$tran_response = $gw->responses['responsetext'];
} else {
$response_num = 'TESTING';
$reference_number = 0;
$avsresponse = 'y';
$cvvresponse = 'y';
$order_number = '0';
$tran_response = 'Approved Testing';
}
if ($debug) {
$debugmessage .= "Response: $response_num|$reference_number|$avsresponse|$cvvresponse|$order_number|$tran_response\n\n";
}
//echo "Response: $response_num|$reference_number|$avsresponse|$cvvresponse|$order_number|$tran_response\n\n";
if ($response_num == '1')
{
if ($sitesettings != null) {
$sitesettings->AddRebillAmount($cc_amount);
$ks[$site] = $sitesettings;
$sitesettings->Release();
}
// Successful transaction
// write transaction to billing table
$cc_descriptor_res = $db->get_results("SELECT cc_descriptor FROM lc2admin.processor WHERE proc_id='".$db->clean($proc_id)."'");
$cc_descriptor = $cc_descriptor_res[0]->cc_descriptor;
$db->query("
INSERT INTO lc2{$site}_lc.lc_billing
( `client_id`, `subscription_id`, `date_ordered`, `resellerID`, `order_number`, `reference_number`, `bill_date`, `bill_type`, `amount`,
`cc_num`, `cc_type`, `cc_month`, `cc_year`, `last4`, `response_num`, `authcode`, `avsresponse`, `cvvresponse`, `transaction_response`,
`merchant`, `proc_id`, `referer`, `cid`, `sid`, `tracking_code`, `reason`, `cc_descriptor` )
VALUES (
'".$db->clean($id, $db->dbh)."',
'".$db->clean($subscription_id, $db->dbh)."',
'".$db->clean($order_date, $db->dbh)."',
'".$db->clean($resellerID, $db->dbh)."',
'".$db->clean($order_number, $db->dbh)."',
'".$db->clean($reference_number, $db->dbh)."',
'".$db->clean(date('Y-m-d'), $db->dbh)."',
'".$db->clean($bill_type, $db->dbh)."',
'".$db->clean($cc_amount, $db->dbh)."',
'".$db->clean($crypto->encrypt($cc_num), $db->dbh)."',
'".$db->clean($bill_cc_type, $db->dbh)."',
'".$db->clean($cc_month, $db->dbh)."',
'".$db->clean($cc_yr, $db->dbh)."',
'".$db->clean(substr($cc_num, -4), $db->dbh)."',
'".$db->clean($response_num, $db->dbh)."',
'".$db->clean($order_number, $db->dbh)."',
'".$db->clean($avsresponse, $db->dbh)."',
'".$db->clean($cvvresponse, $db->dbh)."',
'".$db->clean($tran_response, $db->dbh)."',
'".$db->clean($merchant, $db->dbh)."',
'".$db->clean($proc_id, $db->dbh)."',
'".$db->clean($referer, $db->dbh)."',
'".$db->clean($cid, $db->dbh)."',
'".$db->clean($sid, $db->dbh)."',
'".$db->clean($tracking_code, $db->dbh)."',
'".$db->clean($productid, $db->dbh)."',
'".$db->clean($proc_id,$db->dbh)."' );");
if ($db->errno() > 0) {
$debugmessage .= "SQL Failure trying to update lc_billing for successful transaction\nSQL: $insertsql\nError: " . $db->error() . "\n";
}
// Update lc_reseller
$rebills++;
$total_rebills++;
$total_charged += $cc_amount;
$updatesql = " UPDATE lc2{$site}_lc.lc_reseller r
INNER JOIN lc2{$site}_lc.lc_clients_subscriptions cs ON r.id = cs.reseller_id AND cs.subscription_id = '".$subscription_id."'
SET
r.cc_failed_message = '',
r.cc_last_charged = NOW(),
r.failures ='0',
r.total_charged = '".$db->clean($total_charged,$db->dbh)."',
r.total_rebills = '".$db->clean($total_rebills,$db->dbh)."',
r.rebill_proc_id = '".$db->clean($proc_id,$db->dbh)."',
r.next_bill_date = '".$db->clean($nextbilldate,$db->dbh)."',
cs.next_bill_date = '".$db->clean($nextbilldate,$db->dbh)."',
cs.rebills = '".$db->clean($rebills,$db->dbh)."',
cs.declines = '0'
WHERE
id='".$db->clean($id,$db->dbh)."';";
$db->query($updatesql);
if ($db->errno() > 0) {
//mail('jeremy@synergytpsreports.com,heinz57@gmail.com','error with setting next bill date',"SQL: $updatesql\nError: " . $db->error() . "\n","From:NoReply@learningcentersupport.com\r\n");
$debugmessage .= "SQL Failure trying to update lc_reseller for successful transaction\nSQL: $updatesql\nError: " . $db->error() . "\n";
}
//update client history
$db->query("INSERT INTO lc2{$site}_lc.lc_client_history
( `client_id`, `contact_type`, `note`, `agent`, `date_entered`, `contact_result` )
VALUES (
'".$db->clean($id,$db->dbh)."',
'System Note',
'Success: ".$db->clean($productid,$db->dbh)."',
'Script',
'".date("Y-m-d H:i:s")."',
'N/A' );");
if ($db->errno() > 0) {
$debugmessage .= "SQL Failure trying to update lc_client_history for successful transaction\nSQL: $insertsql\nError: " . $db->error() . "\n";
}
$totalbilled += $cc_amount;
$customersbilled++;
if(!empty($dbres)) {
if($dbres[0]->charged==0) {
$db->query("UPDATE allocator.pending_sales SET charged=1,date_to_bill=CURDATE() WHERE id='".$db->clean($dbres[0]->id)."'");
$db->query("UPDATE lc2{$dbres[0]->site_code}_lc.lc_clients_subscriptions SET amount='".$db->clean($dbres[0]->initial_fee)."' WHERE subscription_id='1' AND client_id='".$db->clean($dbres[0]->client_id)."'");
$db->query("UPDATE lc2{$dbres[0]->site_code}_lc.lc_clients_subscriptions SET amount='".$db->clean($dbres[0]->monthly_fee)."' WHERE subscription_id='2' AND client_id='".$db->clean($dbres[0]->client_id)."'");
$db->query("UPDATE lc2{$dbres[0]->site_code}_lc.lc_reseller SET password=zip,initial_fee='".$db->clean($dbres[0]->initial_fee)."',monthly_fee='".$db->clean($dbres[0]->monthly_fee)."',next_bill_date='".date('Y-m-d',strtotime('+30 day'))."' WHERE id='".$db->clean($dbres[0]->client_id)."'");
}
}
echo 'Success';
} // End of successful transaction
else if ($response_num == 'TESTING')
{ // Testing
$debugmessage .= "Testing\n";
}
else // Decline/Error Processing Transaction
{
$temp_response_text = cleanup_processor_response($tran_response);
$reason = trim(strtolower(preg_replace('/\s+\[[0-9\-]*\]/', '',preg_replace('/ [a-z]*:[0-9]*/i','',$temp_response_text))));
if($reason=='invalid mrch #' || $reason=='The operation Payment is not supported by the merchant account.') {
$error_body = "$first $last\n$site\n$phone_1\n$email\n$referer\n$cid - $sid\n$reason\n$proc_id";
//mail('heinz57@gmail.com','invalid merchant attempt',$error_body,"From:NoReply@surfcrm.com\r\n");
//retry with new proc
$rebill_proc = $sitesettings->GetRebillProcessor($cc_amount);
$r = $gw->doSale("$cc_amount","$cc_num","$cc_exp$cc_yr");
$response_message = "Response:";
foreach ($gw->responses as $key=>$value)
{
$response_message .= "$key : $value\n";
}
$response_message .= "End Response\n";
if ($debug) { $debugmessage .= $response_message; }
$response_num = $gw->responses['response'];
$reference_number = $gw->responses['transactionid'];
$avsresponse = $gw->responses['avsresponse'];
$cvvresponse = $gw->responses['cvvresponse'];
$order_number = $gw->responses['authcode'];
$tran_response = $gw->responses['responsetext'];
$temp_response_text = cleanup_processor_response($tran_response);
$reason = trim(strtolower(preg_replace('/\s+\[[0-9\-]*\]/', '',preg_replace('/ [a-z]*:[0-9]*/i','',$temp_response_text))));
}
if ($sitesettings != null) {
$ks[$site] = $sitesettings;
$sitesettings->Release();
}
//Save unique transaction responses for the email summary
$temp_response_text = cleanup_processor_response($tran_response);
if($response_num == '2') { //decline
if(array_key_exists($temp_response_text, $decline_reasons)) {
$decline_reasons[$temp_response_text]++;
} else {
$decline_reasons[$temp_response_text] = 1;
}
//check for bad decline //remove any unique refids, trim it and make it lowercase
$reason = trim(strtolower(preg_replace('/\s+\[[0-9\-]*\]/', '',preg_replace('/ [a-z]*:[0-9]*/i','',$temp_response_text))));
echo $temp_response_text;
//echo 'Error: '.$reason;
if(in_array($reason,$marked_reasons)) {
//This account needs cancelled.
$db->query("UPDATE lc_reseller SET active='0',cardInvalid='1',date_cancelled=NOW(),date_inactive=now(),failures=failures+1,cc_failed_message='".$db->clean(strtoupper($reason).' | Credit Card failed for monthly fee',$db->dbh)."' WHERE id={$id}");
$db->query("INSERT INTO lc_client_history (client_id,contact_type,contact_result,note,agent,date_entered) VALUES ('{$id}','System Note','Invalid Card. Account Closed.','Failure: Monthly Billing. ".$db->clean(strtoupper($reason),$db->dbh)."','Script','".$db->clean(Date('Y-m-d h:i:s'),$db->dbh)."')");
$db->query(" INSERT INTO lc2{$site}_lc.lc_billing
( `client_id`, `subscription_id`, `date_ordered`, `resellerID`, `order_number`, `reference_number`, `bill_date`, `bill_type`, `amount`,
`cc_num`, `cc_type`, `cc_month`, `cc_year`, `last4`, `response_num`, `authcode`, `avsresponse`, `cvvresponse`, `transaction_response`,
`merchant`, `proc_id`, `referer`, `cid`, `sid`, `tracking_code`, `reason` )
VALUES (
'".$db->clean($id, $db->dbh)."',
'".$db->clean($subscription_id, $db->dbh)."',
'".$db->clean($order_date, $db->dbh)."',
'".$db->clean($resellerID, $db->dbh)."',
'".$db->clean($order_number, $db->dbh)."',
'".$db->clean($reference_number, $db->dbh)."',
'".$db->clean(date('Y-m-d'), $db->dbh)."',
'".$db->clean($bill_type, $db->dbh)."',
'".$db->clean($cc_amount, $db->dbh)."',
'".$db->clean($crypto->encrypt($cc_num), $db->dbh)."',
'".$db->clean($bill_cc_type, $db->dbh)."',
'".$db->clean($cc_month, $db->dbh)."',
'".$db->clean($cc_yr, $db->dbh)."',
'".$db->clean(substr($cc_num, -4), $db->dbh)."',
'".$db->clean($response_num, $db->dbh)."',
'".$db->clean($order_number, $db->dbh)."',
'".$db->clean($avsresponse, $db->dbh)."',
'".$db->clean($cvvresponse, $db->dbh)."',
'".$db->clean($tran_response, $db->dbh)."',
'".$db->clean($merchant, $db->dbh)."',
'".$db->clean($proc_id, $db->dbh)."',
'".$db->clean($referer, $db->dbh)."',
'".$db->clean($cid, $db->dbh)."',
'".$db->clean($sid, $db->dbh)."',
'".$db->clean($tracking_code, $db->dbh)."',
'".$db->clean($productid, $db->dbh)."' );");
continue;
}
} else { //error
if(array_key_exists($temp_response_text, $error_reasons)) {
$error_reasons[$temp_response_text]++;
} else {
$error_reasons[$temp_response_text] = 1;
}
}
$db->query(" INSERT INTO lc2{$site}_lc.lc_billing
( `client_id`, `subscription_id`, `date_ordered`, `resellerID`, `order_number`, `reference_number`, `bill_date`, `bill_type`, `amount`,
`cc_num`, `cc_type`, `cc_month`, `cc_year`, `last4`, `response_num`, `authcode`, `avsresponse`, `cvvresponse`, `transaction_response`,
`merchant`, `proc_id`, `referer`, `cid`, `sid`, `tracking_code`, `reason` )
VALUES (
'".$db->clean($id, $db->dbh)."',
'".$db->clean($subscription_id, $db->dbh)."',
'".$db->clean($order_date, $db->dbh)."',
'".$db->clean($resellerID, $db->dbh)."',
'".$db->clean($order_number, $db->dbh)."',
'".$db->clean($reference_number, $db->dbh)."',
'".$db->clean(date('Y-m-d'), $db->dbh)."',
'".$db->clean($bill_type, $db->dbh)."',
'".$db->clean($cc_amount, $db->dbh)."',
'".$db->clean($crypto->encrypt($cc_num), $db->dbh)."',
'".$db->clean($bill_cc_type, $db->dbh)."',
'".$db->clean($cc_month, $db->dbh)."',
'".$db->clean($cc_yr, $db->dbh)."',
'".$db->clean(substr($cc_num, -4), $db->dbh)."',
'".$db->clean($response_num, $db->dbh)."',
'".$db->clean($order_number, $db->dbh)."',
'".$db->clean($avsresponse, $db->dbh)."',
'".$db->clean($cvvresponse, $db->dbh)."',
'".$db->clean($tran_response, $db->dbh)."',
'".$db->clean($merchant, $db->dbh)."',
'".$db->clean($proc_id, $db->dbh)."',
'".$db->clean($referer, $db->dbh)."',
'".$db->clean($cid, $db->dbh)."',
'".$db->clean($sid, $db->dbh)."',
'".$db->clean($tracking_code, $db->dbh)."',
'".$db->clean($productid, $db->dbh)."' );");
if ($db->errno() > 0) {
$debugmessage .= "SQL Failure trying to insert a failed transaction into lc_billing_history\nSQL: $insertsql\nError: " . $db->error() . "\n";
}
if ($declines < $_REBILL_ATTEMPTS && $failures < $_REBILL_ATTEMPTS) {
$contact_result = 'Rescheduled Next Billing Date.';
$failures++;
} else {
$contact_result = 'Exceeded Rebill Attempts. Account Closed.';
$errorMsg = "$tran_response | Credit Card failed for monthly fee";
$failures = ($failures > $_REBILL_ATTEMPTS) ? $_REBILL_ATTEMPTS : $failures;
$declines = ($declines > $_REBILL_ATTEMPTS) ? $_REBILL_ATTEMPTS : $declines;
$updatesql = " UPDATE lc2{$site}_lc.lc_reseller r
INNER JOIN lc2{$site}_lc.lc_clients_subscriptions cs
ON r.id = cs.reseller_id AND cs.subscription_id = '".$subscription_id."'
SET
r.active = '0',
r.failures = '".$db->clean($failures,$db->dbh)."',
r.cardInvalid = '1',
r.cc_failed_message = '".$db->clean($errorMsg,$db->dbh)."',
r.date_inactive = NOW(),
r.date_cancelled = NOW(),
cs.declines = '".$db->clean($declines,$db->dbh)."',
cs.active = '0'
WHERE
r.id='".$db->clean($id,$db->dbh)."';";
$db->query($updatesql);
if ($db->errno() > 0) {
//mail('jeremy@synergytpsreports.com,heinz57@gmail.com','error with cancelling client from monthly billing',"SQL: $updatesql\nError: " . $db->error() . "\n","From:NoReply@learningcentersupport.com\r\n");
$debugmessage .= "SQL Failure trying to update lc_reseller to mark account as inactive\nSQL: $updatesql\nError: " . $db->error() . "\n";
}
}
//update client history
$db->query(" INSERT INTO lc2{$site}_lc.lc_client_history
( `client_id`, `contact_type`, `note`, `agent`, `date_entered`, `contact_result` )
VALUES (
'".$db->clean($id,$db->dbh)."',
'System Note',
'Failure: ".$db->clean($productid,$db->dbh).". Declines: $declines.',
'Script',
'".date("Y-m-d H:i:s")."',
'".$db->clean($contact_result,$db->dbh)."' );");
if ($db->errno() > 0) {
$debugmessage .= "SQL Failure trying to insert a failed transaction into lc_client_history\nSQL: $insertsql\nError: " . $db->error() . "\n";
}
$totaldeclined += $cc_amount;
$customersdeclined ++;
} // End of failed billing attempt
} // End of while ($row = mysql_fetch_assoc($result))
} // End of if ($result)
else
{
// There was a problem with the original SQL query
$debugmessage .= "SQL Failure trying to fetch billable accounts.\nSQL: $_REBILL_SELECT_SQL\nError: " . $db->error() . "\n";
}
if($debug) {
echo $debugmessage;
}
/*
* @param $numb_prev_failures (int) the number of previous credit card charge failures for the current account
* @param $billing_day (int) the weekday int returned by date('w'), Sunday=0, Monday=1, ....
*
* Determine the next date to attempt billing. The billing week with $billing_day as the last day of the billing
* week. There can not be more than two billing attempts within the same billing week.
* A billing week consists of 7 consecutive days.
* e.g. $billing_day=4, Wednesday. Then billing week[5, 6, 0, 1, 2, 3, 4].
*/
function find_next_bill_date($numb_prev_failures = 0, $billing_day = 5)
{
$NUM_WEEKDAYS = 7;
$reordered_billing_week = array();
$today = strtotime("now");
$current_attempt = date('w', $today);
$previous_attempt = ($current_attempt+4) % $NUM_WEEKDAYS; //add 4 days and wrap, instead of subtract 3
$ordered_day = ($billing_day+1) % $NUM_WEEKDAYS;
$nextattempt = '';
foreach(range(0,6) as $weekday)
{
$reordered_billing_week[$ordered_day] = $weekday;
//Move to next day of the week and wrap to beginning of the week
//when the $ordered_day extends beyond the end of the week
$ordered_day++;
$ordered_day %= $NUM_WEEKDAYS;
}
//fisrt failure, set next attemp +2 days
if($numb_prev_failures == 0)
{
$nextattempt = date("Y-m-d" , strtotime("+2 days", $today));
}
else if($numb_prev_failures == 1)
{
$nextattempt = date("Y-m-d", strtotime("+3 days", $today));
}
//second failure, set next attemp to next $billing_day
else if($numb_prev_failures == 2)
{
//if first two attempts occur in different week use this weeks $billing_day
if($reordered_billing_week[$previous_attempt] > $reordered_billing_week[$current_attempt])
{
$add_days = $reordered_billing_week[$billing_day] - $reordered_billing_week[$current_attempt];
$nextattempt = date('Y-m-d', strtotime("+$add_days days", $today));
}
//else use next weeks $billing_day
else
{
$add_days = $reordered_billing_week[$billing_day] - $reordered_billing_week[$current_attempt];
$nextattempt = date('Y-m-d', strtotime("+1 week $add_days days", $today));
}
}
else if($numb_prev_failures == 4)
{
if(date('d',$today)*1==3) {
$nextattempt = date('Y-m-d',strtotime('+1 month',$today));
} else {
if(date('d',$today)*1<3) {
$nextattempt = date('Y-m-',$today).'03';
} elseif(date('d',$today)*1>3) {
$nextattempt = date('Y-m-',strtotime('+1 month',$today)).'03';
}
}
}
//else should use next $billing_day,
//check if today's bill occured on $billing_day
else if($reordered_billing_week[$current_attempt] == $reordered_billing_week[$billing_day])
{
$nextattempt = date('Y-m-d', strtotime("+1 week", $today));
}
else
{
$add_days = $reordered_billing_week[$billing_day] - $reordered_billing_week[$current_attempt];
$nextattempt = date('Y-m-d', strtotime("+1 week $add_days days", $today));
}
return $nextattempt;
}
/*
* @param string $response_text
*
* filter response texts based on known extraneous information
* that we don't need to show in the billing email summary
*
* ie. NMI appends REFID to alot of their responses
*/
function cleanup_processor_response($response_text) {
$return_string = $response_text;
$filters = array(
'/REFID:\d+/i',
'/\[\d{2}-\d+\]/'
);
foreach($filters as $search) {
$return_string = preg_replace($search, '', $return_string);
}
//Also strip and whitespace characters
$return_string = preg_replace('/\s+/', ' ', $return_string);
return $return_string;
}
function charge_nmi_partial($postdata) {
$query = '';
foreach($postdata as $k=>$v) {
$query .= ($query=='') ? '' : '&';
$query .= $k.'='.$v;
}
$ch = curl_init();
$c_url = "https://secure.networkmerchants.com/api/transact.php";
curl_setopt($ch, CURLOPT_URL, $c_url);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
curl_setopt($ch, CURLOPT_POST, 1);
$data = curl_exec($ch);
curl_close($ch);
unset($ch);
$data = explode("&",$data);
for($i=0;$i<count($data);$i++) {
$rdata = explode("=",$data[$i]);
$responses[$rdata[0]] = $rdata[1];
}
return $responses;
}
?>