Changed function names for less typing.
[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';
36
37 static protected $_mode = NULL;
38
39 static protected $_params = array();
40
41 /**
42 * We only need one instance of this object. So we use the singleton
43 * pattern and cache the instance in this variable
44 *
45 * @var object
46 * @static
47 */
48 static private $_singleton = NULL;
49
50 /**
51 * Constructor
52 *
53 * @param string $mode the mode of operation: live or test
54 *
55 * @return void
56 */ function __construct($mode, &$paymentProcessor) {
57 $this->_mode = $mode;
58
59 $this->_paymentProcessor = $paymentProcessor;
60
61 $this->_processorName = ts('TrustCommerce');
62
63 $config = CRM_Core_Config::singleton();
64 $this->_setParam('user_name', $paymentProcessor['user_name']);
65 $this->_setParam('password', $paymentProcessor['password']);
66
67 $this->_setParam('timestamp', time());
68 srand(time());
69 $this->_setParam('sequence', rand(1, 1000));
70 $this->logging_level = TRUSTCOMMERCE_LOGGING_LEVEL;
71 }
72
73 /**
74 * singleton function used to manage this object
75 *
76 * @param string $mode the mode of operation: live or test
77 *
78 * @return object
79 * @static
80 *
81 */
82 static
83 function &singleton($mode, &$paymentProcessor) {
84 $processorName = $paymentProcessor['name'];
85 if (self::$_singleton[$processorName] === NULL) {
86 self::$_singleton[$processorName] = new org_fsf_payment_trustcommerce($mode, $paymentProcessor);
87 }
88 return self::$_singleton[$processorName];
89 }
90
91 /**
e0273c0a
LMM
92 * Submit a payment using the TC API
93 * @param array $params The params we will be sending to tclink_send()
94 * @return mixed An array of our results, or an error object if the transaction fails.
71a6ba5c
LMM
95 * @public
96 */
97 function doDirectPayment(&$params) {
98 if (!extension_loaded("tclink")) {
99 return self::error(9001, 'TrustCommerce requires that the tclink module is loaded');
100 }
101
f322addf
LMM
102 /* Copy our paramaters to ourself */
103 foreach ($params as $field => $value) {
71a6ba5c
LMM
104 $this->_setParam($field, $value);
105 }
106
f322addf
LMM
107 /* Get our fields to pass to tclink_send() */
108 $tc_params = $this->_getTrustCommerceFields();
71a6ba5c 109
f322addf
LMM
110 /* Are we recurring? If so add the extra API fields. */
111 if (CRM_Utils_Array::value('is_recur', $params) && $params['contributionRecurID']) {
112 $tc_params = $this->_getRecurPaymentFields($tc_params);
113 }
71a6ba5c 114
f322addf 115 /* Pass our cooked params to the alter hook, per Core/Payment/Dummy.php */
32bf0975 116 CRM_Utils_Hook::alterPaymentProcessorParams($this, $params, $tc_params);
71a6ba5c
LMM
117
118 // TrustCommerce will not refuse duplicates, so we should check if the user already submitted this transaction
f322addf 119 if ($this->_checkDupe($tc_params['ticket'])) {
71a6ba5c
LMM
120 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.');
121 }
122
f322addf
LMM
123 /* Call the TC API, and grab the reply */
124 $reply = tclink_send($tc_params);
71a6ba5c 125
f322addf 126 /* Parse our reply */
5efae07f 127 $result = $this->_getTCReply($reply);
71a6ba5c 128
f322addf
LMM
129 if($result == 0) {
130 /* We were successful, congrats. Lets wrap it up:
131 * Convert back to dollars
132 * Save the transaction ID
133 */
134 $params['trxn_id'] = $reply['transid'];
135 $params['gross_amount'] = $tc_params['amount'] / 100;
71a6ba5c 136
f322addf 137 return $params;
71a6ba5c 138
f322addf
LMM
139 } else {
140 /* Otherwise we return the error object */
141 return $result;
142 }
71a6ba5c
LMM
143 }
144
145 /**
f322addf
LMM
146 * Gets the recurring billing fields for the TC API
147 * @param array $fields The fields to modify.
148 * @return array The fields for tclink_send(), modified for recurring billing.
71a6ba5c
LMM
149 * @public
150 */
f322addf 151 function _getRecurPaymentFields($fields) {
285eaf25
LMM
152 $payments = $this->_getParam('frequency_interval');
153 $cycle = $this->_getParam('frequency_unit');
71a6ba5c 154
f322addf 155 /* Translate billing cycle from CiviCRM -> TC */
285eaf25
LMM
156 switch($cycle) {
157 case 'day':
158 $cycle = 'd';
159 break;
160 case 'week':
161 $cycle = 'w';
162 break;
163 case 'month':
164 $cycle = 'm';
165 break;
166 case 'year':
167 $cycle = 'y';
168 break;
71a6ba5c 169 }
bc323ec4
LMM
170
171 /* Translate frequency interval from CiviCRM -> TC
172 * Payments are the same, HOWEVER a payment of 1 (forever) should be 0 in TC */
173 if($payments == 1) {
174 $payments = 0;
71a6ba5c 175 }
71a6ba5c 176
bc323ec4
LMM
177 $fields['cycle'] = '1'.$cycle; /* The billing cycle in years, months, weeks, or days. */
178 $fields['payments'] = $payments;
179 $fields['action'] = 'store'; /* Change our mode to `store' mode. */
71a6ba5c 180
bc323ec4 181 return $fields;
a79ba043
LMM
182 }
183
184 /* Parses a response from TC via the tclink_send() command.
185 * @param $reply array The result of a call to tclink_send().
186 * @return mixed self::error() if transaction failed, otherwise returns 0.
187 */
5efae07f 188 function _getTCReply($reply) {
71a6ba5c 189
285eaf25 190 /* DUPLIATE CODE, please refactor. ~lisa */
bc323ec4 191 if (!$reply) {
285eaf25 192 return self::error(9002, 'Could not initiate connection to payment gateway');
71a6ba5c
LMM
193 }
194
bc323ec4 195 switch($reply['status']) {
285eaf25
LMM
196 case self::AUTH_APPROVED:
197 // It's all good
198 break;
199 case self::AUTH_DECLINED:
200 // TODO FIXME be more or less specific?
201 // declinetype can be: decline, avs, cvv, call, expiredcard, carderror, authexpired, fraud, blacklist, velocity
202 // See TC documentation for more info
a8c5366f 203 return self::error(9009, "Your transaction was declined: {$reply['declinetype']}");
285eaf25
LMM
204 break;
205 case self::AUTH_BADDATA:
a8c5366f
LMM
206 // TODO FIXME do something with $reply['error'] and $reply['offender']
207 return self::error(9011, "Invalid credit card information. The following fields were invalid: {$reply['offenders']}.");
285eaf25
LMM
208 break;
209 case self::AUTH_ERROR:
210 return self::error(9002, 'Could not initiate connection to payment gateway');
211 break;
71a6ba5c 212 }
a79ba043 213 return 0;
71a6ba5c
LMM
214 }
215
216 function _getTrustCommerceFields() {
217 // Total amount is from the form contribution field
218 $amount = $this->_getParam('total_amount');
219 // CRM-9894 would this ever be the case??
220 if (empty($amount)) {
221 $amount = $this->_getParam('amount');
222 }
223 $fields = array();
224 $fields['custid'] = $this->_getParam('user_name');
225 $fields['password'] = $this->_getParam('password');
226 $fields['action'] = 'sale';
227
228 // Enable address verification
229 $fields['avs'] = 'y';
230
231 $fields['address1'] = $this->_getParam('street_address');
232 $fields['zip'] = $this->_getParam('postal_code');
233
234 $fields['name'] = $this->_getParam('billing_first_name') . ' ' . $this->_getParam('billing_last_name');
235
236 // This assumes currencies where the . is used as the decimal point, like USD
237 $amount = preg_replace("/([^0-9\\.])/i", "", $amount);
238
239 // We need to pass the amount to TrustCommerce in dollar cents
240 $fields['amount'] = $amount * 100;
241
242 // Unique identifier
243 $fields['ticket'] = substr($this->_getParam('invoiceID'), 0, 20);
244
245 // cc info
246 $fields['cc'] = $this->_getParam('credit_card_number');
247 $fields['cvv'] = $this->_getParam('cvv2');
248 $exp_month = str_pad($this->_getParam('month'), 2, '0', STR_PAD_LEFT);
249 $exp_year = substr($this->_getParam('year'),-2);
250 $fields['exp'] = "$exp_month$exp_year";
251
252 if ($this->_mode != 'live') {
253 $fields['demo'] = 'y';
254 }
71a6ba5c
LMM
255 return $fields;
256 }
257
258 /**
259 * Checks to see if invoice_id already exists in db
260 *
261 * @param int $invoiceId The ID to check
262 *
263 * @return bool True if ID exists, else false
264 */
265 function _checkDupe($invoiceId) {
266 require_once 'CRM/Contribute/DAO/Contribution.php';
267 $contribution = new CRM_Contribute_DAO_Contribution();
268 $contribution->invoice_id = $invoiceId;
269 return $contribution->find();
270 }
271
272 /**
273 * Get the value of a field if set
274 *
275 * @param string $field the field
276 *
277 * @return mixed value of the field, or empty string if the field is
278 * not set
279 */
280 function _getParam($field) {
281 return CRM_Utils_Array::value($field, $this->_params, '');
282 }
283
284 function &error($errorCode = NULL, $errorMessage = NULL) {
285 $e = CRM_Core_Error::singleton();
286 if ($errorCode) {
287 $e->push($errorCode, 0, NULL, $errorMessage);
288 }
289 else {
290 $e->push(9001, 0, NULL, 'Unknown System Error.');
291 }
292 return $e;
293 }
294
295 /**
296 * Set a field to the specified value. Value must be a scalar (int,
297 * float, string, or boolean)
298 *
299 * @param string $field
300 * @param mixed $value
301 *
302 * @return bool false if value is not a scalar, true if successful
303 */
304 function _setParam($field, $value) {
305 if (!is_scalar($value)) {
306 return FALSE;
307 }
308 else {
309 $this->_params[$field] = $value;
310 }
311 }
312
313 /**
314 * This function checks to see if we have the right config values
315 *
316 * @return string the error message if any
317 * @public
318 */
319 function checkConfig() {
320 $error = array();
321 if (empty($this->_paymentProcessor['user_name'])) {
322 $error[] = ts('Customer ID is not set for this payment processor');
323 }
324
325 if (empty($this->_paymentProcessor['password'])) {
326 $error[] = ts('Password is not set for this payment processor');
327 }
328
329 if (!empty($error)) {
330 return implode('<p>', $error);
331 } else {
332 return NULL;
333 }
334 }
335
14f15ff3 336 function cancelSubscription(&$message = '', $params = array()) {
7964e0e9
LMM
337 $tc_params['custid'] = $this->_getParam('user_name');
338 $tc_params['password'] = $this->_getParam('password');
339 $tc_params['action'] = 'unstore';
cbf5200e 340 $tc_params['billingid'] = CRM_Utils_Array::value('trxn_id', $params);
71a6ba5c 341
7964e0e9 342 $result = tclink_send($tc_params);
71a6ba5c 343
7964e0e9
LMM
344 /* Test if call failed */
345 if(!$result) {
71a6ba5c
LMM
346 return self::error(9002, 'Could not initiate connection to payment gateway');
347 }
7964e0e9 348 /* We are done, pass success */
71a6ba5c
LMM
349 return TRUE;
350 }
351
352 public function install() {
353 return TRUE;
354 }
355
356 public function uninstall() {
357 return TRUE;
358 }
359
360}