3 * This file is part of CiviCRM.
5 * CiviCRM is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
10 * CiviCRM is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with CiviCRM. If not, see <http://www.gnu.org/licenses/>.
19 * Licensed to CiviCRM under the GPL v3 or higher
21 * Written and contributed by Ward Vandewege <ward@fsf.org> (http://www.fsf.org)
22 * Modified by Lisa Marie Maginnis <lisa@fsf.org> (http://www.fsf.org)
26 // Define logging level (0 = off, 4 = log everything)
27 define('TRUSTCOMMERCE_LOGGING_LEVEL', 4);
29 require_once 'CRM/Core/Payment.php';
30 class org_fsf_payment_trustcommerce
extends CRM_Core_Payment
{
31 CONST CHARSET
= 'iso-8859-1';
32 CONST AUTH_APPROVED
= 'approve';
33 CONST AUTH_DECLINED
= 'decline';
34 CONST AUTH_BADDATA
= 'baddata';
35 CONST AUTH_ERROR
= 'error';
36 CONST AUTH_BLACKLIST
= 'blacklisted';
38 static protected $_mode = NULL;
40 static protected $_params = array();
43 * We only need one instance of this object. So we use the singleton
44 * pattern and cache the instance in this variable
49 static private $_singleton = NULL;
54 * @param string $mode the mode of operation: live or test
57 */ function __construct($mode, &$paymentProcessor) {
60 $this->_paymentProcessor
= $paymentProcessor;
62 $this->_processorName
= ts('TrustCommerce');
64 $config = CRM_Core_Config
::singleton();
65 $this->_setParam('user_name', $paymentProcessor['user_name']);
66 $this->_setParam('password', $paymentProcessor['password']);
68 $this->_setParam('timestamp', time());
70 $this->_setParam('sequence', rand(1, 1000));
71 $this->logging_level
= TRUSTCOMMERCE_LOGGING_LEVEL
;
76 * singleton function used to manage this object
78 * @param string $mode the mode of operation: live or test
85 function &singleton($mode, &$paymentProcessor) {
86 $processorName = $paymentProcessor['name'];
87 if (self
::$_singleton[$processorName] === NULL) {
88 self
::$_singleton[$processorName] = new org_fsf_payment_trustcommerce($mode, $paymentProcessor);
90 return self
::$_singleton[$processorName];
94 * Submit a payment using the TC API
95 * @param array $params The params we will be sending to tclink_send()
96 * @return mixed An array of our results, or an error object if the transaction fails.
99 function doDirectPayment(&$params) {
100 if (!extension_loaded("tclink")) {
101 return self
::error(9001, 'TrustCommerce requires that the tclink module is loaded');
104 /* Copy our paramaters to ourself */
105 foreach ($params as $field => $value) {
106 $this->_setParam($field, $value);
109 /* Get our fields to pass to tclink_send() */
110 $tc_params = $this->_getTrustCommerceFields();
112 /* Are we recurring? If so add the extra API fields. */
113 if (CRM_Utils_Array
::value('is_recur', $params) && $params['contributionRecurID']) {
114 $tc_params = $this->_getRecurPaymentFields($tc_params);
117 /* Pass our cooked params to the alter hook, per Core/Payment/Dummy.php */
118 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $tc_params);
120 // TrustCommerce will not refuse duplicates, so we should check if the user already submitted this transaction
121 if ($this->_checkDupe($tc_params['ticket'])) {
122 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.');
125 /* This implements a local blacklist, and passes us though as a normal failure
126 * if the luser is on the blacklist. */
127 if(!$this->_isBlacklisted()) {
128 /* Call the TC API, and grab the reply */
129 $reply = $this->_sendTCRequest($tc_params);
131 $this->_logger($tc_params);
132 $reply['status'] = self
::AUTH_BLACKLIST
;
135 /* Parse our reply */
136 $result = $this->_getTCReply($reply);
139 /* We were successful, congrats. Lets wrap it up:
140 * Convert back to dollars
141 * Save the transaction ID
144 if (CRM_Utils_Array
::value('is_recur', $params) && $params['contributionRecurID']) {
145 $params['contributionRecurID'] = $reply['billingid'];
147 $params['trxn_id'] = $reply['transid'];
149 $params['gross_amount'] = $tc_params['amount'] / 100;
154 /* Otherwise we return the error object */
159 function _isBlacklisted() {
160 if($this->_isIPBlacklisted()) {
162 } else if($this->_IsAgentBlacklisted()) {
168 function _isAgentBlacklisted() {
169 $ip = $_SERVER['REMOTE_ADDR'];
170 $agent = $_SERVER['HTTP_USER_AGENT'];
171 $dao = CRM_Core_DAO
::executeQuery('SELECT * FROM `trustcommerce_useragent_blacklist`');
172 while($dao->fetch()) {
173 if(preg_match('/'.$dao->name
.'/', $agent) === 1) {
174 error_log(' [client '.$ip.'] [agent '.$agent.'] - Blacklisted by USER_AGENT rule #'.$dao->id
);
181 function _isIPBlacklisted() {
182 $ip = $_SERVER['REMOTE_ADDR'];
183 $agent = $_SERVER['HTTP_USER_AGENT'];
185 $blacklist = array();
186 $dao = CRM_Core_DAO
::executeQuery('SELECT * FROM `trustcommerce_blacklist`');
187 while($dao->fetch()) {
188 if($ip >= $dao->start
&& $ip <= $dao->end
) {
189 error_log('[client '.long2ip($ip).'] [agent '.$agent.'] Blacklisted by IP rule #'.$dao->id
);
196 function _sendTCRequest($request) {
197 $this->_logger($request);
198 return tclink_send($request);
201 function _logger($params) {
203 foreach ($params as $key => $data) {
204 /* Delete any data we should not be writing to disk. This includes:
205 * custid, password, cc, exp, and cvv
215 $msg .= ' '.$key.' => '.$data;
218 error_log('[client '.$_SERVER['REMOTE_ADDR'].'] TrustCommerce:'.$msg);
222 * Gets the recurring billing fields for the TC API
223 * @param array $fields The fields to modify.
224 * @return array The fields for tclink_send(), modified for recurring billing.
227 function _getRecurPaymentFields($fields) {
228 $payments = $this->_getParam('frequency_interval');
229 $cycle = $this->_getParam('frequency_unit');
231 /* Translate billing cycle from CiviCRM -> TC */
247 /* Translate frequency interval from CiviCRM -> TC
248 * Payments are the same, HOWEVER a payment of 1 (forever) should be 0 in TC */
253 $fields['cycle'] = '1'.$cycle; /* The billing cycle in years, months, weeks, or days. */
254 $fields['payments'] = $payments;
255 $fields['authnow'] = 'y';
256 $fields['action'] = 'store'; /* Change our mode to `store' mode. */
261 /* Parses a response from TC via the tclink_send() command.
262 * @param $reply array The result of a call to tclink_send().
263 * @return mixed self::error() if transaction failed, otherwise returns 0.
265 function _getTCReply($reply) {
267 /* DUPLIATE CODE, please refactor. ~lisa */
269 return self
::error(9002, 'Could not initiate connection to payment gateway');
272 $this->_logger($reply);
274 switch($reply['status']) {
275 case self
::AUTH_BLACKLIST
:
276 return self
::error(9001, "Your transaction was declined: error #90210");
278 case self
::AUTH_APPROVED
:
281 case self
::AUTH_DECLINED
:
282 // TODO FIXME be more or less specific?
283 // declinetype can be: decline, avs, cvv, call, expiredcard, carderror, authexpired, fraud, blacklist, velocity
284 // See TC documentation for more info
285 switch($reply['declinetype']) {
287 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.");
290 return self
::error(9009, "Your transaction was declined: {$reply['declinetype']}");
292 case self
::AUTH_BADDATA
:
293 // TODO FIXME do something with $reply['error'] and $reply['offender']
294 return self
::error(9011, "Invalid credit card information. The following fields were invalid: {$reply['offenders']}.");
296 case self
::AUTH_ERROR
:
297 return self
::error(9002, 'Could not initiate connection to payment gateway');
303 function _getTrustCommerceFields() {
304 // Total amount is from the form contribution field
305 $amount = $this->_getParam('total_amount');
306 // CRM-9894 would this ever be the case??
307 if (empty($amount)) {
308 $amount = $this->_getParam('amount');
311 $fields['custid'] = $this->_getParam('user_name');
312 $fields['password'] = $this->_getParam('password');
313 $fields['action'] = 'sale';
315 // Enable address verification
316 $fields['avs'] = 'y';
318 $fields['address1'] = $this->_getParam('street_address');
319 $fields['zip'] = $this->_getParam('postal_code');
321 $fields['name'] = $this->_getParam('billing_first_name') . ' ' . $this->_getParam('billing_last_name');
323 // This assumes currencies where the . is used as the decimal point, like USD
324 $amount = preg_replace("/([^0-9\\.])/i", "", $amount);
326 // We need to pass the amount to TrustCommerce in dollar cents
327 $fields['amount'] = $amount * 100;
330 $fields['ticket'] = substr($this->_getParam('invoiceID'), 0, 20);
333 $fields['cc'] = $this->_getParam('credit_card_number');
334 $fields['cvv'] = $this->_getParam('cvv2');
335 $exp_month = str_pad($this->_getParam('month'), 2, '0', STR_PAD_LEFT
);
336 $exp_year = substr($this->_getParam('year'),-2);
337 $fields['exp'] = "$exp_month$exp_year";
339 if ($this->_mode
!= 'live') {
340 $fields['demo'] = 'y';
346 * Checks to see if invoice_id already exists in db
348 * @param int $invoiceId The ID to check
350 * @return bool True if ID exists, else false
352 function _checkDupe($invoiceId) {
353 require_once 'CRM/Contribute/DAO/Contribution.php';
354 $contribution = new CRM_Contribute_DAO_Contribution();
355 $contribution->invoice_id
= $invoiceId;
356 return $contribution->find();
360 * Get the value of a field if set
362 * @param string $field the field
364 * @return mixed value of the field, or empty string if the field is
367 function _getParam($field) {
368 return CRM_Utils_Array
::value($field, $this->_params
, '');
371 function &error($errorCode = NULL, $errorMessage = NULL) {
372 $e = CRM_Core_Error
::singleton();
374 $e->push($errorCode, 0, NULL, $errorMessage);
377 $e->push(9001, 0, NULL, 'Unknown System Error.');
383 * Set a field to the specified value. Value must be a scalar (int,
384 * float, string, or boolean)
386 * @param string $field
387 * @param mixed $value
389 * @return bool false if value is not a scalar, true if successful
391 function _setParam($field, $value) {
392 if (!is_scalar($value)) {
396 $this->_params
[$field] = $value;
401 * This function checks to see if we have the right config values
403 * @return string the error message if any
406 function checkConfig() {
408 if (empty($this->_paymentProcessor
['user_name'])) {
409 $error[] = ts('Customer ID is not set for this payment processor');
412 if (empty($this->_paymentProcessor
['password'])) {
413 $error[] = ts('Password is not set for this payment processor');
416 if (!empty($error)) {
417 return implode('<p>', $error);
423 function cancelSubscription(&$message = '', $params = array()) {
424 $tc_params['custid'] = $this->_getParam('user_name');
425 $tc_params['password'] = $this->_getParam('password');
426 $tc_params['action'] = 'unstore';
427 $tc_params['billingid'] = CRM_Utils_Array
::value('trxn_id', $params);
429 $result = $this->_sendTCRequest($tc_params);
431 /* Test if call failed */
433 return self
::error(9002, 'Could not initiate connection to payment gateway');
435 /* We are done, pass success */
439 public function install() {
443 public function uninstall() {