Cleaned up documentation for doDirectPayment()
[trustcommerce.git] / trustcommerce.php
CommitLineData
71a6ba5c
LMM
1<?php
2/*
3 * Copyright (C) 2012
4 * Licensed to CiviCRM under the GPL v3 or higher
5 *
6 * Written and contributed by Ward Vandewege <ward@fsf.org> (http://www.fsf.org)
68f3cf09 7 * Modified by Lisa Marie Maginnis <lisa@fsf.org> (http://www.fsf.org)
71a6ba5c
LMM
8 *
9 */
10
11// Define logging level (0 = off, 4 = log everything)
12define('TRUSTCOMMERCE_LOGGING_LEVEL', 4);
13
14require_once 'CRM/Core/Payment.php';
15class org_fsf_payment_trustcommerce extends CRM_Core_Payment {
16 CONST CHARSET = 'iso-8859-1';
17 CONST AUTH_APPROVED = 'approve';
18 CONST AUTH_DECLINED = 'decline';
19 CONST AUTH_BADDATA = 'baddata';
20 CONST AUTH_ERROR = 'error';
21
22 static protected $_mode = NULL;
23
24 static protected $_params = array();
25
26 /**
27 * We only need one instance of this object. So we use the singleton
28 * pattern and cache the instance in this variable
29 *
30 * @var object
31 * @static
32 */
33 static private $_singleton = NULL;
34
35 /**
36 * Constructor
37 *
38 * @param string $mode the mode of operation: live or test
39 *
40 * @return void
41 */ function __construct($mode, &$paymentProcessor) {
42 $this->_mode = $mode;
43
44 $this->_paymentProcessor = $paymentProcessor;
45
46 $this->_processorName = ts('TrustCommerce');
47
48 $config = CRM_Core_Config::singleton();
49 $this->_setParam('user_name', $paymentProcessor['user_name']);
50 $this->_setParam('password', $paymentProcessor['password']);
51
52 $this->_setParam('timestamp', time());
53 srand(time());
54 $this->_setParam('sequence', rand(1, 1000));
55 $this->logging_level = TRUSTCOMMERCE_LOGGING_LEVEL;
56 }
57
58 /**
59 * singleton function used to manage this object
60 *
61 * @param string $mode the mode of operation: live or test
62 *
63 * @return object
64 * @static
65 *
66 */
67 static
68 function &singleton($mode, &$paymentProcessor) {
69 $processorName = $paymentProcessor['name'];
70 if (self::$_singleton[$processorName] === NULL) {
71 self::$_singleton[$processorName] = new org_fsf_payment_trustcommerce($mode, $paymentProcessor);
72 }
73 return self::$_singleton[$processorName];
74 }
75
76 /**
e0273c0a
LMM
77 * Submit a payment using the TC API
78 * @param array $params The params we will be sending to tclink_send()
79 * @return mixed An array of our results, or an error object if the transaction fails.
71a6ba5c
LMM
80 * @public
81 */
82 function doDirectPayment(&$params) {
83 if (!extension_loaded("tclink")) {
84 return self::error(9001, 'TrustCommerce requires that the tclink module is loaded');
85 }
86
71a6ba5c
LMM
87 $newParams = $params;
88 if (CRM_Utils_Array::value('is_recur', $params) &&
89 $params['contributionRecurID']
90 ) {
91 CRM_Utils_Hook::alterPaymentProcessorParams($this,
92 $params,
93 $newParams
94 );
95 }
96 foreach ($newParams as $field => $value) {
97 $this->_setParam($field, $value);
98 }
99
100 if (CRM_Utils_Array::value('is_recur', $params) &&
101 $params['contributionRecurID']
102 ) {
103 return $this->doRecurPayment($params);
104 }
105
106 $postFields = array();
107 $tclink = $this->_getTrustCommerceFields();
108
109 // Set up our call for hook_civicrm_paymentProcessor,
110 // since we now have our parameters as assigned for the AIM back end.
111 CRM_Utils_Hook::alterPaymentProcessorParams($this,
112 $params,
113 $tclink
114 );
115
116 // TrustCommerce will not refuse duplicates, so we should check if the user already submitted this transaction
117 if ($this->_checkDupe($tclink['ticket'])) {
118 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.');
119 }
120
121 $result = tclink_send($tclink);
122
123 if (!$result) {
124 return self::error(9002, 'Could not initiate connection to payment gateway');
125 }
126
127 foreach ($result as $field => $value) {
128 error_log("result: $field => $value");
129 }
130
131 switch($result['status']) {
132 case self::AUTH_APPROVED:
133 // It's all good
134 break;
135 case self::AUTH_DECLINED:
136 // TODO FIXME be more or less specific?
137 // declinetype can be: decline, avs, cvv, call, expiredcard, carderror, authexpired, fraud, blacklist, velocity
138 // See TC documentation for more info
139 return self::error(9009, "Your transaction was declined: {$result['declinetype']}");
140 break;
141 case self::AUTH_BADDATA:
142 // TODO FIXME do something with $result['error'] and $result['offender']
143 return self::error(9011, "Invalid credit card information. Please re-enter.");
144 break;
145 case self::AUTH_ERROR:
146 return self::error(9002, 'Could not initiate connection to payment gateway');
147 break;
148 }
149
150 // Success
151
152 $params['trxn_id'] = $result['transid'];
153 $params['gross_amount'] = $tclink['amount'] / 100;
154
155 return $params;
156 }
157
158 /**
159 * Submit an Automated Recurring Billing subscription
160 *
161 * @param array $params assoc array of input parameters for this transaction
162 *
163 * @return array the result in a nice formatted array (or an error object)
164 * @public
165 */
166 function doRecurPayment(&$params) {
285eaf25
LMM
167 $payments = $this->_getParam('frequency_interval');
168 $cycle = $this->_getParam('frequency_unit');
71a6ba5c 169
285eaf25
LMM
170 /* Sort out our billing scheme */
171 switch($cycle) {
172 case 'day':
173 $cycle = 'd';
174 break;
175 case 'week':
176 $cycle = 'w';
177 break;
178 case 'month':
179 $cycle = 'm';
180 break;
181 case 'year':
182 $cycle = 'y';
183 break;
184 default:
185 return self::error(9001, 'Payment interval not set! Unable to process payment.');
186 break;
71a6ba5c
LMM
187 }
188
71a6ba5c 189
285eaf25
LMM
190 $params['authnow'] = 'y'; /* Process this payment `now' */
191 $params['cycle'] = $cycle; /* The billing cycle in years, months, weeks, or days. */
192 $params['payments'] = $payments;
71a6ba5c 193
71a6ba5c 194
285eaf25 195 $tclink = $this->_getTrustCommerceFields();
71a6ba5c 196
285eaf25
LMM
197 // Set up our call for hook_civicrm_paymentProcessor,
198 // since we now have our parameters as assigned for the AIM back end.
199 CRM_Utils_Hook::alterPaymentProcessorParams($this,
200 $params,
201 $tclink
202 );
71a6ba5c 203
285eaf25
LMM
204 // TrustCommerce will not refuse duplicates, so we should check if the user already submitted this transaction
205 if ($this->_checkDupe($tclink['ticket'])) {
206 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.');
71a6ba5c 207 }
71a6ba5c 208
285eaf25 209 $result = tclink_send($tclink);
71a6ba5c 210
a79ba043
LMM
211 $result = _getTrustCommereceResponse($result);
212
213 if($result == 0) {
214 /* Transaction was sucessful */
215 $params['trxn_id'] = $result['transid']; /* Get our transaction ID */
216 $params['gross_amount'] = $tclink['amount']/100; /* Convert from cents to dollars */
217 return $params;
218 } else {
219 /* Transaction was *not* successful */
220 return $result;
221 }
222 }
223
224 /* Parses a response from TC via the tclink_send() command.
225 * @param $reply array The result of a call to tclink_send().
226 * @return mixed self::error() if transaction failed, otherwise returns 0.
227 */
228 function _getTrustCommerceResponse($reply) {
71a6ba5c 229
285eaf25
LMM
230 /* DUPLIATE CODE, please refactor. ~lisa */
231 if (!$result) {
232 return self::error(9002, 'Could not initiate connection to payment gateway');
71a6ba5c
LMM
233 }
234
285eaf25
LMM
235 switch($result['status']) {
236 case self::AUTH_APPROVED:
237 // It's all good
238 break;
239 case self::AUTH_DECLINED:
240 // TODO FIXME be more or less specific?
241 // declinetype can be: decline, avs, cvv, call, expiredcard, carderror, authexpired, fraud, blacklist, velocity
242 // See TC documentation for more info
243 return self::error(9009, "Your transaction was declined: {$result['declinetype']}");
244 break;
245 case self::AUTH_BADDATA:
246 // TODO FIXME do something with $result['error'] and $result['offender']
247 return self::error(9011, "Invalid credit card information. Please re-enter.");
248 break;
249 case self::AUTH_ERROR:
250 return self::error(9002, 'Could not initiate connection to payment gateway');
251 break;
71a6ba5c 252 }
a79ba043 253 return 0;
71a6ba5c
LMM
254 }
255
256 function _getTrustCommerceFields() {
257 // Total amount is from the form contribution field
258 $amount = $this->_getParam('total_amount');
259 // CRM-9894 would this ever be the case??
260 if (empty($amount)) {
261 $amount = $this->_getParam('amount');
262 }
263 $fields = array();
264 $fields['custid'] = $this->_getParam('user_name');
265 $fields['password'] = $this->_getParam('password');
266 $fields['action'] = 'sale';
267
268 // Enable address verification
269 $fields['avs'] = 'y';
270
271 $fields['address1'] = $this->_getParam('street_address');
272 $fields['zip'] = $this->_getParam('postal_code');
273
274 $fields['name'] = $this->_getParam('billing_first_name') . ' ' . $this->_getParam('billing_last_name');
275
276 // This assumes currencies where the . is used as the decimal point, like USD
277 $amount = preg_replace("/([^0-9\\.])/i", "", $amount);
278
279 // We need to pass the amount to TrustCommerce in dollar cents
280 $fields['amount'] = $amount * 100;
281
282 // Unique identifier
283 $fields['ticket'] = substr($this->_getParam('invoiceID'), 0, 20);
284
285 // cc info
286 $fields['cc'] = $this->_getParam('credit_card_number');
287 $fields['cvv'] = $this->_getParam('cvv2');
288 $exp_month = str_pad($this->_getParam('month'), 2, '0', STR_PAD_LEFT);
289 $exp_year = substr($this->_getParam('year'),-2);
290 $fields['exp'] = "$exp_month$exp_year";
291
292 if ($this->_mode != 'live') {
293 $fields['demo'] = 'y';
294 }
71a6ba5c
LMM
295 return $fields;
296 }
297
298 /**
299 * Checks to see if invoice_id already exists in db
300 *
301 * @param int $invoiceId The ID to check
302 *
303 * @return bool True if ID exists, else false
304 */
305 function _checkDupe($invoiceId) {
306 require_once 'CRM/Contribute/DAO/Contribution.php';
307 $contribution = new CRM_Contribute_DAO_Contribution();
308 $contribution->invoice_id = $invoiceId;
309 return $contribution->find();
310 }
311
312 /**
313 * Get the value of a field if set
314 *
315 * @param string $field the field
316 *
317 * @return mixed value of the field, or empty string if the field is
318 * not set
319 */
320 function _getParam($field) {
321 return CRM_Utils_Array::value($field, $this->_params, '');
322 }
323
324 function &error($errorCode = NULL, $errorMessage = NULL) {
325 $e = CRM_Core_Error::singleton();
326 if ($errorCode) {
327 $e->push($errorCode, 0, NULL, $errorMessage);
328 }
329 else {
330 $e->push(9001, 0, NULL, 'Unknown System Error.');
331 }
332 return $e;
333 }
334
335 /**
336 * Set a field to the specified value. Value must be a scalar (int,
337 * float, string, or boolean)
338 *
339 * @param string $field
340 * @param mixed $value
341 *
342 * @return bool false if value is not a scalar, true if successful
343 */
344 function _setParam($field, $value) {
345 if (!is_scalar($value)) {
346 return FALSE;
347 }
348 else {
349 $this->_params[$field] = $value;
350 }
351 }
352
353 /**
354 * This function checks to see if we have the right config values
355 *
356 * @return string the error message if any
357 * @public
358 */
359 function checkConfig() {
360 $error = array();
361 if (empty($this->_paymentProcessor['user_name'])) {
362 $error[] = ts('Customer ID is not set for this payment processor');
363 }
364
365 if (empty($this->_paymentProcessor['password'])) {
366 $error[] = ts('Password is not set for this payment processor');
367 }
368
369 if (!empty($error)) {
370 return implode('<p>', $error);
371 } else {
372 return NULL;
373 }
374 }
375
376 function cancelSubscriptionURL($entityID = NULL, $entity = NULL) {
377 if ($entityID && $entity == 'membership') {
378 require_once 'CRM/Contact/BAO/Contact/Utils.php';
379 $contactID = CRM_Core_DAO::getFieldValue("CRM_Member_DAO_Membership", $entityID, "contact_id");
380 $checksumValue = CRM_Contact_BAO_Contact_Utils::generateChecksum($contactID, NULL, 'inf');
381
382 return CRM_Utils_System::url('civicrm/contribute/unsubscribe',
383 "reset=1&mid={$entityID}&cs={$checksumValue}", TRUE, NULL, FALSE, FALSE
384 );
385 }
386
387 return ($this->_mode == 'test') ? 'https://test.authorize.net' : 'https://authorize.net';
388 }
389
390 function cancelSubscription() {
391 $template = CRM_Core_Smarty::singleton();
392
393 $template->assign('subscriptionType', 'cancel');
394
395 $template->assign('apiLogin', $this->_getParam('apiLogin'));
396 $template->assign('paymentKey', $this->_getParam('paymentKey'));
397 $template->assign('subscriptionId', $this->_getParam('subscriptionId'));
398
399 $arbXML = $template->fetch('CRM/Contribute/Form/Contribution/AuthorizeNetARB.tpl');
400
401 // submit to authorize.net
402 $submit = curl_init($this->_paymentProcessor['url_recur']);
403 if (!$submit) {
404 return self::error(9002, 'Could not initiate connection to payment gateway');
405 }
406
407 curl_setopt($submit, CURLOPT_RETURNTRANSFER, 1);
408 curl_setopt($submit, CURLOPT_HTTPHEADER, array("Content-Type: text/xml"));
409 curl_setopt($submit, CURLOPT_HEADER, 1);
410 curl_setopt($submit, CURLOPT_POSTFIELDS, $arbXML);
411 curl_setopt($submit, CURLOPT_POST, 1);
412 curl_setopt($submit, CURLOPT_SSL_VERIFYPEER, 0);
413
414 $response = curl_exec($submit);
415
416 if (!$response) {
417 return self::error(curl_errno($submit), curl_error($submit));
418 }
419
420 curl_close($submit);
421
422 $responseFields = $this->_ParseArbReturn($response);
423
424 if ($responseFields['resultCode'] == 'Error') {
425 return self::error($responseFields['code'], $responseFields['text']);
426 }
427
428 // carry on cancelation procedure
429 return TRUE;
430 }
431
432 public function install() {
433 return TRUE;
434 }
435
436 public function uninstall() {
437 return TRUE;
438 }
439
440}