<?php
/*
+ * This file is part of CiviCRM.
+ *
+ * CiviCRM is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * CiviCRM is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with CiviCRM. If not, see <http://www.gnu.org/licenses/>.
+ *
* Copyright (C) 2012
* Licensed to CiviCRM under the GPL v3 or higher
*
* Written and contributed by Ward Vandewege <ward@fsf.org> (http://www.fsf.org)
+ * Modified by Lisa Marie Maginnis <lisa@fsf.org> (http://www.fsf.org)
*
*/
CONST AUTH_DECLINED = 'decline';
CONST AUTH_BADDATA = 'baddata';
CONST AUTH_ERROR = 'error';
+ CONST AUTH_BLACKLIST = 'blacklisted';
static protected $_mode = NULL;
srand(time());
$this->_setParam('sequence', rand(1, 1000));
$this->logging_level = TRUSTCOMMERCE_LOGGING_LEVEL;
+
}
/**
}
/**
- * Submit a payment using Advanced Integration Method
- *
- * @param array $params assoc array of input parameters for this transaction
- *
- * @return array the result in a nice formatted array (or an error object)
+ * Submit a payment using the TC API
+ * @param array $params The params we will be sending to tclink_send()
+ * @return mixed An array of our results, or an error object if the transaction fails.
* @public
*/
function doDirectPayment(&$params) {
return self::error(9001, 'TrustCommerce requires that the tclink module is loaded');
}
- /*
- * recurpayment function does not compile an array & then proces it -
- * - the tpl does the transformation so adding call to hook here
- * & giving it a change to act on the params array
- */
-
- $newParams = $params;
- if (CRM_Utils_Array::value('is_recur', $params) &&
- $params['contributionRecurID']
- ) {
- CRM_Utils_Hook::alterPaymentProcessorParams($this,
- $params,
- $newParams
- );
- }
- foreach ($newParams as $field => $value) {
+ /* Copy our paramaters to ourself */
+ foreach ($params as $field => $value) {
$this->_setParam($field, $value);
}
- if (CRM_Utils_Array::value('is_recur', $params) &&
- $params['contributionRecurID']
- ) {
- return $this->doRecurPayment($params);
- }
+ /* Get our fields to pass to tclink_send() */
+ $tc_params = $this->_getTrustCommerceFields();
- $postFields = array();
- $tclink = $this->_getTrustCommerceFields();
+ /* Are we recurring? If so add the extra API fields. */
+ if (CRM_Utils_Array::value('is_recur', $params) && $params['contributionRecurID']) {
+ $tc_params = $this->_getRecurPaymentFields($tc_params);
+ }
- // Set up our call for hook_civicrm_paymentProcessor,
- // since we now have our parameters as assigned for the AIM back end.
- CRM_Utils_Hook::alterPaymentProcessorParams($this,
- $params,
- $tclink
- );
+ /* Pass our cooked params to the alter hook, per Core/Payment/Dummy.php */
+ CRM_Utils_Hook::alterPaymentProcessorParams($this, $params, $tc_params);
// TrustCommerce will not refuse duplicates, so we should check if the user already submitted this transaction
- if ($this->_checkDupe($tclink['ticket'])) {
+ if ($this->_checkDupe($tc_params['ticket'])) {
return self::error(9004, 'It appears that this transaction is a duplicate. Have you already submitted the form once? If so there may have been a connection problem. You can try your transaction again. If you continue to have problems please contact the site administrator.');
}
- $result = tclink_send($tclink);
+ /* This implements a local blacklist, and passes us though as a normal failure
+ * if the luser is on the blacklist. */
+ if(!$this->_isBlacklisted()) {
+ /* Call the TC API, and grab the reply */
+ $reply = $this->_sendTCRequest($tc_params);
+ } else {
+ $this->_logger($tc_params);
+ $reply['status'] = self::AUTH_BLACKLIST;
+ }
- if (!$result) {
- return self::error(9002, 'Could not initiate connection to payment gateway');
+ /* Parse our reply */
+ $result = $this->_getTCReply($reply);
+
+ if($result == 0) {
+ /* We were successful, congrats. Lets wrap it up:
+ * Convert back to dollars
+ * Save the transaction ID
+ */
+
+ if (CRM_Utils_Array::value('is_recur', $params) && $params['contributionRecurID']) {
+ $params['contributionRecurID'] = $reply['billingid'];
+ }
+ $params['trxn_id'] = $reply['transid'];
+
+ $params['gross_amount'] = $tc_params['amount'] / 100;
+
+ return $params;
+
+ } else {
+ /* Otherwise we return the error object */
+ return $result;
}
+ }
- foreach ($result as $field => $value) {
- error_log("result: $field => $value");
+ function _isBlacklisted() {
+ if($this->_isIPBlacklisted()) {
+ return TRUE;
+ } else if($this->_IsAgentBlacklisted()) {
+ return TRUE;
+ }
+ return FALSE;
+ }
+
+ function _isAgentBlacklisted() {
+ $ip = $_SERVER['REMOTE_ADDR'];
+ $agent = $_SERVER['HTTP_USER_AGENT'];
+ $dao = CRM_Core_DAO::executeQuery('SELECT * FROM `trustcommerce_useragent_blacklist`');
+ while($dao->fetch()) {
+ if(preg_match('/'.$dao->name.'/', $agent) === 1) {
+ error_log(' [client '.$ip.'] [agent '.$agent.'] - Blacklisted by USER_AGENT rule #'.$dao->id);
+ return TRUE;
+ }
}
+ return FALSE;
+ }
- switch($result['status']) {
- case self::AUTH_APPROVED:
- // It's all good
- break;
- case self::AUTH_DECLINED:
- // TODO FIXME be more or less specific?
- // declinetype can be: decline, avs, cvv, call, expiredcard, carderror, authexpired, fraud, blacklist, velocity
- // See TC documentation for more info
- return self::error(9009, "Your transaction was declined: {$result['declinetype']}");
- break;
- case self::AUTH_BADDATA:
- // TODO FIXME do something with $result['error'] and $result['offender']
- return self::error(9011, "Invalid credit card information. Please re-enter.");
- break;
- case self::AUTH_ERROR:
- return self::error(9002, 'Could not initiate connection to payment gateway');
- break;
+ function _isIPBlacklisted() {
+ $ip = $_SERVER['REMOTE_ADDR'];
+ $agent = $_SERVER['HTTP_USER_AGENT'];
+ $ip = ip2long($ip);
+ $blacklist = array();
+ $dao = CRM_Core_DAO::executeQuery('SELECT * FROM `trustcommerce_blacklist`');
+ while($dao->fetch()) {
+ if($ip >= $dao->start && $ip <= $dao->end) {
+ error_log('[client '.long2ip($ip).'] [agent '.$agent.'] Blacklisted by IP rule #'.$dao->id);
+ return TRUE;
+ }
}
-
- // Success
+ return FALSE;
+ }
- $params['trxn_id'] = $result['transid'];
- $params['gross_amount'] = $tclink['amount'] / 100;
+ function _sendTCRequest($request) {
+ $this->_logger($request);
+ return tclink_send($request);
+ }
- return $params;
+ function _logger($params) {
+ $msg = '';
+ foreach ($params as $key => $data) {
+ /* Delete any data we should not be writing to disk. This includes:
+ * custid, password, cc, exp, and cvv
+ */
+ switch($key) {
+ case 'custid':
+ case 'password':
+ case 'cc':
+ case 'exp':
+ case 'cvv':
+ break;
+ default:
+ $msg .= ' '.$key.' => '.$data;
+ }
+ }
+ error_log('[client '.$_SERVER['REMOTE_ADDR'].'] TrustCommerce:'.$msg);
}
/**
- * Submit an Automated Recurring Billing subscription
- *
- * @param array $params assoc array of input parameters for this transaction
- *
- * @return array the result in a nice formatted array (or an error object)
+ * Gets the recurring billing fields for the TC API
+ * @param array $fields The fields to modify.
+ * @return array The fields for tclink_send(), modified for recurring billing.
* @public
*/
- function doRecurPayment(&$params) {
- $template = CRM_Core_Smarty::singleton();
-
- $intervalLength = $this->_getParam('frequency_interval');
- $intervalUnit = $this->_getParam('frequency_unit');
- if ($intervalUnit == 'week') {
- $intervalLength *= 7;
- $intervalUnit = 'days';
- }
- elseif ($intervalUnit == 'year') {
- $intervalLength *= 12;
- $intervalUnit = 'months';
- }
- elseif ($intervalUnit == 'day') {
- $intervalUnit = 'days';
- }
- elseif ($intervalUnit == 'month') {
- $intervalUnit = 'months';
- }
-
- // interval cannot be less than 7 days or more than 1 year
- if ($intervalUnit == 'days') {
- if ($intervalLength < 7) {
- return self::error(9001, 'Payment interval must be at least one week');
- }
- elseif ($intervalLength > 365) {
- return self::error(9001, 'Payment interval may not be longer than one year');
- }
- }
- elseif ($intervalUnit == 'months') {
- if ($intervalLength < 1) {
- return self::error(9001, 'Payment interval must be at least one week');
- }
- elseif ($intervalLength > 12) {
- return self::error(9001, 'Payment interval may not be longer than one year');
- }
+ function _getRecurPaymentFields($fields) {
+ $payments = $this->_getParam('frequency_interval');
+ $cycle = $this->_getParam('frequency_unit');
+
+ /* Translate billing cycle from CiviCRM -> TC */
+ switch($cycle) {
+ case 'day':
+ $cycle = 'd';
+ break;
+ case 'week':
+ $cycle = 'w';
+ break;
+ case 'month':
+ $cycle = 'm';
+ break;
+ case 'year':
+ $cycle = 'y';
+ break;
}
- $template->assign('intervalLength', $intervalLength);
- $template->assign('intervalUnit', $intervalUnit);
-
- $template->assign('apiLogin', $this->_getParam('apiLogin'));
- $template->assign('paymentKey', $this->_getParam('paymentKey'));
- $template->assign('refId', substr($this->_getParam('invoiceID'), 0, 20));
-
- //for recurring, carry first contribution id
- $template->assign('invoiceNumber', $this->_getParam('contributionID'));
- $firstPaymentDate = $this->_getParam('receive_date');
- if (!empty($firstPaymentDate)) {
- //allow for post dated payment if set in form
- $template->assign('startDate', date('Y-m-d', strtotime($firstPaymentDate)));
+ /* Translate frequency interval from CiviCRM -> TC
+ * Payments are the same, HOWEVER a payment of 1 (forever) should be 0 in TC */
+ if($payments == 1) {
+ $payments = 0;
}
- else {
- $template->assign('startDate', date('Y-m-d'));
- }
- // for open ended subscription totalOccurrences has to be 9999
- $installments = $this->_getParam('installments');
- $template->assign('totalOccurrences', $installments ? $installments : 9999);
- $template->assign('amount', $this->_getParam('amount'));
+ $fields['cycle'] = '1'.$cycle; /* The billing cycle in years, months, weeks, or days. */
+ $fields['payments'] = $payments;
+ $fields['authnow'] = 'y';
+ $fields['action'] = 'store'; /* Change our mode to `store' mode. */
- $template->assign('cardNumber', $this->_getParam('credit_card_number'));
- $exp_month = str_pad($this->_getParam('month'), 2, '0', STR_PAD_LEFT);
- $exp_year = $this->_getParam('year');
- $template->assign('expirationDate', $exp_year . '-' . $exp_month);
- // name rather than description is used in the tpl - see http://www.authorize.net/support/ARB_guide.pdf
- $template->assign('name', $this->_getParam('description'));
-
- $template->assign('email', $this->_getParam('email'));
- $template->assign('contactID', $this->_getParam('contactID'));
- $template->assign('billingFirstName', $this->_getParam('billing_first_name'));
- $template->assign('billingLastName', $this->_getParam('billing_last_name'));
- $template->assign('billingAddress', $this->_getParam('street_address'));
- $template->assign('billingCity', $this->_getParam('city'));
- $template->assign('billingState', $this->_getParam('state_province'));
- $template->assign('billingZip', $this->_getParam('postal_code'));
- $template->assign('billingCountry', $this->_getParam('country'));
-
- $arbXML = $template->fetch('CRM/Contribute/Form/Contribution/AuthorizeNetARB.tpl');
- // submit to authorize.net
-
- $submit = curl_init($this->_paymentProcessor['url_recur']);
- if (!$submit) {
- return self::error(9002, 'Could not initiate connection to payment gateway');
- }
- curl_setopt($submit, CURLOPT_RETURNTRANSFER, 1);
- curl_setopt($submit, CURLOPT_HTTPHEADER, array("Content-Type: text/xml"));
- curl_setopt($submit, CURLOPT_HEADER, 1);
- curl_setopt($submit, CURLOPT_POSTFIELDS, $arbXML);
- curl_setopt($submit, CURLOPT_POST, 1);
- curl_setopt($submit, CURLOPT_SSL_VERIFYPEER, 0);
+ return $fields;
+ }
- $response = curl_exec($submit);
+ /* Parses a response from TC via the tclink_send() command.
+ * @param $reply array The result of a call to tclink_send().
+ * @return mixed self::error() if transaction failed, otherwise returns 0.
+ */
+ function _getTCReply($reply) {
- if (!$response) {
- return self::error(curl_errno($submit), curl_error($submit));
+ /* DUPLIATE CODE, please refactor. ~lisa */
+ if (!$reply) {
+ return self::error(9002, 'Could not initiate connection to payment gateway');
}
- curl_close($submit);
- $responseFields = $this->_ParseArbReturn($response);
+ $this->_logger($reply);
- if ($responseFields['resultCode'] == 'Error') {
- return self::error($responseFields['code'], $responseFields['text']);
- }
-
- // update recur processor_id with subscriptionId
- CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_ContributionRecur', $params['contributionRecurID'],
- 'processor_id', $responseFields['subscriptionId']
- );
- //only impact of assigning this here is is can be used to cancel the subscription in an automated test
- // if it isn't cancelled a duplicate transaction error occurs
- if (CRM_Utils_Array::value('subscriptionId', $responseFields)) {
- $this->_setParam('subscriptionId', $responseFields['subscriptionId']);
+ switch($reply['status']) {
+ case self::AUTH_BLACKLIST:
+ return self::error(9001, "Your transaction was declined: error #90210");
+ break;
+ case self::AUTH_APPROVED:
+ // It's all good
+ break;
+ case self::AUTH_DECLINED:
+ // TODO FIXME be more or less specific?
+ // declinetype can be: decline, avs, cvv, call, expiredcard, carderror, authexpired, fraud, blacklist, velocity
+ // See TC documentation for more info
+ switch($reply['declinetype']) {
+ case 'avs':
+ return self::error(9009, "Your transaction was declined for address verification reasons. If your address was correct please contact us at donate@fsf.org before attempting to retry your transaction.");
+ break;
+ }
+ return self::error(9009, "Your transaction was declined: {$reply['declinetype']}");
+ break;
+ case self::AUTH_BADDATA:
+ // TODO FIXME do something with $reply['error'] and $reply['offender']
+ return self::error(9011, "Invalid credit card information. The following fields were invalid: {$reply['offenders']}.");
+ break;
+ case self::AUTH_ERROR:
+ return self::error(9002, 'Could not initiate connection to payment gateway');
+ break;
}
- return $params;
+ return 0;
}
function _getTrustCommerceFields() {
if ($this->_mode != 'live') {
$fields['demo'] = 'y';
}
- // TODO FIXME remove
- foreach ($fields as $field => $value) {
- if ($field == 'custid') $value = '********';
- if ($field == 'password') $value = '********';
- if ($field == 'cc') $value = '********';
- if ($field == 'cvv') $value = '********';
- if ($field == 'exp') $value = '********';
- error_log("fields: $field => $value");
- }
-
return $fields;
}
}
}
- function cancelSubscriptionURL($entityID = NULL, $entity = NULL) {
- if ($entityID && $entity == 'membership') {
- require_once 'CRM/Contact/BAO/Contact/Utils.php';
- $contactID = CRM_Core_DAO::getFieldValue("CRM_Member_DAO_Membership", $entityID, "contact_id");
- $checksumValue = CRM_Contact_BAO_Contact_Utils::generateChecksum($contactID, NULL, 'inf');
+ function cancelSubscription(&$message = '', $params = array()) {
+ $tc_params['custid'] = $this->_getParam('user_name');
+ $tc_params['password'] = $this->_getParam('password');
+ $tc_params['action'] = 'unstore';
+ $tc_params['billingid'] = CRM_Utils_Array::value('trxn_id', $params);
+
+ $result = $this->_sendTCRequest($tc_params);
- return CRM_Utils_System::url('civicrm/contribute/unsubscribe',
- "reset=1&mid={$entityID}&cs={$checksumValue}", TRUE, NULL, FALSE, FALSE
- );
+ /* Test if call failed */
+ if(!$result) {
+ return self::error(9002, 'Could not initiate connection to payment gateway');
}
-
- return ($this->_mode == 'test') ? 'https://test.authorize.net' : 'https://authorize.net';
+ /* We are done, pass success */
+ return TRUE;
}
- function cancelSubscription() {
- $template = CRM_Core_Smarty::singleton();
+ function changeSubscriptionAmount(&$message = '', $params = array()) {
+ $tc_params['custid'] = $this->_getParam('user_name');
+ $tc_params['password'] = $this->_getParam('password');
+ $tc_params['action'] = 'store';
- $template->assign('subscriptionType', 'cancel');
+ $tc_params['billingid'] = CRM_Utils_Array::value('subscriptionId', $params);
+ $tc_params['payments'] = CRM_Utils_Array::value('installments', $params);
+ $tc_params['amount'] = CRM_Utils_Array::value('amount', $params) * 100;
- $template->assign('apiLogin', $this->_getParam('apiLogin'));
- $template->assign('paymentKey', $this->_getParam('paymentKey'));
- $template->assign('subscriptionId', $this->_getParam('subscriptionId'));
-
- $arbXML = $template->fetch('CRM/Contribute/Form/Contribution/AuthorizeNetARB.tpl');
-
- // submit to authorize.net
- $submit = curl_init($this->_paymentProcessor['url_recur']);
- if (!$submit) {
- return self::error(9002, 'Could not initiate connection to payment gateway');
+ if($tc_params['payments'] == 1) {
+ $tc_params['payments'] = 0;
}
+ $reply = $this->_sendTCRequest($tc_params);
+ $result = $this->_getTCReply($reply);
- curl_setopt($submit, CURLOPT_RETURNTRANSFER, 1);
- curl_setopt($submit, CURLOPT_HTTPHEADER, array("Content-Type: text/xml"));
- curl_setopt($submit, CURLOPT_HEADER, 1);
- curl_setopt($submit, CURLOPT_POSTFIELDS, $arbXML);
- curl_setopt($submit, CURLOPT_POST, 1);
- curl_setopt($submit, CURLOPT_SSL_VERIFYPEER, 0);
-
- $response = curl_exec($submit);
-
- if (!$response) {
- return self::error(curl_errno($submit), curl_error($submit));
+ /* Test if call failed */
+ if(!$result) {
+ return self::error(9002, 'Could not initiate connection to payment gateway');
}
- curl_close($submit);
-
- $responseFields = $this->_ParseArbReturn($response);
+ /* We are done, pass success */
+ return TRUE;
- if ($responseFields['resultCode'] == 'Error') {
- return self::error($responseFields['code'], $responseFields['text']);
}
- // carry on cancelation procedure
- return TRUE;
- }
-
public function install() {
return TRUE;
}
}
}
-
-