Removed extra payment gateway check.
[trustcommerce.git] / trustcommerce.php
CommitLineData
71a6ba5c
LMM
1<?php
2/*
93b42747
LMM
3 * This file is part of CiviCRM.
4 *
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.
9 *
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.
14 *
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/>.
17 *
71a6ba5c
LMM
18 * Copyright (C) 2012
19 * Licensed to CiviCRM under the GPL v3 or higher
20 *
21 * Written and contributed by Ward Vandewege <ward@fsf.org> (http://www.fsf.org)
68f3cf09 22 * Modified by Lisa Marie Maginnis <lisa@fsf.org> (http://www.fsf.org)
4efc3ebe 23 * Copyright © 2015 David Thompson <davet@gnu.org>
71a6ba5c
LMM
24 *
25 */
26
27// Define logging level (0 = off, 4 = log everything)
28define('TRUSTCOMMERCE_LOGGING_LEVEL', 4);
29
30require_once 'CRM/Core/Payment.php';
31class org_fsf_payment_trustcommerce extends CRM_Core_Payment {
32 CONST CHARSET = 'iso-8859-1';
33 CONST AUTH_APPROVED = 'approve';
34 CONST AUTH_DECLINED = 'decline';
35 CONST AUTH_BADDATA = 'baddata';
36 CONST AUTH_ERROR = 'error';
4d58ae2f 37 CONST AUTH_BLACKLIST = 'blacklisted';
71a6ba5c
LMM
38
39 static protected $_mode = NULL;
40
41 static protected $_params = array();
42
43 /**
44 * We only need one instance of this object. So we use the singleton
45 * pattern and cache the instance in this variable
46 *
47 * @var object
48 * @static
49 */
50 static private $_singleton = NULL;
51
52 /**
53 * Constructor
54 *
55 * @param string $mode the mode of operation: live or test
56 *
57 * @return void
58 */ function __construct($mode, &$paymentProcessor) {
59 $this->_mode = $mode;
60
61 $this->_paymentProcessor = $paymentProcessor;
62
63 $this->_processorName = ts('TrustCommerce');
64
65 $config = CRM_Core_Config::singleton();
66 $this->_setParam('user_name', $paymentProcessor['user_name']);
67 $this->_setParam('password', $paymentProcessor['password']);
68
69 $this->_setParam('timestamp', time());
70 srand(time());
71 $this->_setParam('sequence', rand(1, 1000));
72 $this->logging_level = TRUSTCOMMERCE_LOGGING_LEVEL;
4d58ae2f 73
71a6ba5c
LMM
74 }
75
76 /**
77 * singleton function used to manage this object
78 *
79 * @param string $mode the mode of operation: live or test
80 *
81 * @return object
82 * @static
83 *
84 */
85 static
86 function &singleton($mode, &$paymentProcessor) {
87 $processorName = $paymentProcessor['name'];
88 if (self::$_singleton[$processorName] === NULL) {
89 self::$_singleton[$processorName] = new org_fsf_payment_trustcommerce($mode, $paymentProcessor);
90 }
91 return self::$_singleton[$processorName];
92 }
93
94 /**
e0273c0a
LMM
95 * Submit a payment using the TC API
96 * @param array $params The params we will be sending to tclink_send()
97 * @return mixed An array of our results, or an error object if the transaction fails.
71a6ba5c
LMM
98 * @public
99 */
100 function doDirectPayment(&$params) {
101 if (!extension_loaded("tclink")) {
102 return self::error(9001, 'TrustCommerce requires that the tclink module is loaded');
103 }
104
f322addf
LMM
105 /* Copy our paramaters to ourself */
106 foreach ($params as $field => $value) {
71a6ba5c
LMM
107 $this->_setParam($field, $value);
108 }
109
f322addf
LMM
110 /* Get our fields to pass to tclink_send() */
111 $tc_params = $this->_getTrustCommerceFields();
71a6ba5c 112
f322addf 113 /* Are we recurring? If so add the extra API fields. */
7d2018fa 114 if (CRM_Utils_Array::value('is_recur', $params) == 1) {
f322addf 115 $tc_params = $this->_getRecurPaymentFields($tc_params);
7d2018fa 116 $recur=1;
f322addf 117 }
71a6ba5c 118
f322addf 119 /* Pass our cooked params to the alter hook, per Core/Payment/Dummy.php */
32bf0975 120 CRM_Utils_Hook::alterPaymentProcessorParams($this, $params, $tc_params);
71a6ba5c
LMM
121
122 // TrustCommerce will not refuse duplicates, so we should check if the user already submitted this transaction
f322addf 123 if ($this->_checkDupe($tc_params['ticket'])) {
71a6ba5c
LMM
124 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 }
126
4d58ae2f
LMM
127 /* This implements a local blacklist, and passes us though as a normal failure
128 * if the luser is on the blacklist. */
129 if(!$this->_isBlacklisted()) {
130 /* Call the TC API, and grab the reply */
131 $reply = $this->_sendTCRequest($tc_params);
132 } else {
133 $this->_logger($tc_params);
134 $reply['status'] = self::AUTH_BLACKLIST;
135 }
71a6ba5c 136
f322addf 137 /* Parse our reply */
5efae07f 138 $result = $this->_getTCReply($reply);
71a6ba5c 139
f322addf
LMM
140 if($result == 0) {
141 /* We were successful, congrats. Lets wrap it up:
142 * Convert back to dollars
143 * Save the transaction ID
144 */
06f2e425 145
7d2018fa
DT
146 if (array_key_exists('billingid', $reply)) {
147 $params['recurr_profile_id'] = $reply['billingid'];
148 CRM_Core_DAO::setFieldValue(
149 'CRM_Contribute_DAO_ContributionRecur',
150 $this->_getParam('contributionRecurID'),
151 'processor_id', $reply['billingid']
152 );
153 }
f322addf 154 $params['trxn_id'] = $reply['transid'];
06f2e425 155
f322addf 156 $params['gross_amount'] = $tc_params['amount'] / 100;
71a6ba5c 157
f322addf 158 return $params;
71a6ba5c 159
f322addf
LMM
160 } else {
161 /* Otherwise we return the error object */
162 return $result;
163 }
71a6ba5c
LMM
164 }
165
4efc3ebe
DT
166 /**
167 * Update CC info for a recurring contribution
168 */
169 function updateSubscriptionBillingInfo(&$message = '', $params = array()) {
170 $expYear = $params['credit_card_exp_date']['Y'];
171 $expMonth = $params['credit_card_exp_date']['M'];
172
173 $tc_params = array(
174 'custid' => $this->_paymentProcessor['user_name'],
175 'password' => $this->_paymentProcessor['password'],
176 'action' => 'store',
177 'billingid' => $params['subscriptionId'],
178 'avs' => 'y', // Enable address verification
179 'address1' => $params['street_address'],
180 'zip' => $params['postal_code'],
181 'name' => $this->_formatBillingName($params['first_name'],
182 $params['last_name']),
183 'cc' => $params['credit_card_number'],
184 'cvv' => $params['cvv2'],
185 'exp' => $this->_formatExpirationDate($expYear, $expMonth),
186 'amount' => $this->_formatAmount($params['amount']),
187 );
188
189 CRM_Utils_Hook::alterPaymentProcessorParams($this, $params, $tc_params);
190
191 $reply = $this->_sendTCRequest($tc_params);
192 $result = $this->_getTCReply($reply);
193
194 if($result === 0) {
195 $message = 'Successfully updated TC billing id ' . $tc_params['billingid'];
196
197 return TRUE;
198 } else {
199 return FALSE;
200 }
201 }
202
203 // TODO: Use the formatting functions throughout the entire class to
204 // dedupe the conversions done elsewhere in a less reusable way.
205 function _formatAmount($amount) {
206 return $amount * 100;
207 }
208
209 function _formatBillingName($firstName, $lastName) {
210 return "$firstName $lastName";
211 }
212
213 function _formatExpirationDate($year, $month) {
214 $exp_month = str_pad($month, 2, '0', STR_PAD_LEFT);
215 $exp_year = substr($year, -2);
216
217 return "$exp_month$exp_year";
218 }
219
4d58ae2f 220 function _isBlacklisted() {
d5e500b0
LMM
221 if($this->_isIPBlacklisted()) {
222 return TRUE;
223 } else if($this->_IsAgentBlacklisted()) {
224 return TRUE;
0b6767d8 225 }
d5e500b0 226 return FALSE;
4d58ae2f
LMM
227 }
228
229 function _isAgentBlacklisted() {
230 $ip = $_SERVER['REMOTE_ADDR'];
231 $agent = $_SERVER['HTTP_USER_AGENT'];
232 $dao = CRM_Core_DAO::executeQuery('SELECT * FROM `trustcommerce_useragent_blacklist`');
233 while($dao->fetch()) {
234 if(preg_match('/'.$dao->name.'/', $agent) === 1) {
d5e500b0
LMM
235 error_log(' [client '.$ip.'] [agent '.$agent.'] - Blacklisted by USER_AGENT rule #'.$dao->id);
236 return TRUE;
4d58ae2f
LMM
237 }
238 }
239 return FALSE;
240 }
241
242 function _isIPBlacklisted() {
243 $ip = $_SERVER['REMOTE_ADDR'];
c389ccec 244 $agent = $_SERVER['HTTP_USER_AGENT'];
4d58ae2f
LMM
245 $ip = ip2long($ip);
246 $blacklist = array();
247 $dao = CRM_Core_DAO::executeQuery('SELECT * FROM `trustcommerce_blacklist`');
248 while($dao->fetch()) {
249 if($ip >= $dao->start && $ip <= $dao->end) {
d5e500b0
LMM
250 error_log('[client '.long2ip($ip).'] [agent '.$agent.'] Blacklisted by IP rule #'.$dao->id);
251 return TRUE;
4d58ae2f
LMM
252 }
253 }
254 return FALSE;
255 }
256
e055e8ef
LMM
257 function _sendTCRequest($request) {
258 $this->_logger($request);
259 return tclink_send($request);
260 }
261
262 function _logger($params) {
e990a9a5 263 $msg = '';
69a1e975 264 foreach ($params as $key => $data) {
e055e8ef
LMM
265 /* Delete any data we should not be writing to disk. This includes:
266 * custid, password, cc, exp, and cvv
267 */
e055e8ef 268 switch($key) {
e990a9a5
LMM
269 case 'custid':
270 case 'password':
271 case 'cc':
272 case 'exp':
273 case 'cvv':
e055e8ef
LMM
274 break;
275 default:
e990a9a5 276 $msg .= ' '.$key.' => '.$data;
e055e8ef
LMM
277 }
278 }
4d58ae2f 279 error_log('[client '.$_SERVER['REMOTE_ADDR'].'] TrustCommerce:'.$msg);
e055e8ef
LMM
280 }
281
71a6ba5c 282 /**
f322addf
LMM
283 * Gets the recurring billing fields for the TC API
284 * @param array $fields The fields to modify.
285 * @return array The fields for tclink_send(), modified for recurring billing.
71a6ba5c
LMM
286 * @public
287 */
f322addf 288 function _getRecurPaymentFields($fields) {
285eaf25
LMM
289 $payments = $this->_getParam('frequency_interval');
290 $cycle = $this->_getParam('frequency_unit');
71a6ba5c 291
f322addf 292 /* Translate billing cycle from CiviCRM -> TC */
285eaf25
LMM
293 switch($cycle) {
294 case 'day':
295 $cycle = 'd';
296 break;
297 case 'week':
298 $cycle = 'w';
299 break;
300 case 'month':
301 $cycle = 'm';
302 break;
303 case 'year':
304 $cycle = 'y';
305 break;
71a6ba5c 306 }
0b6767d8 307
bc323ec4
LMM
308 /* Translate frequency interval from CiviCRM -> TC
309 * Payments are the same, HOWEVER a payment of 1 (forever) should be 0 in TC */
310 if($payments == 1) {
311 $payments = 0;
71a6ba5c 312 }
71a6ba5c 313
bc323ec4
LMM
314 $fields['cycle'] = '1'.$cycle; /* The billing cycle in years, months, weeks, or days. */
315 $fields['payments'] = $payments;
316 $fields['action'] = 'store'; /* Change our mode to `store' mode. */
71a6ba5c 317
bc323ec4 318 return $fields;
a79ba043
LMM
319 }
320
321 /* Parses a response from TC via the tclink_send() command.
322 * @param $reply array The result of a call to tclink_send().
323 * @return mixed self::error() if transaction failed, otherwise returns 0.
324 */
5efae07f 325 function _getTCReply($reply) {
71a6ba5c 326
285eaf25 327 /* DUPLIATE CODE, please refactor. ~lisa */
bc323ec4 328 if (!$reply) {
285eaf25 329 return self::error(9002, 'Could not initiate connection to payment gateway');
71a6ba5c
LMM
330 }
331
4d58ae2f
LMM
332 $this->_logger($reply);
333
bc323ec4 334 switch($reply['status']) {
4d58ae2f
LMM
335 case self::AUTH_BLACKLIST:
336 return self::error(9001, "Your transaction was declined: error #90210");
337 break;
285eaf25
LMM
338 case self::AUTH_APPROVED:
339 // It's all good
340 break;
341 case self::AUTH_DECLINED:
0b6767d8 342 // TODO FIXME be more or less specific?
285eaf25
LMM
343 // declinetype can be: decline, avs, cvv, call, expiredcard, carderror, authexpired, fraud, blacklist, velocity
344 // See TC documentation for more info
da1932b6
LMM
345 switch($reply['declinetype']) {
346 case 'avs':
78390e15 347 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.");
da1932b6
LMM
348 break;
349 }
a8c5366f 350 return self::error(9009, "Your transaction was declined: {$reply['declinetype']}");
285eaf25
LMM
351 break;
352 case self::AUTH_BADDATA:
a8c5366f
LMM
353 // TODO FIXME do something with $reply['error'] and $reply['offender']
354 return self::error(9011, "Invalid credit card information. The following fields were invalid: {$reply['offenders']}.");
285eaf25
LMM
355 break;
356 case self::AUTH_ERROR:
357 return self::error(9002, 'Could not initiate connection to payment gateway');
358 break;
71a6ba5c 359 }
a79ba043 360 return 0;
71a6ba5c
LMM
361 }
362
363 function _getTrustCommerceFields() {
364 // Total amount is from the form contribution field
365 $amount = $this->_getParam('total_amount');
366 // CRM-9894 would this ever be the case??
367 if (empty($amount)) {
368 $amount = $this->_getParam('amount');
369 }
370 $fields = array();
371 $fields['custid'] = $this->_getParam('user_name');
372 $fields['password'] = $this->_getParam('password');
373 $fields['action'] = 'sale';
374
375 // Enable address verification
376 $fields['avs'] = 'y';
377
378 $fields['address1'] = $this->_getParam('street_address');
379 $fields['zip'] = $this->_getParam('postal_code');
380
381 $fields['name'] = $this->_getParam('billing_first_name') . ' ' . $this->_getParam('billing_last_name');
382
383 // This assumes currencies where the . is used as the decimal point, like USD
384 $amount = preg_replace("/([^0-9\\.])/i", "", $amount);
385
386 // We need to pass the amount to TrustCommerce in dollar cents
387 $fields['amount'] = $amount * 100;
388
389 // Unique identifier
390 $fields['ticket'] = substr($this->_getParam('invoiceID'), 0, 20);
391
392 // cc info
393 $fields['cc'] = $this->_getParam('credit_card_number');
394 $fields['cvv'] = $this->_getParam('cvv2');
395 $exp_month = str_pad($this->_getParam('month'), 2, '0', STR_PAD_LEFT);
396 $exp_year = substr($this->_getParam('year'),-2);
397 $fields['exp'] = "$exp_month$exp_year";
398
399 if ($this->_mode != 'live') {
400 $fields['demo'] = 'y';
401 }
71a6ba5c
LMM
402 return $fields;
403 }
404
405 /**
406 * Checks to see if invoice_id already exists in db
407 *
408 * @param int $invoiceId The ID to check
409 *
410 * @return bool True if ID exists, else false
411 */
412 function _checkDupe($invoiceId) {
413 require_once 'CRM/Contribute/DAO/Contribution.php';
414 $contribution = new CRM_Contribute_DAO_Contribution();
415 $contribution->invoice_id = $invoiceId;
416 return $contribution->find();
417 }
418
419 /**
420 * Get the value of a field if set
421 *
422 * @param string $field the field
423 *
424 * @return mixed value of the field, or empty string if the field is
425 * not set
426 */
427 function _getParam($field) {
428 return CRM_Utils_Array::value($field, $this->_params, '');
429 }
430
431 function &error($errorCode = NULL, $errorMessage = NULL) {
432 $e = CRM_Core_Error::singleton();
433 if ($errorCode) {
434 $e->push($errorCode, 0, NULL, $errorMessage);
435 }
436 else {
437 $e->push(9001, 0, NULL, 'Unknown System Error.');
438 }
439 return $e;
440 }
441
442 /**
443 * Set a field to the specified value. Value must be a scalar (int,
444 * float, string, or boolean)
445 *
446 * @param string $field
447 * @param mixed $value
448 *
449 * @return bool false if value is not a scalar, true if successful
450 */
451 function _setParam($field, $value) {
452 if (!is_scalar($value)) {
453 return FALSE;
454 }
455 else {
456 $this->_params[$field] = $value;
457 }
458 }
459
460 /**
461 * This function checks to see if we have the right config values
462 *
463 * @return string the error message if any
464 * @public
465 */
466 function checkConfig() {
467 $error = array();
468 if (empty($this->_paymentProcessor['user_name'])) {
469 $error[] = ts('Customer ID is not set for this payment processor');
470 }
471
472 if (empty($this->_paymentProcessor['password'])) {
473 $error[] = ts('Password is not set for this payment processor');
474 }
475
476 if (!empty($error)) {
477 return implode('<p>', $error);
478 } else {
479 return NULL;
480 }
481 }
482
14f15ff3 483 function cancelSubscription(&$message = '', $params = array()) {
7964e0e9
LMM
484 $tc_params['custid'] = $this->_getParam('user_name');
485 $tc_params['password'] = $this->_getParam('password');
486 $tc_params['action'] = 'unstore';
ee0485c3 487 $tc_params['billingid'] = CRM_Utils_Array::value('subscriptionId', $params);
0b6767d8 488
e990a9a5 489 $result = $this->_sendTCRequest($tc_params);
71a6ba5c 490
7964e0e9
LMM
491 /* Test if call failed */
492 if(!$result) {
71a6ba5c
LMM
493 return self::error(9002, 'Could not initiate connection to payment gateway');
494 }
7964e0e9 495 /* We are done, pass success */
71a6ba5c
LMM
496 return TRUE;
497 }
2ff31643
DT
498
499 function changeSubscriptionAmount(&$message = '', $params = array()) {
1d268593
DT
500 $tc_params['custid'] = $this->_paymentProcessor['user_name'];
501 $tc_params['password'] = $this->_paymentProcessor['password'];
2ff31643
DT
502 $tc_params['action'] = 'store';
503
504 $tc_params['billingid'] = CRM_Utils_Array::value('subscriptionId', $params);
505 $tc_params['payments'] = CRM_Utils_Array::value('installments', $params);
506 $tc_params['amount'] = CRM_Utils_Array::value('amount', $params) * 100;
507
508 if($tc_params['payments'] == 1) {
509 $tc_params['payments'] = 0;
510 }
511 $reply = $this->_sendTCRequest($tc_params);
512 $result = $this->_getTCReply($reply);
513
2ff31643
DT
514 /* We are done, pass success */
515 return TRUE;
516
517 }
518
71a6ba5c
LMM
519 public function install() {
520 return TRUE;
521 }
522
523 public function uninstall() {
524 return TRUE;
525 }
526
527}