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>
27 // Define logging level (0 = off, 4 = log everything)
28 define('TRUSTCOMMERCE_LOGGING_LEVEL', 4);
30 require_once 'CRM/Core/Payment.php';
31 class 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';
37 CONST AUTH_BLACKLIST
= 'blacklisted';
39 static protected $_mode = NULL;
41 static protected $_params = array();
44 * We only need one instance of this object. So we use the singleton
45 * pattern and cache the instance in this variable
50 static private $_singleton = NULL;
55 * @param string $mode the mode of operation: live or test
58 */ function __construct($mode, &$paymentProcessor) {
61 $this->_paymentProcessor
= $paymentProcessor;
63 $this->_processorName
= ts('TrustCommerce');
65 $config = CRM_Core_Config
::singleton();
66 $this->_setParam('user_name', $paymentProcessor['user_name']);
67 $this->_setParam('password', $paymentProcessor['password']);
69 $this->_setParam('timestamp', time());
71 $this->_setParam('sequence', rand(1, 1000));
72 $this->logging_level
= TRUSTCOMMERCE_LOGGING_LEVEL
;
77 * singleton function used to manage this object
79 * @param string $mode the mode of operation: live or test
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);
91 return self
::$_singleton[$processorName];
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.
100 function doDirectPayment(&$params) {
101 if (!extension_loaded("tclink")) {
102 return self
::error(9001, 'TrustCommerce requires that the tclink module is loaded');
105 /* Copy our paramaters to ourself */
106 foreach ($params as $field => $value) {
107 $this->_setParam($field, $value);
110 /* Get our fields to pass to tclink_send() */
111 $tc_params = $this->_getTrustCommerceFields();
113 /* Are we recurring? If so add the extra API fields. */
114 if (CRM_Utils_Array
::value('is_recur', $params) == 1) {
115 $tc_params = $this->_getRecurPaymentFields($tc_params);
119 /* Pass our cooked params to the alter hook, per Core/Payment/Dummy.php */
120 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $tc_params);
122 // TrustCommerce will not refuse duplicates, so we should check if the user already submitted this transaction
123 if ($this->_checkDupe($tc_params['ticket'])) {
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.');
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);
133 $this->_logger($tc_params);
134 $reply['status'] = self
::AUTH_BLACKLIST
;
137 /* Parse our reply */
138 $result = $this->_getTCReply($reply);
141 /* We were successful, congrats. Lets wrap it up:
142 * Convert back to dollars
143 * Save the transaction ID
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']
154 $params['trxn_id'] = $reply['transid'];
156 $params['gross_amount'] = $tc_params['amount'] / 100;
161 /* Otherwise we return the error object */
167 * Update CC info for a recurring contribution
169 function updateSubscriptionBillingInfo(&$message = '', $params = array()) {
170 $expYear = $params['credit_card_exp_date']['Y'];
171 $expMonth = $params['credit_card_exp_date']['M'];
174 'custid' => $this->_paymentProcessor
['user_name'],
175 'password' => $this->_paymentProcessor
['password'],
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']),
189 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $tc_params);
191 $reply = $this->_sendTCRequest($tc_params);
192 $result = $this->_getTCReply($reply);
195 $message = 'Successfully updated TC billing id ' . $tc_params['billingid'];
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;
209 function _formatBillingName($firstName, $lastName) {
210 return "$firstName $lastName";
213 function _formatExpirationDate($year, $month) {
214 $exp_month = str_pad($month, 2, '0', STR_PAD_LEFT
);
215 $exp_year = substr($year, -2);
217 return "$exp_month$exp_year";
220 function _isBlacklisted() {
221 if($this->_isIPBlacklisted()) {
223 } else if($this->_IsAgentBlacklisted()) {
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) {
235 error_log(' [client '.$ip.'] [agent '.$agent.'] - Blacklisted by USER_AGENT rule #'.$dao->id
);
242 function _isIPBlacklisted() {
243 $ip = $_SERVER['REMOTE_ADDR'];
244 $agent = $_SERVER['HTTP_USER_AGENT'];
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
) {
250 error_log('[client '.long2ip($ip).'] [agent '.$agent.'] Blacklisted by IP rule #'.$dao->id
);
257 function _sendTCRequest($request) {
258 $this->_logger($request);
259 return tclink_send($request);
262 function _logger($params) {
264 foreach ($params as $key => $data) {
265 /* Delete any data we should not be writing to disk. This includes:
266 * custid, password, cc, exp, and cvv
276 $msg .= ' '.$key.' => '.$data;
279 error_log('[client '.$_SERVER['REMOTE_ADDR'].'] TrustCommerce:'.$msg);
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.
288 function _getRecurPaymentFields($fields) {
289 $payments = $this->_getParam('frequency_interval');
290 $cycle = $this->_getParam('frequency_unit');
292 /* Translate billing cycle from CiviCRM -> TC */
308 /* Translate frequency interval from CiviCRM -> TC
309 * Payments are the same, HOWEVER a payment of 1 (forever) should be 0 in TC */
314 $fields['cycle'] = '1'.$cycle; /* The billing cycle in years, months, weeks, or days. */
315 $fields['payments'] = $payments;
316 $fields['authnow'] = 'y';
317 $fields['start'] = date("Y-m-d"); /* Start date is required when 'authnow' is used. */
318 $fields['action'] = 'store'; /* Change our mode to `store' mode. */
323 /* Parses a response from TC via the tclink_send() command.
324 * @param $reply array The result of a call to tclink_send().
325 * @return mixed self::error() if transaction failed, otherwise returns 0.
327 function _getTCReply($reply) {
329 /* DUPLIATE CODE, please refactor. ~lisa */
331 return self
::error(9002, 'Could not initiate connection to payment gateway');
334 $this->_logger($reply);
336 switch($reply['status']) {
337 case self
::AUTH_BLACKLIST
:
338 return self
::error(9001, "Your transaction was declined: error #90210");
340 case self
::AUTH_APPROVED
:
343 case self
::AUTH_DECLINED
:
344 // TODO FIXME be more or less specific?
345 // declinetype can be: decline, avs, cvv, call, expiredcard, carderror, authexpired, fraud, blacklist, velocity
346 // See TC documentation for more info
347 switch($reply['declinetype']) {
349 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.");
352 return self
::error(9009, "Your transaction was declined: {$reply['declinetype']}");
354 case self
::AUTH_BADDATA
:
355 // TODO FIXME do something with $reply['error'] and $reply['offender']
356 return self
::error(9011, "Invalid credit card information. The following fields were invalid: {$reply['offenders']}.");
358 case self
::AUTH_ERROR
:
359 return self
::error(9002, 'Could not initiate connection to payment gateway');
365 function _getTrustCommerceFields() {
366 // Total amount is from the form contribution field
367 $amount = $this->_getParam('total_amount');
368 // CRM-9894 would this ever be the case??
369 if (empty($amount)) {
370 $amount = $this->_getParam('amount');
373 $fields['custid'] = $this->_getParam('user_name');
374 $fields['password'] = $this->_getParam('password');
375 $fields['action'] = 'sale';
377 // Enable address verification
378 $fields['avs'] = 'y';
380 $fields['address1'] = $this->_getParam('street_address');
381 $fields['zip'] = $this->_getParam('postal_code');
383 $fields['name'] = $this->_getParam('billing_first_name') . ' ' . $this->_getParam('billing_last_name');
385 // This assumes currencies where the . is used as the decimal point, like USD
386 $amount = preg_replace("/([^0-9\\.])/i", "", $amount);
388 // We need to pass the amount to TrustCommerce in dollar cents
389 $fields['amount'] = $amount * 100;
392 $fields['ticket'] = substr($this->_getParam('invoiceID'), 0, 20);
395 $fields['cc'] = $this->_getParam('credit_card_number');
396 $fields['cvv'] = $this->_getParam('cvv2');
397 $exp_month = str_pad($this->_getParam('month'), 2, '0', STR_PAD_LEFT
);
398 $exp_year = substr($this->_getParam('year'),-2);
399 $fields['exp'] = "$exp_month$exp_year";
401 if ($this->_mode
!= 'live') {
402 $fields['demo'] = 'y';
408 * Checks to see if invoice_id already exists in db
410 * @param int $invoiceId The ID to check
412 * @return bool True if ID exists, else false
414 function _checkDupe($invoiceId) {
415 require_once 'CRM/Contribute/DAO/Contribution.php';
416 $contribution = new CRM_Contribute_DAO_Contribution();
417 $contribution->invoice_id
= $invoiceId;
418 return $contribution->find();
422 * Get the value of a field if set
424 * @param string $field the field
426 * @return mixed value of the field, or empty string if the field is
429 function _getParam($field) {
430 return CRM_Utils_Array
::value($field, $this->_params
, '');
433 function &error($errorCode = NULL, $errorMessage = NULL) {
434 $e = CRM_Core_Error
::singleton();
436 $e->push($errorCode, 0, NULL, $errorMessage);
439 $e->push(9001, 0, NULL, 'Unknown System Error.');
445 * Set a field to the specified value. Value must be a scalar (int,
446 * float, string, or boolean)
448 * @param string $field
449 * @param mixed $value
451 * @return bool false if value is not a scalar, true if successful
453 function _setParam($field, $value) {
454 if (!is_scalar($value)) {
458 $this->_params
[$field] = $value;
463 * This function checks to see if we have the right config values
465 * @return string the error message if any
468 function checkConfig() {
470 if (empty($this->_paymentProcessor
['user_name'])) {
471 $error[] = ts('Customer ID is not set for this payment processor');
474 if (empty($this->_paymentProcessor
['password'])) {
475 $error[] = ts('Password is not set for this payment processor');
478 if (!empty($error)) {
479 return implode('<p>', $error);
485 function cancelSubscription(&$message = '', $params = array()) {
486 $tc_params['custid'] = $this->_getParam('user_name');
487 $tc_params['password'] = $this->_getParam('password');
488 $tc_params['action'] = 'unstore';
489 $tc_params['billingid'] = CRM_Utils_Array
::value('trxn_id', $params);
491 $result = $this->_sendTCRequest($tc_params);
493 /* Test if call failed */
495 return self
::error(9002, 'Could not initiate connection to payment gateway');
497 /* We are done, pass success */
501 function changeSubscriptionAmount(&$message = '', $params = array()) {
502 $tc_params['custid'] = $this->_getParam('user_name');
503 $tc_params['password'] = $this->_getParam('password');
504 $tc_params['action'] = 'store';
506 $tc_params['billingid'] = CRM_Utils_Array
::value('subscriptionId', $params);
507 $tc_params['payments'] = CRM_Utils_Array
::value('installments', $params);
508 $tc_params['amount'] = CRM_Utils_Array
::value('amount', $params) * 100;
510 if($tc_params['payments'] == 1) {
511 $tc_params['payments'] = 0;
513 $reply = $this->_sendTCRequest($tc_params);
514 $result = $this->_getTCReply($reply);
516 /* Test if call failed */
518 return self
::error(9002, 'Could not initiate connection to payment gateway');
521 /* We are done, pass success */
526 public function install() {
530 public function uninstall() {