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