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)
23 * Copyright © 2015 David Thompson <davet@gnu.org>
28 * CiviCRM payment processor module for TrustCommerece.
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
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,
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>
43 * @package org.fsf.payment.trustcommerce
47 * Define logging level (0 = off, 4 = log everything)
49 define('TRUSTCOMMERCE_LOGGING_LEVEL', 4);
52 * Load the CiviCRM core payment class so we can extend it.
54 require_once 'CRM/Core/Payment.php';
57 * The payment processor object, it extends CRM_Core_Payment.
59 //class org_fsf_payment_trustcommerce extends CRM_Core_Payment {
60 class CRM_Core_Payment_TrustCommerce
extends CRM_Core_Payment
{
66 * This is our default charset, currently unused.
68 CONST CHARSET
= 'iso-8859-1';
70 * The API response value for transaction approved.
72 CONST AUTH_APPROVED
= 'approve';
74 * The API response value for transaction declined.
76 CONST AUTH_DECLINED
= 'decline';
78 * The API response value for baddata passed to the TC API.
80 CONST AUTH_BADDATA
= 'baddata';
82 * The API response value for an error in the TC API call.
84 CONST AUTH_ERROR
= 'error';
86 * The API response value for blacklisted in our local blacklist
88 CONST AUTH_BLACKLIST
= 'blacklisted';
90 * The API response value for approved status per the TCDevGuide.
92 CONST AUTH_ACCEPTED
= 'accepted';
95 * The current mode of the payment processor, valid values are: live, demo.
99 protected $_mode = NULL;
101 * The array of params cooked and passed to the TC API via tc_link().
105 protected $_params = array();
108 * We only need one instance of this object. So we use the singleton
109 * pattern and cache the instance in this variable
113 static private $_singleton = NULL;
116 * Sets our basic TC API paramaters (username, password). Also sets up:
117 * logging level, processor name, the mode (live/demo), and creates/copies
120 * @param string $mode the mode of operation: live or test
121 * @param CRM_Core_Payment The payment processor object.
125 function __construct($mode, &$paymentProcessor) {
126 $this->_mode
= $mode;
128 $this->_paymentProcessor
= $paymentProcessor;
130 $this->_processorName
= ts('TrustCommerce');
132 $config = CRM_Core_Config
::singleton();
133 $this->_setParam('user_name', $paymentProcessor['user_name']);
134 $this->_setParam('password', $paymentProcessor['password']);
136 $this->_setParam('timestamp', time());
138 $this->_setParam('sequence', rand(1, 1000));
139 $this->logging_level
= TRUSTCOMMERCE_LOGGING_LEVEL
;
144 * The singleton function used to manage this object
146 * @param string $mode the mode of operation: live or test
147 * @param CRM_Core_Payment The payment processor object.
152 static function &singleton($mode, &$paymentProcessor) {
153 $processorName = $paymentProcessor['name'];
154 if (self
::$_singleton[$processorName] === NULL) {
155 self
::$_singleton[$processorName] = new CRM_Core_Payment_TrustCommerce($mode, $paymentProcessor);
157 return self
::$_singleton[$processorName];
161 * Submit a payment using the TC API
163 * @param array $params The params we will be sending to tclink_send()
164 * @return mixed An array of our results, or an error object if the transaction fails.
167 function doDirectPayment(&$params) {
168 if (!extension_loaded("tclink")) {
169 return self
::error(9001, 'TrustCommerce requires that the tclink module is loaded');
172 /* Copy our paramaters to ourself */
173 foreach ($params as $field => $value) {
174 $this->_setParam($field, $value);
177 /* Get our fields to pass to tclink_send() */
178 $tc_params = $this->_getTrustCommerceFields();
180 /* Are we recurring? If so add the extra API fields. */
181 if (CRM_Utils_Array
::value('is_recur', $params) == 1) {
182 $tc_params = $this->_getRecurPaymentFields($tc_params);
186 /* Pass our cooked params to the alter hook, per Core/Payment/Dummy.php */
187 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $tc_params);
189 // TrustCommerce will not refuse duplicates, so we should check if the user already submitted this transaction
190 if ($this->_checkDupe($tc_params['ticket'])) {
191 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.');
194 /* This implements a local blacklist, and passes us though as a normal failure
195 * if the luser is on the blacklist. */
196 if(!$this->_isBlacklisted($tc_params)) {
197 /* Call the TC API, and grab the reply */
198 $reply = $this->_sendTCRequest($tc_params);
200 $this->_logger($tc_params);
201 $reply['status'] = self
::AUTH_BLACKLIST
;
202 usleep(rand(1000000,10000000));
205 /* Parse our reply */
206 $result = $this->_getTCReply($reply);
208 if(!is_object($result)) {
210 /* We were successful, congrats. Lets wrap it up:
211 * Convert back to dollars
212 * Save the transaction ID
215 if (array_key_exists('billingid', $reply)) {
216 $params['recurr_profile_id'] = $reply['billingid'];
217 CRM_Core_DAO
::setFieldValue(
218 'CRM_Contribute_DAO_ContributionRecur',
219 $this->_getParam('contributionRecurID'),
220 'processor_id', $reply['billingid']
223 $params['trxn_id'] = $reply['transid'];
225 $params['gross_amount'] = $tc_params['amount'] / 100;
230 /* Otherwise we return the error object */
236 * Hook to update CC info for a recurring contribution
238 * @param string $message The message to dispaly on update success/failure
239 * @param array $params The paramters to pass to the payment processor
241 * @return bool True if successful, false on failure
243 function updateSubscriptionBillingInfo(&$message = '', $params = array()) {
244 $expYear = $params['credit_card_exp_date']['Y'];
245 $expMonth = $params['credit_card_exp_date']['M'];
247 // TODO: This should be our build in params set function, not by hand!
249 'custid' => $this->_paymentProcessor
['user_name'],
250 'password' => $this->_paymentProcessor
['password'],
252 'billingid' => $params['subscriptionId'],
253 'avs' => 'y', // Enable address verification
254 'address1' => $params['street_address'],
255 'zip' => $params['postal_code'],
256 'name' => $this->_formatBillingName($params['first_name'],
257 $params['last_name']),
258 'cc' => $params['credit_card_number'],
259 'cvv' => $params['cvv2'],
260 'exp' => $this->_formatExpirationDate($expYear, $expMonth),
261 'amount' => $this->_formatAmount($params['amount']),
264 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $tc_params);
266 $reply = $this->_sendTCRequest($tc_params);
267 $result = $this->_getTCReply($reply);
270 // TODO: Respect vaules for $messages passed in from our caller
271 $message = 'Successfully updated TC billing id ' . $tc_params['billingid'];
279 // TODO: Use the formatting functions throughout the entire class to
280 // dedupe the conversions done elsewhere in a less reusable way.
283 * Internal routine to convert from CiviCRM amounts to TC amounts.
285 * Multiplies the amount by 100.
287 * @param float $amount The currency value to convert.
289 * @return int The TC amount
291 private function _formatAmount($amount) {
292 return $amount * 100;
296 * Internal routine to format the billing name for TC
298 * @param string $firstName The first name to submit to TC
299 * @param string $lastName The last name to submit to TC
301 * @return string The TC name format, "$firstName $lastName"
303 private function _formatBillingName($firstName, $lastName) {
304 return "$firstName $lastName";
308 * Formats the expiration date for TC
310 * @param int $year The credit card expiration year
311 * @param int $month The credit card expiration year
313 * @return The TC CC expiration date format, "$month$year"
315 private function _formatExpirationDate($year, $month) {
316 $exp_month = str_pad($month, 2, '0', STR_PAD_LEFT
);
317 $exp_year = substr($year, -2);
319 return "$exp_month$exp_year";
322 private function _isParamsBlacklisted($tc_params) {
323 if($tc_params['amount'] == 101) {
324 error_log("TrustCommerce: _isParamsBlacklisted() triggered");
332 * Checks to see if the source IP/USERAGENT are blacklisted.
334 * @return bool TRUE if on the blacklist, FALSE if not.
336 private function _isBlacklisted($tc_params) {
337 if($this->_isIPBlacklisted()) {
339 } else if($this->_isAgentBlacklisted()) {
341 } else if($this->_isParamsBlacklisted($tc_params)) {
349 * Checks to see if the source USERAGENT is blacklisted
351 * @return bool TRUE if on the blacklist, FALSE if not.
353 private function _isAgentBlacklisted() {
354 // TODO: fix DB calls to be more the CiviCRM way
355 $ip = $_SERVER['REMOTE_ADDR'];
356 $agent = $_SERVER['HTTP_USER_AGENT'];
357 $dao = CRM_Core_DAO
::executeQuery('SELECT * FROM `trustcommerce_useragent_blacklist`');
358 while($dao->fetch()) {
359 if(preg_match('/'.$dao->name
.'/', $agent) === 1) {
360 error_log(' [client '.$ip.'] [agent '.$agent.'] - Blacklisted by USER_AGENT rule #'.$dao->id
);
368 * Checks to see if the source IP is blacklisted
370 * @return bool TRUE if on the blacklist, FALSE if not.
372 private function _isIPBlacklisted() {
373 // TODO: fix DB calls to be more the CiviCRM way
374 $ip = $_SERVER['REMOTE_ADDR'];
375 $agent = $_SERVER['HTTP_USER_AGENT'];
377 $blacklist = array();
378 $dao = CRM_Core_DAO
::executeQuery('SELECT * FROM `trustcommerce_blacklist`');
379 while($dao->fetch()) {
380 if($ip >= $dao->start
&& $ip <= $dao->end
) {
381 error_log('[client '.long2ip($ip).'] [agent '.$agent.'] Blacklisted by IP rule #'.$dao->id
);
389 * Sends the API call to TC for processing
391 * @param array $request The array of paramaters to pass the TC API
393 * @return array The response from the TC API
395 function _sendTCRequest($request) {
396 $this->_logger($request);
397 return tclink_send($request);
401 * Logs paramaters from TC along with the remote address of the client
403 * Will log paramaters via the error_log() routine. For security reasons
404 * the following values are not logged (skipped): custid, password, cc
407 * @param array $params The paramaters to log
409 function _logger($params) {
411 foreach ($params as $key => $data) {
412 /* Delete any data we should not be writing to disk. This includes:
413 * custid, password, cc, exp, and cvv
423 $msg .= ' '.$key.' => '.$data;
426 error_log('[client '.$_SERVER['REMOTE_ADDR'].'] TrustCommerce:'.$msg);
430 * Gets the recurring billing fields for the TC API
432 * @param array $fields The fields to modify.
433 * @return array The fields for tclink_send(), modified for recurring billing.
436 function _getRecurPaymentFields($fields) {
437 $payments = $this->_getParam('frequency_interval');
438 $cycle = $this->_getParam('frequency_unit');
440 /* Translate billing cycle from CiviCRM -> TC */
456 /* Translate frequency interval from CiviCRM -> TC
457 * Payments are the same, HOWEVER a payment of 1 (forever) should be 0 in TC */
462 $fields['cycle'] = '1'.$cycle; /* The billing cycle in years, months, weeks, or days. */
463 $fields['payments'] = $payments;
464 $fields['action'] = 'store'; /* Change our mode to `store' mode. */
469 /** Parses a response from TC via the tclink_send() command.
471 * @param array $reply The result of a call to tclink_send().
473 * @return mixed|CRM_Core_Error CRM_Core_Error object if transaction failed, otherwise
476 function _getTCReply($reply) {
478 /* DUPLIATE CODE, please refactor. ~lisa */
480 return self
::error(9002, 'Could not initiate connection to payment gateway.');
483 $this->_logger($reply);
485 switch($reply['status']) {
486 case self
::AUTH_BLACKLIST
:
487 return self
::error(9001, "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.");
489 case self
::AUTH_APPROVED
:
491 case self
::AUTH_ACCEPTED
:
494 case self
::AUTH_DECLINED
:
495 // TODO FIXME be more or less specific?
496 // declinetype can be: decline, avs, cvv, call, expiredcard, carderror, authexpired, fraud, blacklist, velocity
497 // See TC documentation for more info
498 switch($reply['declinetype']) {
500 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.");
503 return self
::error(9009, "Your transaction was declined. Please check the correctness of your credit card information, including CC number, expiration date and CVV code.");
505 case self
::AUTH_BADDATA
:
506 // TODO FIXME do something with $reply['error'] and $reply['offender']
507 return self
::error(9011, "Invalid credit card information. The following fields were invalid: {$reply['offenders']}.");
509 case self
::AUTH_ERROR
:
510 return self
::error(9002, 'Could not initiate connection to payment gateway');
517 * Generate the basic paramaters to send the TC API
519 * @return array The array of paramaters to pass _sendTCRequest()
521 function _getTrustCommerceFields() {
522 // Total amount is from the form contribution field
523 $amount = $this->_getParam('total_amount');
524 // CRM-9894 would this ever be the case??
525 if (empty($amount)) {
526 $amount = $this->_getParam('amount');
530 $fields['custid'] = $this->_paymentProcessor
['user_name'];
531 $fields['password'] = $this->_paymentProcessor
['password'];
533 $fields['action'] = 'sale';
535 // Enable address verification
536 $fields['avs'] = 'y';
538 $fields['address1'] = $this->_getParam('street_address');
539 $fields['zip'] = $this->_getParam('postal_code');
541 $fields['name'] = $this->_getParam('billing_first_name') . ' ' . $this->_getParam('billing_last_name');
543 // This assumes currencies where the . is used as the decimal point, like USD
544 $amount = preg_replace("/([^0-9\\.])/i", "", $amount);
546 // We need to pass the amount to TrustCommerce in dollar cents
547 $fields['amount'] = $amount * 100;
550 $fields['ticket'] = substr($this->_getParam('invoiceID'), 0, 20);
553 $fields['cc'] = $this->_getParam('credit_card_number');
554 $fields['cvv'] = $this->_getParam('cvv2');
555 $exp_month = str_pad($this->_getParam('month'), 2, '0', STR_PAD_LEFT
);
556 $exp_year = substr($this->_getParam('year'),-2);
557 $fields['exp'] = "$exp_month$exp_year";
559 if ($this->_mode
!= 'live') {
560 $fields['demo'] = 'y';
566 * Checks to see if invoice_id already exists in db
568 * @param int $invoiceId The ID to check
570 * @return bool True if ID exists, else false
572 function _checkDupe($invoiceId) {
573 require_once 'CRM/Contribute/DAO/Contribution.php';
574 $contribution = new CRM_Contribute_DAO_Contribution();
575 $contribution->invoice_id
= $invoiceId;
576 return $contribution->find();
580 * Get the value of a field if set
582 * @param string $field the field
584 * @return mixed value of the field, or empty string if the field is
587 function _getParam($field) {
588 $value = CRM_Utils_Array
::value($field, $this->_params
, '');
590 $value = str_replace(array('&', '"', "'", '<', '>'), '', $value);
596 * Sets our error message/logging information for CiviCRM
598 * @param int $errorCode The numerical code of the error, defaults to 9001
599 * @param string $errorMessage The error message to display/log
601 * @return CRM_Core_Error The error object with message and code.
603 function &error($errorCode = NULL, $errorMessage = NULL) {
604 $e = CRM_Core_Error
::singleton();
606 $e->push($errorCode, 0, NULL, $errorMessage);
609 $e->push(9001, 0, NULL, 'Unknown System Error.');
615 * Set a field to the specified value. Value must be a scalar (int,
616 * float, string, or boolean)
618 * @param string $field
619 * @param mixed $value
621 * @return bool false if value is not a scalar, true if successful
623 function _setParam($field, $value) {
624 if (!is_scalar($value)) {
628 $this->_params
[$field] = $value;
633 * Checks to see if we have the manditory config values set.
635 * @return string the error message if any
638 function checkConfig() {
640 if (empty($this->_paymentProcessor
['user_name'])) {
641 $error[] = ts('Customer ID is not set for this payment processor');
644 if (empty($this->_paymentProcessor
['password'])) {
645 $error[] = ts('Password is not set for this payment processor');
648 if (!empty($error)) {
649 return implode('<p>', $error);
656 * Hook to cancel a recurring contribution
658 * @param string $message The message to dispaly on update success/failure
659 * @param array $params The paramters to pass to the payment processor
661 * @return bool True if successful, false on failure
663 function cancelSubscription(&$message = '', $params = array()) {
664 $tc_params['custid'] = $this->_getParam('user_name');
665 $tc_params['password'] = $this->_getParam('password');
666 $tc_params['action'] = 'unstore';
667 $tc_params['billingid'] = CRM_Utils_Array
::value('subscriptionId', $params);
669 $result = $this->_sendTCRequest($tc_params);
671 /* Test if call failed */
673 return self
::error(9002, 'Could not initiate connection to payment gateway');
675 /* We are done, pass success */
680 * Hook to update amount billed for a recurring contribution
682 * @param string $message The message to dispaly on update success/failure
683 * @param array $params The paramters to pass to the payment processor
685 * @return bool True if successful, false on failure
687 function changeSubscriptionAmount(&$message = '', $params = array()) {
688 $tc_params['custid'] = $this->_paymentProcessor
['user_name'];
689 $tc_params['password'] = $this->_paymentProcessor
['password'];
690 $tc_params['action'] = 'store';
692 $tc_params['billingid'] = CRM_Utils_Array
::value('subscriptionId', $params);
693 $tc_params['payments'] = CRM_Utils_Array
::value('installments', $params);
694 $tc_params['amount'] = CRM_Utils_Array
::value('amount', $params) * 100;
696 if($tc_params['payments'] == 1) {
697 $tc_params['payments'] = 0;
699 $reply = $this->_sendTCRequest($tc_params);
700 $result = $this->_getTCReply($reply);
702 /* We are done, pass success */
708 * Installs the trustcommerce module (currently a dummy)
710 public function install() {
715 * Uninstalls the trustcommerce module (currently a dummy)
717 public function uninstall() {