e7ab62139f1ef960be2a1d01a9c061af8c8a132e
[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 * @param CRM_Core_Payment The payment processor object.
121 *
122 * @return void
123 */
124 function __construct($mode, &$paymentProcessor) {
125 $this->_mode = $mode;
126
127 $this->_paymentProcessor = $paymentProcessor;
128
129 $this->_processorName = ts('TrustCommerce');
130
131 $config = CRM_Core_Config::singleton();
132 $this->_setParam('user_name', $paymentProcessor['user_name']);
133 $this->_setParam('password', $paymentProcessor['password']);
134
135 $this->_setParam('timestamp', time());
136 srand(time());
137 $this->_setParam('sequence', rand(1, 1000));
138 $this->logging_level = TRUSTCOMMERCE_LOGGING_LEVEL;
139
140 }
141
142 /**
143 * The singleton function used to manage this object
144 *
145 * @param string $mode the mode of operation: live or test
146 * @param CRM_Core_Payment The payment processor object.
147 *
148 * @return object
149 * @static
150 */
151 static function &singleton($mode, &$paymentProcessor) {
152 $processorName = $paymentProcessor['name'];
153 if (self::$_singleton[$processorName] === NULL) {
154 self::$_singleton[$processorName] = new org_fsf_payment_trustcommerce($mode, $paymentProcessor);
155 }
156 return self::$_singleton[$processorName];
157 }
158
159 /**
160 * Submit a payment using the TC API
161 *
162 * @param array $params The params we will be sending to tclink_send()
163 * @return mixed An array of our results, or an error object if the transaction fails.
164 * @public
165 */
166 function doDirectPayment(&$params) {
167 if (!extension_loaded("tclink")) {
168 return self::error(9001, 'TrustCommerce requires that the tclink module is loaded');
169 }
170
171 /* Copy our paramaters to ourself */
172 foreach ($params as $field => $value) {
173 $this->_setParam($field, $value);
174 }
175
176 /* Get our fields to pass to tclink_send() */
177 $tc_params = $this->_getTrustCommerceFields();
178
179 /* Are we recurring? If so add the extra API fields. */
180 if (CRM_Utils_Array::value('is_recur', $params) == 1) {
181 $tc_params = $this->_getRecurPaymentFields($tc_params);
182 $recur=1;
183 }
184
185 /* Pass our cooked params to the alter hook, per Core/Payment/Dummy.php */
186 CRM_Utils_Hook::alterPaymentProcessorParams($this, $params, $tc_params);
187
188 // TrustCommerce will not refuse duplicates, so we should check if the user already submitted this transaction
189 if ($this->_checkDupe($tc_params['ticket'])) {
190 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.');
191 }
192
193 /* This implements a local blacklist, and passes us though as a normal failure
194 * if the luser is on the blacklist. */
195 if(!$this->_isBlacklisted()) {
196 /* Call the TC API, and grab the reply */
197 $reply = $this->_sendTCRequest($tc_params);
198 } else {
199 $this->_logger($tc_params);
200 $reply['status'] = self::AUTH_BLACKLIST;
201 }
202
203 /* Parse our reply */
204 $result = $this->_getTCReply($reply);
205
206 if($result == 0) {
207 /* We were successful, congrats. Lets wrap it up:
208 * Convert back to dollars
209 * Save the transaction ID
210 */
211
212 if (array_key_exists('billingid', $reply)) {
213 $params['recurr_profile_id'] = $reply['billingid'];
214 CRM_Core_DAO::setFieldValue(
215 'CRM_Contribute_DAO_ContributionRecur',
216 $this->_getParam('contributionRecurID'),
217 'processor_id', $reply['billingid']
218 );
219 }
220 $params['trxn_id'] = $reply['transid'];
221
222 $params['gross_amount'] = $tc_params['amount'] / 100;
223
224 return $params;
225
226 } else {
227 /* Otherwise we return the error object */
228 return $result;
229 }
230 }
231
232 /**
233 * Hook to update CC info for a recurring contribution
234 *
235 * @param string $message The message to dispaly on update success/failure
236 * @param array $params The paramters to pass to the payment processor
237 *
238 * @return bool True if successful, false on failure
239 */
240 function updateSubscriptionBillingInfo(&$message = '', $params = array()) {
241 $expYear = $params['credit_card_exp_date']['Y'];
242 $expMonth = $params['credit_card_exp_date']['M'];
243
244 // TODO: This should be our build in params set function, not by hand!
245 $tc_params = array(
246 'custid' => $this->_paymentProcessor['user_name'],
247 'password' => $this->_paymentProcessor['password'],
248 'action' => 'store',
249 'billingid' => $params['subscriptionId'],
250 'avs' => 'y', // Enable address verification
251 'address1' => $params['street_address'],
252 'zip' => $params['postal_code'],
253 'name' => $this->_formatBillingName($params['first_name'],
254 $params['last_name']),
255 'cc' => $params['credit_card_number'],
256 'cvv' => $params['cvv2'],
257 'exp' => $this->_formatExpirationDate($expYear, $expMonth),
258 'amount' => $this->_formatAmount($params['amount']),
259 );
260
261 CRM_Utils_Hook::alterPaymentProcessorParams($this, $params, $tc_params);
262
263 $reply = $this->_sendTCRequest($tc_params);
264 $result = $this->_getTCReply($reply);
265
266 if($result === 0) {
267 // TODO: Respect vaules for $messages passed in from our caller
268 $message = 'Successfully updated TC billing id ' . $tc_params['billingid'];
269
270 return TRUE;
271 } else {
272 return FALSE;
273 }
274 }
275
276 // TODO: Use the formatting functions throughout the entire class to
277 // dedupe the conversions done elsewhere in a less reusable way.
278
279 /**
280 * Internal routine to convert from CiviCRM amounts to TC amounts.
281 *
282 * Multiplies the amount by 100.
283 *
284 * @param float $amount The currency value to convert.
285 *
286 * @return int The TC amount
287 */
288 private function _formatAmount($amount) {
289 return $amount * 100;
290 }
291
292 /**
293 * Internal routine to format the billing name for TC
294 *
295 * @param string $firstName The first name to submit to TC
296 * @param string $lastName The last name to submit to TC
297 *
298 * @return string The TC name format, "$firstName $lastName"
299 */
300 private function _formatBillingName($firstName, $lastName) {
301 return "$firstName $lastName";
302 }
303
304 /**
305 * Formats the expiration date for TC
306 *
307 * @param int $year The credit card expiration year
308 * @param int $month The credit card expiration year
309 *
310 * @return The TC CC expiration date format, "$month$year"
311 */
312 private function _formatExpirationDate($year, $month) {
313 $exp_month = str_pad($month, 2, '0', STR_PAD_LEFT);
314 $exp_year = substr($year, -2);
315
316 return "$exp_month$exp_year";
317 }
318
319 /**
320 * Checks to see if the source IP/USERAGENT are blacklisted.
321 *
322 * @return bool TRUE if on the blacklist, FALSE if not.
323 */
324 private function _isBlacklisted() {
325 if($this->_isIPBlacklisted()) {
326 return TRUE;
327 } else if($this->_IsAgentBlacklisted()) {
328 return TRUE;
329 }
330 return FALSE;
331 }
332
333 /**
334 * Checks to see if the source USERAGENT is blacklisted
335 *
336 * @return bool TRUE if on the blacklist, FALSE if not.
337 */
338 private function _isAgentBlacklisted() {
339 // TODO: fix DB calls to be more the CiviCRM way
340 $ip = $_SERVER['REMOTE_ADDR'];
341 $agent = $_SERVER['HTTP_USER_AGENT'];
342 $dao = CRM_Core_DAO::executeQuery('SELECT * FROM `trustcommerce_useragent_blacklist`');
343 while($dao->fetch()) {
344 if(preg_match('/'.$dao->name.'/', $agent) === 1) {
345 error_log(' [client '.$ip.'] [agent '.$agent.'] - Blacklisted by USER_AGENT rule #'.$dao->id);
346 return TRUE;
347 }
348 }
349 return FALSE;
350 }
351
352 /**
353 * Checks to see if the source IP is blacklisted
354 *
355 * @return bool TRUE if on the blacklist, FALSE if not.
356 */
357 private function _isIPBlacklisted() {
358 // TODO: fix DB calls to be more the CiviCRM way
359 $ip = $_SERVER['REMOTE_ADDR'];
360 $agent = $_SERVER['HTTP_USER_AGENT'];
361 $ip = ip2long($ip);
362 $blacklist = array();
363 $dao = CRM_Core_DAO::executeQuery('SELECT * FROM `trustcommerce_blacklist`');
364 while($dao->fetch()) {
365 if($ip >= $dao->start && $ip <= $dao->end) {
366 error_log('[client '.long2ip($ip).'] [agent '.$agent.'] Blacklisted by IP rule #'.$dao->id);
367 return TRUE;
368 }
369 }
370 return FALSE;
371 }
372
373 /**
374 * Sends the API call to TC for processing
375 *
376 * @param array $request The array of paramaters to pass the TC API
377 *
378 * @return array The response from the TC API
379 */
380 function _sendTCRequest($request) {
381 $this->_logger($request);
382 return tclink_send($request);
383 }
384
385 /**
386 * Logs paramaters from TC along with the remote address of the client
387 *
388 * Will log paramaters via the error_log() routine. For security reasons
389 * the following values are not logged (skipped): custid, password, cc
390 * exp, and cvv.
391 *
392 * @param array $params The paramaters to log
393 */
394 function _logger($params) {
395 $msg = '';
396 foreach ($params as $key => $data) {
397 /* Delete any data we should not be writing to disk. This includes:
398 * custid, password, cc, exp, and cvv
399 */
400 switch($key) {
401 case 'custid':
402 case 'password':
403 case 'cc':
404 case 'exp':
405 case 'cvv':
406 break;
407 default:
408 $msg .= ' '.$key.' => '.$data;
409 }
410 }
411 error_log('[client '.$_SERVER['REMOTE_ADDR'].'] TrustCommerce:'.$msg);
412 }
413
414 /**
415 * Gets the recurring billing fields for the TC API
416 *
417 * @param array $fields The fields to modify.
418 * @return array The fields for tclink_send(), modified for recurring billing.
419 * @public
420 */
421 function _getRecurPaymentFields($fields) {
422 $payments = $this->_getParam('frequency_interval');
423 $cycle = $this->_getParam('frequency_unit');
424
425 /* Translate billing cycle from CiviCRM -> TC */
426 switch($cycle) {
427 case 'day':
428 $cycle = 'd';
429 break;
430 case 'week':
431 $cycle = 'w';
432 break;
433 case 'month':
434 $cycle = 'm';
435 break;
436 case 'year':
437 $cycle = 'y';
438 break;
439 }
440
441 /* Translate frequency interval from CiviCRM -> TC
442 * Payments are the same, HOWEVER a payment of 1 (forever) should be 0 in TC */
443 if($payments == 1) {
444 $payments = 0;
445 }
446
447 $fields['cycle'] = '1'.$cycle; /* The billing cycle in years, months, weeks, or days. */
448 $fields['payments'] = $payments;
449 $fields['action'] = 'store'; /* Change our mode to `store' mode. */
450
451 return $fields;
452 }
453
454 /** Parses a response from TC via the tclink_send() command.
455 *
456 * @param array $reply The result of a call to tclink_send().
457 *
458 * @return mixed|CRM_Core_Error CRM_Core_Error object if transaction failed, otherwise
459 * returns 0.
460 */
461 function _getTCReply($reply) {
462
463 /* DUPLIATE CODE, please refactor. ~lisa */
464 if (!$reply) {
465 return self::error(9002, 'Could not initiate connection to payment gateway.');
466 }
467
468 $this->_logger($reply);
469
470 switch($reply['status']) {
471 case self::AUTH_BLACKLIST:
472 return self::error(9001, "Your transaction was declined: error #90210");
473 break;
474 case self::AUTH_APPROVED:
475 break;
476 case self::AUTH_ACCEPTED:
477 // It's all good
478 break;
479 case self::AUTH_DECLINED:
480 // TODO FIXME be more or less specific?
481 // declinetype can be: decline, avs, cvv, call, expiredcard, carderror, authexpired, fraud, blacklist, velocity
482 // See TC documentation for more info
483 switch($reply['declinetype']) {
484 case 'avs':
485 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.");
486 break;
487 }
488 return self::error(9009, "Your transaction was declined: {$reply['declinetype']}");
489 break;
490 case self::AUTH_BADDATA:
491 // TODO FIXME do something with $reply['error'] and $reply['offender']
492 return self::error(9011, "Invalid credit card information. The following fields were invalid: {$reply['offenders']}.");
493 break;
494 case self::AUTH_ERROR:
495 return self::error(9002, 'Could not initiate connection to payment gateway');
496 break;
497 }
498 return 0;
499 }
500
501 /**
502 * Generate the basic paramaters to send the TC API
503 *
504 * @return array The array of paramaters to pass _sendTCRequest()
505 */
506 function _getTrustCommerceFields() {
507 // Total amount is from the form contribution field
508 $amount = $this->_getParam('total_amount');
509 // CRM-9894 would this ever be the case??
510 if (empty($amount)) {
511 $amount = $this->_getParam('amount');
512 }
513 $fields = array();
514 $fields['custid'] = $this->_getParam('user_name');
515 $fields['password'] = $this->_getParam('password');
516 $fields['action'] = 'sale';
517
518 // Enable address verification
519 $fields['avs'] = 'y';
520
521 $fields['address1'] = $this->_getParam('street_address');
522 $fields['zip'] = $this->_getParam('postal_code');
523
524 $fields['name'] = $this->_getParam('billing_first_name') . ' ' . $this->_getParam('billing_last_name');
525
526 // This assumes currencies where the . is used as the decimal point, like USD
527 $amount = preg_replace("/([^0-9\\.])/i", "", $amount);
528
529 // We need to pass the amount to TrustCommerce in dollar cents
530 $fields['amount'] = $amount * 100;
531
532 // Unique identifier
533 $fields['ticket'] = substr($this->_getParam('invoiceID'), 0, 20);
534
535 // cc info
536 $fields['cc'] = $this->_getParam('credit_card_number');
537 $fields['cvv'] = $this->_getParam('cvv2');
538 $exp_month = str_pad($this->_getParam('month'), 2, '0', STR_PAD_LEFT);
539 $exp_year = substr($this->_getParam('year'),-2);
540 $fields['exp'] = "$exp_month$exp_year";
541
542 if ($this->_mode != 'live') {
543 $fields['demo'] = 'y';
544 }
545 return $fields;
546 }
547
548 /**
549 * Checks to see if invoice_id already exists in db
550 *
551 * @param int $invoiceId The ID to check
552 *
553 * @return bool True if ID exists, else false
554 */
555 function _checkDupe($invoiceId) {
556 require_once 'CRM/Contribute/DAO/Contribution.php';
557 $contribution = new CRM_Contribute_DAO_Contribution();
558 $contribution->invoice_id = $invoiceId;
559 return $contribution->find();
560 }
561
562 /**
563 * Get the value of a field if set
564 *
565 * @param string $field the field
566 *
567 * @return mixed value of the field, or empty string if the field is
568 * not set
569 */
570 function _getParam($field) {
571 return CRM_Utils_Array::value($field, $this->_params, '');
572 }
573
574 /**
575 * Sets our error message/logging information for CiviCRM
576 *
577 * @param int $errorCode The numerical code of the error, defaults to 9001
578 * @param string $errorMessage The error message to display/log
579 *
580 * @return CRM_Core_Error The error object with message and code.
581 */
582 function &error($errorCode = NULL, $errorMessage = NULL) {
583 $e = CRM_Core_Error::singleton();
584 if ($errorCode) {
585 $e->push($errorCode, 0, NULL, $errorMessage);
586 }
587 else {
588 $e->push(9001, 0, NULL, 'Unknown System Error.');
589 }
590 return $e;
591 }
592
593 /**
594 * Set a field to the specified value. Value must be a scalar (int,
595 * float, string, or boolean)
596 *
597 * @param string $field
598 * @param mixed $value
599 *
600 * @return bool false if value is not a scalar, true if successful
601 */
602 function _setParam($field, $value) {
603 if (!is_scalar($value)) {
604 return FALSE;
605 }
606 else {
607 $this->_params[$field] = $value;
608 }
609 }
610
611 /**
612 * Checks to see if we have the manditory config values set.
613 *
614 * @return string the error message if any
615 * @public
616 */
617 function checkConfig() {
618 $error = array();
619 if (empty($this->_paymentProcessor['user_name'])) {
620 $error[] = ts('Customer ID is not set for this payment processor');
621 }
622
623 if (empty($this->_paymentProcessor['password'])) {
624 $error[] = ts('Password is not set for this payment processor');
625 }
626
627 if (!empty($error)) {
628 return implode('<p>', $error);
629 } else {
630 return NULL;
631 }
632 }
633
634 /**
635 * Hook to cancel a recurring contribution
636 *
637 * @param string $message The message to dispaly on update success/failure
638 * @param array $params The paramters to pass to the payment processor
639 *
640 * @return bool True if successful, false on failure
641 */
642 function cancelSubscription(&$message = '', $params = array()) {
643 $tc_params['custid'] = $this->_getParam('user_name');
644 $tc_params['password'] = $this->_getParam('password');
645 $tc_params['action'] = 'unstore';
646 $tc_params['billingid'] = CRM_Utils_Array::value('subscriptionId', $params);
647
648 $result = $this->_sendTCRequest($tc_params);
649
650 /* Test if call failed */
651 if(!$result) {
652 return self::error(9002, 'Could not initiate connection to payment gateway');
653 }
654 /* We are done, pass success */
655 return TRUE;
656 }
657
658 /**
659 * Hook to update amount billed for a recurring contribution
660 *
661 * @param string $message The message to dispaly on update success/failure
662 * @param array $params The paramters to pass to the payment processor
663 *
664 * @return bool True if successful, false on failure
665 */
666 function changeSubscriptionAmount(&$message = '', $params = array()) {
667 $tc_params['custid'] = $this->_paymentProcessor['user_name'];
668 $tc_params['password'] = $this->_paymentProcessor['password'];
669 $tc_params['action'] = 'store';
670
671 $tc_params['billingid'] = CRM_Utils_Array::value('subscriptionId', $params);
672 $tc_params['payments'] = CRM_Utils_Array::value('installments', $params);
673 $tc_params['amount'] = CRM_Utils_Array::value('amount', $params) * 100;
674
675 if($tc_params['payments'] == 1) {
676 $tc_params['payments'] = 0;
677 }
678 $reply = $this->_sendTCRequest($tc_params);
679 $result = $this->_getTCReply($reply);
680
681 /* We are done, pass success */
682 return TRUE;
683
684 }
685
686 /**
687 * Installs the trustcommerce module (currently a dummy)
688 */
689 public function install() {
690 return TRUE;
691 }
692
693 /**
694 * Uninstalls the trustcommerce module (currently a dummy)
695 */
696 public function uninstall() {
697 return TRUE;
698 }
699
700 }