INFRA-132 - Docblock formatting fixes
[civicrm-core.git] / CRM / Core / Payment / IATS.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the Affero General Public License Version 1, |
12 | March 2002. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @author Alan Dixon
32 * @copyright CiviCRM LLC (c) 2004-2014
33 * $Id$
34 *
35 */
36 class CRM_Core_Payment_IATS extends CRM_Core_Payment {
37 # (not used, implicit in the API, might need to convert?)
38 const CHARSET = 'UFT-8';
39 /* check IATS website for additional supported currencies */
40 const CURRENCIES = 'CAD,USD,AUD,GBP,EUR,NZD';
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
55 * The mode of operation: live or test.
56 *
57 * @param $paymentProcessor
58 *
59 * @return \CRM_Core_Payment_IATS
60 */
61 public function __construct($mode, &$paymentProcessor) {
62 $this->_paymentProcessor = $paymentProcessor;
63 $this->_processorName = ts('IATS');
64
65 // get merchant data from config
66 $config = CRM_Core_Config::singleton();
67 // live or test
68 $this->_profile['mode'] = $mode;
69 $this->_profile['webserver'] = parse_url($this->_paymentProcessor['url_site'], PHP_URL_HOST);
70 $currencyID = $config->defaultCurrency;
71
72 if (!in_array($currencyID, explode(',', self::CURRENCIES))) {
73 // Configuration error: default currency must be in CURRENCIES const
74 return self::error('Invalid configuration:' . $currencyID . ', you must use one of ' . self::CURRENCIES . ' with IATS');
75 }
76 }
77
78 /**
79 * This function collects all the information from a web/api form and invokes
80 * the relevant payment processor specific functions to perform the transaction
81 *
82 * @param array $params
83 * Assoc array of input parameters for this transaction.
84 *
85 * @return array
86 * the result in an nice formatted array (or an error object)
87 * @abstract
88 */
89 public function doDirectPayment(&$params) {
90 // $result = '';
91 // foreach($params as $key => $value) {
92 // $result .= "<strong>$key</strong>: $value<br />";
93 // }
94 // return self::error($result);
95 // make sure i've been called correctly ...
96
97 if (!$this->_profile) {
98 return self::error('Unexpected error, missing profile');
99 }
100 if (!in_array($params['currencyID'], explode(',', self::CURRENCIES))) {
101 return self::error('Invalid currency selection, must be one of ' . self::CURRENCIES);
102 }
103 $isRecur = CRM_Utils_Array::value('is_recur', $params, FALSE);
104 // AgentCode = $this->_paymentProcessor['signature'];
105 // Password = $this->_paymentProcessor['password' ];
106 // beginning of modified sample code from IATS php api include IATS supplied api library
107
108 if ($isRecur) {
109 include_once 'Services/IATS/iats_reoccur.php';
110 $iatslink1 = new iatslinkReoccur;
111 }
112 else {
113 include_once 'Services/IATS/iatslink.php';
114 $iatslink1 = new iatslink;
115 }
116
117 $iatslink1->setTestMode($this->_profile['mode'] != 'live');
118 $iatslink1->setWebServer($this->_profile['webserver']);
119
120 // return self::error($this->_profile['webserver']);
121
122 // Put your invoice here
123 $iatslink1->setInvoiceNumber($params['invoiceID']);
124
125 // $iatslink1->setCardType("VISA");
126 // If CardType is not set, iatslink will find the cardType
127 // CardType not set because IATS uses different names!
128 // $iatslink1->setCardType($params['credit_card_type']);
129
130 $iatslink1->setCardNumber($params['credit_card_number']);
131 $expiry_string = sprintf('%02d/%02d', $params['month'], ($params['year'] % 100));
132 $iatslink1->setCardExpiry($expiry_string);
133 $amount = sprintf('%01.2f', $params['amount']);
134 // sell
135 $iatslink1->setDollarAmount($amount);
136 // refund
137 //$iatslink1->setDollarAmount(-1.15);
138
139 $AgentCode = $this->_paymentProcessor['signature'];
140 $Password = $this->_paymentProcessor['password'];
141 $iatslink1->setAgentCode($AgentCode);
142 $iatslink1->setPassword($Password);
143 // send IATS my invoiceID to match things up later
144 $iatslink1->setInvoiceNumber($params['invoiceID']);
145
146 // Set billing fields
147 $iatslink1->setFirstName($params['billing_first_name']);
148 $iatslink1->setLastName($params['billing_last_name']);
149 $iatslink1->setStreetAddress($params['street_address']);
150 $iatslink1->setCity($params['city']);
151 $iatslink1->setState($params['state_province']);
152 $iatslink1->setZipCode($params['postal_code']);
153 // and now go! ... uses curl to post and retrieve values
154 // after various data integrity tests
155 // simple version
156 if (!$isRecur) {
157 // cvv2 only seems to get set for this!
158 $iatslink1->setCVV2($params['cvv2']);
159
160 // Allow further manipulation of the arguments via custom hooks,
161 // before initiating processCreditCard()
162 CRM_Utils_Hook::alterPaymentProcessorParams($this, $params, $iatslink1);
163
164 $iatslink1->processCreditCard();
165 // extra fields for recurring donations
166 }
167 else {
168 // implicit - test?: 1 == $params['frequency_interval'];
169 $scheduleType = NULL;
170 if ($params['installments']) {
171 $paymentsRecur = $params['installments'] - 1;
172 }
173 // handle unspecified installments by setting to 10 years, IATS doesn't allow indefinitely recurring contributions
174 else {
175 switch ($params['frequency_unit']) {
176 case 'week':
177 $paymentsRecur = 520;
178 case 'month':
179 $paymentsRecur = 120;
180 }
181 }
182 // IATS requires end date, calculated here
183
184 // to be converted to date format later
185 $startTime = time();
186 $date = getdate($startTime);
187
188 switch ($params['frequency_unit']) {
189 case 'week':
190 $scheduleType = 'WEEKLY';
191 $scheduleDate = $date['wday'] + 1;
192 $endTime = $startTime + ($paymentsRecur * 7 * 24 * 60 * 60);
193 break;
194
195 case 'month':
196 $scheduleType = 'MONTHLY';
197 $scheduleDate = $date['mday'];
198 $date['mon'] += $paymentsRecur;
199 while ($date['mon'] > 12) {
200 $date['mon'] -= 12;
201 $date['year'] += 1;
202 }
203 $endTime = mktime($date['hours'], $date['minutes'], $date['seconds'], $date['mon'], $date['mday'], $date['year']);
204 break;
205
206 default:
207 die('Invalid frequency unit!');
208 break;
209 }
210 $endDate = date('Y-m-d', $endTime);
211 $startDate = date('Y-m-d', $startTime);
212 $iatslink1->setReoccuringStatus("ON");
213 $iatslink1->setBeginDate($startDate);
214 $iatslink1->setEndDate($endDate);
215 $iatslink1->setScheduleType($scheduleType);
216 $iatslink1->setScheduleDate($scheduleDate);
217
218 // Allow further manipulation of the arguments via custom hooks,
219 // before initiating the curl process
220 CRM_Utils_Hook::alterPaymentProcessorParams($this, $params, $iatslink1);
221
222 // this next line is the reoccc equiv of processCreditCard
223 $iatslink1->createReoccCustomer();
224 }
225
226 if ($iatslink1->getStatus() == 1) {
227 // this just means we got some kind of answer, not necessarily approved
228 $result = $iatslink1->getAuthorizationResult();
229 //return self::error($result);
230 $result = explode(':', $result, 2);
231 $trxn_result = trim($result[0]);
232 $trxn_id = trim($result[1]);
233 if ($trxn_result == 'OK') {
234 $params['trxn_id'] = $trxn_id . ':' . time();
235 $params['gross_amount'] = $amount;
236 return $params;
237 }
238 // createReoccCustomer() may return other, valid result codes...
239 elseif (preg_match('/A\d+/', $trxn_result)) {
240 $params['trxn_id'] = $trxn_result;
241 $params['gross_amount'] = $amount;
242 return $params;
243 }
244 else {
245 return self::error($trxn_id);
246 }
247 }
248 else {
249 return self::error($iatslink1->getError());
250 }
251 }
252
253 /**
254 * @param null $error
255 *
256 * @return object
257 */
258 public function &error($error = NULL) {
259 $e = CRM_Core_Error::singleton();
260 if (is_object($error)) {
261 $e->push($error->getResponseCode(),
262 0, NULL,
263 $error->getMessage()
264 );
265 }
266 elseif ($error && is_numeric($error)) {
267 $e->push($error,
268 0, NULL,
269 $this->errorString($error)
270 );
271 }
272 elseif (is_string($error)) {
273 $e->push(9002,
274 0, NULL,
275 $error
276 );
277 }
278 else {
279 $e->push(9001, 0, NULL, "Unknown System Error.");
280 }
281 return $e;
282 }
283
284 /**
285 * @param int $error_id
286 *
287 * @return string
288 */
289 public function errorString($error_id) {
290 $errors = array(
291 1 => 'Agent Code has not been set up on the authorization system.',
292 2 => 'Unable to process transaction. Verify and re-enter credit card information.',
293 3 => 'Charge card expired.',
294 4 => 'Incorrect expiration date.',
295 5 => 'Invalid transaction. Verify and re-enter credit card information.',
296 6 => 'Transaction not supported by institution.',
297 7 => 'Lost or stolen card.',
298 8 => 'Invalid card status.',
299 9 => 'Restricted card status. Usually on corporate cards restricted to specific sales.',
300 10 => 'Error. Please verify and re-enter credit card information.',
301 11 => 'General decline code, may have different reasons for each card type. Please have your client call customer service.',
302 14 => 'This means that the credit card is over the limit.',
303 15 => 'Decline code, may have different reasons for each card type. Please have your client call customer service.',
304 16 => 'Invalid charge card number. Verify and re-enter credit card information.',
305 17 => 'Unable to authorize transaction. Verify card information with customer and re-enter. Could be invalid name or expiry date.',
306 18 => 'Card not supported by institution.',
307 19 => 'Incorrect CVV2.',
308 22 => 'Bank Timeout. Bank lines may be down or busy. Re-try transaction later.',
309 23 => 'System error. Re-try transaction later.',
310 24 => 'Charge card expired.',
311 25 => 'Capture card. Reported lost or stolen.',
312 27 => 'System error, please re-enter transaction.',
313 29 => 'Rejected by Ticketmaster.',
314 31 => 'Manual reject code ',
315 39 => 'Contact Ticketmaster 1-888-955-5455 ',
316 40 => 'Card not supported by Ticketmaster. Invalid cc number.',
317 41 => 'Invalid Expiry date ',
318 100 => 'Authorization system down. DO NOT REPROCESS.',
319 );
320 return ' <strong>' . $errors[(integer) $error_id] . '</strong>';
321 }
322
323 /**
324 * This function checks to see if we have the right config values
325 *
326 * @internal param string $mode the mode we are operating in (live or test)
327 *
328 * @return string
329 * the error message if any
330 */
331 public function checkConfig() {
332 $error = array();
333
334 if (empty($this->_paymentProcessor['signature'])) {
335 $error[] = ts('Agent Code is not set in the Administer CiviCRM &raquo; System Settings &raquo; Payment Processors.');
336 }
337
338 if (empty($this->_paymentProcessor['password'])) {
339 $error[] = ts('Password is not set in the Administer CiviCRM &raquo; System Settings &raquo; Payment Processors.');
340 }
341
342 if (!empty($error)) {
343 return implode('<p>', $error);
344 }
345 else {
346 return NULL;
347 }
348 }
349 }