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