INFRA-132 - Put "else" and "catch" on new line
[civicrm-core.git] / CRM / Core / Payment / eWAY.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | This file is a part of CiviCRM. |
7 | |
8 | CiviCRM is free software; you can copy, modify, and distribute it |
9 | under the terms of the GNU Affero General Public License |
10 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
11 | |
12 | CiviCRM is distributed in the hope that it will be useful, but |
13 | WITHOUT ANY WARRANTY; without even the implied warranty of |
14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
15 | See the GNU Affero General Public License for more details. |
16 | |
17 | You should have received a copy of the GNU Affero General Public |
18 | License and the CiviCRM Licensing Exception along |
19 | with this program; if not, contact CiviCRM LLC |
20 | at info[AT]civicrm[DOT]org. If you have questions about the |
21 | GNU Affero General Public License or the licensing of CiviCRM, |
22 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
23 +--------------------------------------------------------------------+
24 */
25
26
27 /*
28 +--------------------------------------------------------------------+
29 | eWAY Core Payment Module for CiviCRM version 4.6 & 1.9 |
30 +--------------------------------------------------------------------+
31 | Licensed to CiviCRM under the Academic Free License version 3.0 |
32 | |
33 | Written & Contributed by Dolphin Software P/L - March 2008 |
34 +--------------------------------------------------------------------+
35 | |
36 | This file is a part of CiviCRM. |
37 | |
38 | This code was initially based on the recent PayJunction module |
39 | contributed by Phase2 Technology, and then plundered bits from |
40 | the AuthorizeNet module contributed by Ideal Solution, and |
41 | referenced the eWAY code in Drupal 5.7's ecommerce-5.x-3.4 and |
42 | ecommerce-5.x-4.x-dev modules. |
43 | |
44 | Plus a bit of our own code of course - Peter Barwell |
45 | contact PB@DolphinSoftware.com.au if required. |
46 | |
47 | NOTE: This initial eWAY module does not yet allow for recuring |
48 | payments - contact Peter Barwell or add yourself (or both) |
49 | |
50 | NOTE: The eWAY gateway only allows a single currency per account |
51 | (per eWAY CustomerID) ie you can only have one currency per |
52 | added Payment Processor. |
53 | The only way to add multi-currency is to code it so that a |
54 | different CustomerID is used per currency. |
55 | |
56 +--------------------------------------------------------------------+
57 */
58
59 /**
60 -----------------------------------------------------------------------------------------------
61 From the eWAY supplied 'Web.config' dated 25-Sep-2006 - check date and update links if required
62 -----------------------------------------------------------------------------------------------
63
64 LIVE gateway with CVN
65 https://www.eway.com.au/gateway_cvn/xmlpayment.asp
66
67 LIVE gateway without CVN
68 https://www.eway.com.au/gateway/xmlpayment.asp
69
70
71 Test gateway with CVN
72 https://www.eway.com.au/gateway_cvn/xmltest/TestPage.asp
73
74 Test gateway without CVN
75 https://www.eway.com.au/gateway/xmltest/TestPage.asp
76
77
78 LIVE gateway for Stored Transactions
79 https://www.eway.com.au/gateway/xmlstored.asp
80
81
82 -----------------------------------------------------------------------------------------------
83 From the eWAY web-site - http://www.eway.com.au/Support/Developer/PaymentsRealTime.aspx
84 -----------------------------------------------------------------------------------------------
85 The test Customer ID is 87654321 - this is the only ID that will work on the test gateway.
86 The test Credit Card number is 4444333322221111
87 - this is the only credit card number that will work on the test gateway.
88 The test Total Amount should end in 00 or 08 to get a successful response (e.g. $10.00 or $10.08)
89 ie - all other amounts will return a failed response.
90
91 -----------------------------------------------------------------------------------------------
92 **/
93 class CRM_Core_Payment_eWAY extends CRM_Core_Payment {
94 # (not used, implicit in the API, might need to convert?)
95 const CHARSET = 'UTF-8';
96
97 /**
98 * We only need one instance of this object. So we use the singleton
99 * pattern and cache the instance in this variable
100 *
101 * @var object
102 * @static
103 */
104 static private $_singleton = NULL;
105
106 /**********************************************************
107 * Constructor
108 *
109 * @param string $mode
110 * The mode of operation: live or test.
111 *
112 * @param $paymentProcessor
113 *
114 * @return \CRM_Core_Payment_eWAY *******************************************************
115 */
116 public function __construct($mode, &$paymentProcessor) {
117 // require Standard eWAY API libraries
118 require_once 'eWAY/eWAY_GatewayRequest.php';
119 require_once 'eWAY/eWAY_GatewayResponse.php';
120
121 // live or test
122 $this->_mode = $mode;
123 $this->_paymentProcessor = $paymentProcessor;
124 $this->_processorName = ts('eWay');
125 }
126
127 /**
128 * Singleton function used to manage this object
129 *
130 * @param string $mode
131 * The mode of operation: live or test.
132 *
133 * @param object $paymentProcessor
134 * @param null $paymentForm
135 * @param bool $force
136 *
137 * @return object
138 * @static
139 */
140 public static function &singleton($mode, &$paymentProcessor, &$paymentForm = NULL, $force = FALSE) {
141 if (!empty($paymentProcessor['id'])) {
142 $cacheKey = $paymentProcessor['id'];
143 }
144 else {
145 //@todo eliminated instances of this in favour of id-specific instances.
146 $cacheKey = $mode . '_' . $paymentProcessor['name'];
147 }
148
149 if (self::$_singleton[$cacheKey] === NULL) {
150 self::$_singleton[$cacheKey] = new CRM_Core_Payment_eWAY($mode, $paymentProcessor);
151 }
152 return self::$_singleton[$cacheKey];
153 }
154
155 /**********************************************************
156 * This function sends request and receives response from
157 * eWAY payment process
158 **********************************************************/
159 public function doDirectPayment(&$params) {
160 if (CRM_Utils_Array::value('is_recur', $params) == TRUE) {
161 CRM_Core_Error::fatal(ts('eWAY - recurring payments not implemented'));
162 }
163
164 if (!defined('CURLOPT_SSLCERT')) {
165 CRM_Core_Error::fatal(ts('eWAY - Gateway requires curl with SSL support'));
166 }
167
168 // eWAY Client ID
169 $ewayCustomerID = $this->_paymentProcessor['user_name'];
170 // eWAY Gateway URL
171 $gateway_URL = $this->_paymentProcessor['url_site'];
172
173 //------------------------------------
174 // create eWAY gateway objects
175 //------------------------------------
176 $eWAYRequest = new GatewayRequest;
177
178 if (($eWAYRequest == NULL) || (!($eWAYRequest instanceof GatewayRequest))) {
179 return self::errorExit(9001, "Error: Unable to create eWAY Request object.");
180 }
181
182 $eWAYResponse = new GatewayResponse;
183
184 if (($eWAYResponse == NULL) || (!($eWAYResponse instanceof GatewayResponse))) {
185 return self::errorExit(9002, "Error: Unable to create eWAY Response object.");
186 }
187
188 /*
189 //-------------------------------------------------------------
190 // NOTE: eWAY Doesn't use the following at the moment:
191 //-------------------------------------------------------------
192 $creditCardType = $params['credit_card_type'];
193 $currentcyID = $params['currencyID'];
194 $country = $params['country'];
195 */
196
197 //-------------------------------------------------------------
198 // Prepare some composite data from _paymentProcessor fields
199 //-------------------------------------------------------------
200 $fullAddress = $params['street_address'] . ", " . $params['city'] . ", " . $params['state_province'] . ".";
201 $expireYear = substr($params['year'], 2, 2);
202 $expireMonth = sprintf('%02d', (int) $params['month']);
203 // CiviCRM V1.9 - Picks up reasonable description
204 //$description = $params['amount_level'];
205 // CiviCRM V2.0 - Picks up description
206 $description = $params['description'];
207 $txtOptions = "";
208
209 $amountInCents = round(((float) $params['amount']) * 100);
210
211 $credit_card_name = $params['first_name'] . " ";
212 if (strlen($params['middle_name']) > 0) {
213 $credit_card_name .= $params['middle_name'] . " ";
214 }
215 $credit_card_name .= $params['last_name'];
216
217 //----------------------------------------------------------------------------------------------------
218 // We use CiviCRM's param's 'invoiceID' as the unique transaction token to feed to eWAY
219 // Trouble is that eWAY only accepts 16 chars for the token, while CiviCRM's invoiceID is an 32.
220 // As its made from a "$invoiceID = md5(uniqid(rand(), true));" then using the fierst 16 chars
221 // should be alright
222 //----------------------------------------------------------------------------------------------------
223 $uniqueTrnxNum = substr($params['invoiceID'], 0, 16);
224
225 //----------------------------------------------------------------------------------------------------
226 // OPTIONAL: If TEST Card Number force an Override of URL and CutomerID.
227 // During testing CiviCRM once used the LIVE URL.
228 // This code can be uncommented to override the LIVE URL that if CiviCRM does that again.
229 //----------------------------------------------------------------------------------------------------
230 // if ( ( $gateway_URL == "https://www.eway.com.au/gateway_cvn/xmlpayment.asp")
231 // && ( $params['credit_card_number'] == "4444333322221111" ) ) {
232 // $ewayCustomerID = "87654321";
233 // $gateway_URL = "https://www.eway.com.au/gateway_cvn/xmltest/testpage.asp";
234 // }
235
236 //----------------------------------------------------------------------------------------------------
237 // Now set the payment details - see http://www.eway.com.au/Support/Developer/PaymentsRealTime.aspx
238 //----------------------------------------------------------------------------------------------------
239 // 8 Chars - ewayCustomerID - Required
240 $eWAYRequest->EwayCustomerID($ewayCustomerID);
241 // 12 Chars - ewayTotalAmount (in cents) - Required
242 $eWAYRequest->InvoiceAmount($amountInCents);
243 // 50 Chars - ewayCustomerFirstName
244 $eWAYRequest->PurchaserFirstName($params['first_name']);
245 // 50 Chars - ewayCustomerLastName
246 $eWAYRequest->PurchaserLastName($params['last_name']);
247 // 50 Chars - ewayCustomerEmail
248 $eWAYRequest->PurchaserEmailAddress($params['email']);
249 // 255 Chars - ewayCustomerAddress
250 $eWAYRequest->PurchaserAddress($fullAddress);
251 // 6 Chars - ewayCustomerPostcode
252 $eWAYRequest->PurchaserPostalCode($params['postal_code']);
253 // 1000 Chars - ewayCustomerInvoiceDescription
254 $eWAYRequest->InvoiceDescription($description);
255 // 50 Chars - ewayCustomerInvoiceRef
256 $eWAYRequest->InvoiceReference($params['invoiceID']);
257 // 50 Chars - ewayCardHoldersName - Required
258 $eWAYRequest->CardHolderName($credit_card_name);
259 // 20 Chars - ewayCardNumber - Required
260 $eWAYRequest->CardNumber($params['credit_card_number']);
261 // 2 Chars - ewayCardExpiryMonth - Required
262 $eWAYRequest->CardExpiryMonth($expireMonth);
263 // 2 Chars - ewayCardExpiryYear - Required
264 $eWAYRequest->CardExpiryYear($expireYear);
265 // 4 Chars - ewayCVN - Required if CVN Gateway used
266 $eWAYRequest->CVN($params['cvv2']);
267 // 16 Chars - ewayTrxnNumber
268 $eWAYRequest->TransactionNumber($uniqueTrnxNum);
269 // 255 Chars - ewayOption1
270 $eWAYRequest->EwayOption1($txtOptions);
271 // 255 Chars - ewayOption2
272 $eWAYRequest->EwayOption2($txtOptions);
273 // 255 Chars - ewayOption3
274 $eWAYRequest->EwayOption3($txtOptions);
275
276 $eWAYRequest->CustomerIPAddress($params['ip_address']);
277 $eWAYRequest->CustomerBillingCountry($params['country']);
278
279 // Allow further manipulation of the arguments via custom hooks ..
280 CRM_Utils_Hook::alterPaymentProcessorParams($this, $params, $eWAYRequest);
281
282 //----------------------------------------------------------------------------------------------------
283 // Check to see if we have a duplicate before we send
284 //----------------------------------------------------------------------------------------------------
285 if ($this->_checkDupe($params['invoiceID'])) {
286 return self::errorExit(9003, 'It appears that this transaction is a duplicate. Have you already submitted the form once? If so there may have been a connection problem. Check your email for a receipt from eWAY. If you do not receive a receipt within 2 hours you can try your transaction again. If you continue to have problems please contact the site administrator.');
287 }
288
289 //----------------------------------------------------------------------------------------------------
290 // Convert to XML and send the payment information
291 //----------------------------------------------------------------------------------------------------
292 $requestxml = $eWAYRequest->ToXML();
293
294 $submit = curl_init($gateway_URL);
295
296 if (!$submit) {
297 return self::errorExit(9004, 'Could not initiate connection to payment gateway');
298 }
299
300 curl_setopt($submit, CURLOPT_POST, TRUE);
301 // return the result on success, FALSE on failure
302 curl_setopt($submit, CURLOPT_RETURNTRANSFER, TRUE);
303 curl_setopt($submit, CURLOPT_POSTFIELDS, $requestxml);
304 curl_setopt($submit, CURLOPT_TIMEOUT, 36000);
305 // if open_basedir or safe_mode are enabled in PHP settings CURLOPT_FOLLOWLOCATION won't work so don't apply it
306 // it's not really required CRM-5841
307 if (ini_get('open_basedir') == '' && ini_get('safe_mode' == 'Off')) {
308 // ensures any Location headers are followed
309 curl_setopt($submit, CURLOPT_FOLLOWLOCATION, 1);
310 }
311
312 // Send the data out over the wire
313 //--------------------------------
314 $responseData = curl_exec($submit);
315
316 //----------------------------------------------------------------------------------------------------
317 // See if we had a curl error - if so tell 'em and bail out
318 //
319 // NOTE: curl_error does not return a logical value (see its documentation), but
320 // a string, which is empty when there was no error.
321 //----------------------------------------------------------------------------------------------------
322 if ((curl_errno($submit) > 0) || (strlen(curl_error($submit)) > 0)) {
323 $errorNum = curl_errno($submit);
324 $errorDesc = curl_error($submit);
325
326 // Paranoia - in the unlikley event that 'curl' errno fails
327 if ($errorNum == 0) {
328 $errorNum = 9005;
329 }
330
331 // Paranoia - in the unlikley event that 'curl' error fails
332 if (strlen($errorDesc) == 0) {
333 $errorDesc = "Connection to eWAY payment gateway failed";
334 }
335
336 return self::errorExit($errorNum, $errorDesc);
337 }
338
339 //----------------------------------------------------------------------------------------------------
340 // If null data returned - tell 'em and bail out
341 //
342 // NOTE: You will not necessarily get a string back, if the request failed for
343 // any reason, the return value will be the boolean false.
344 //----------------------------------------------------------------------------------------------------
345 if (($responseData === FALSE) || (strlen($responseData) == 0)) {
346 return self::errorExit(9006, "Error: Connection to payment gateway failed - no data returned.");
347 }
348
349 //----------------------------------------------------------------------------------------------------
350 // If gateway returned no data - tell 'em and bail out
351 //----------------------------------------------------------------------------------------------------
352 if (empty($responseData)) {
353 return self::errorExit(9007, "Error: No data returned from payment gateway.");
354 }
355
356 //----------------------------------------------------------------------------------------------------
357 // Success so far - close the curl and check the data
358 //----------------------------------------------------------------------------------------------------
359 curl_close($submit);
360
361 //----------------------------------------------------------------------------------------------------
362 // Payment successfully sent to gateway - process the response now
363 //----------------------------------------------------------------------------------------------------
364 $eWAYResponse->ProcessResponse($responseData);
365
366 //----------------------------------------------------------------------------------------------------
367 // See if we got an OK result - if not tell 'em and bail out
368 //----------------------------------------------------------------------------------------------------
369 if (self::isError($eWAYResponse)) {
370 $eWayTrxnError = $eWAYResponse->Error();
371 CRM_Core_Error::debug_var('eWay Error', $eWayTrxnError, TRUE, TRUE);
372 if (substr($eWayTrxnError, 0, 6) == "Error:") {
373 return self::errorExit(9008, $eWayTrxnError);
374 }
375 $eWayErrorCode = substr($eWayTrxnError, 0, 2);
376 $eWayErrorDesc = substr($eWayTrxnError, 3);
377
378 return self::errorExit(9008, "Error: [" . $eWayErrorCode . "] - " . $eWayErrorDesc . ".");
379 }
380
381 //-----------------------------------------------------------------------------------------------------
382 // Cross-Check - the unique 'TrxnReference' we sent out should match the just received 'TrxnReference'
383 //
384 // PLEASE NOTE: If this occurs (which is highly unlikely) its a serious error as it would mean we have
385 // received an OK status from eWAY, but their Gateway has not returned the correct unique
386 // token - ie something is broken, BUT money has been taken from the client's account,
387 // so we can't very well error-out as CiviCRM will then not process the registration.
388 // There is an error message commented out here but my prefered response to this unlikley
389 // possibility is to email 'support@eWAY.com.au'
390 //-----------------------------------------------------------------------------------------------------
391 $eWayTrxnReference_OUT = $eWAYRequest->GetTransactionNumber();
392 $eWayTrxnReference_IN = $eWAYResponse->InvoiceReference();
393
394 if ($eWayTrxnReference_IN != $eWayTrxnReference_OUT) {
395 // return self::errorExit( 9009, "Error: Unique Trxn code was not returned by eWAY Gateway. This is extremely unusual! Please contact the administrator of this site immediately with details of this transaction.");
396
397 self::send_alert_email($eWAYResponse->TransactionNumber(),
398 $eWayTrxnReference_OUT, $eWayTrxnReference_IN, $requestxml, $responseData
399 );
400 }
401
402 /*
403 //----------------------------------------------------------------------------------------------------
404 // Test mode always returns trxn_id = 0 - so we fix that here
405 //
406 // NOTE: This code was taken from the AuthorizeNet payment processor, however it now appears
407 // unecessary for the eWAY gateway - Left here in case it proves useful
408 //----------------------------------------------------------------------------------------------------
409 if ( $this->_mode == 'test' ) {
410 $query = "SELECT MAX(trxn_id) FROM civicrm_contribution WHERE trxn_id LIKE 'test%'";
411 $p = array( );
412 $trxn_id = strval( CRM_Core_Dao::singleValueQuery( $query, $p ) );
413 $trxn_id = str_replace( 'test', '', $trxn_id );
414 $trxn_id = intval($trxn_id) + 1;
415 $params['trxn_id'] = sprintf('test%08d', $trxn_id);
416 }
417 else {
418 $params['trxn_id'] = $eWAYResponse->TransactionNumber();
419 }
420 */
421
422 //=============
423 // Success !
424 //=============
425 $beaglestatus = $eWAYResponse->BeagleScore();
426 if (!empty($beaglestatus)) {
427 $beaglestatus = ": " . $beaglestatus;
428 }
429 $params['trxn_result_code'] = $eWAYResponse->Status() . $beaglestatus;
430 $params['gross_amount'] = $eWAYResponse->Amount();
431 $params['trxn_id'] = $eWAYResponse->TransactionNumber();
432
433 return $params;
434 }
435 // end function doDirectPayment
436
437 /**
438 * Checks to see if invoice_id already exists in db
439 *
440 * @param int $invoiceId
441 * The ID to check.
442 *
443 * @return bool True if ID exists, else false
444 */
445 public function _checkDupe($invoiceId) {
446 $contribution = new CRM_Contribute_DAO_Contribution();
447 $contribution->invoice_id = $invoiceId;
448 return $contribution->find();
449 }
450
451 /*************************************************************************************************
452 * This function checks the eWAY response status - returning a boolean false if status != 'true'
453 *************************************************************************************************/
454 public function isError(&$response) {
455 $status = $response->Status();
456
457 if ((stripos($status, "true")) === FALSE) {
458 return TRUE;
459 }
460 return FALSE;
461 }
462
463 /**************************************************
464 * Produces error message and returns from class
465 **************************************************/
466 public function &errorExit($errorCode = NULL, $errorMessage = NULL) {
467 $e = CRM_Core_Error::singleton();
468
469 if ($errorCode) {
470 $e->push($errorCode, 0, NULL, $errorMessage);
471 }
472 else {
473 $e->push(9000, 0, NULL, 'Unknown System Error.');
474 }
475 return $e;
476 }
477
478 /**************************************************
479 * NOTE: 'doTransferCheckout' not implemented
480 **************************************************/
481 public function doTransferCheckout(&$params, $component) {
482 CRM_Core_Error::fatal(ts('This function is not implemented'));
483 }
484
485 /********************************************************************************************
486 * This public function checks to see if we have the right processor config values set
487 *
488 * NOTE: Called by Events and Contribute to check config params are set prior to trying
489 * register any credit card details
490 *
491 * @return null|string
492 * @internal param string $mode the mode we are operating in (live or test) - not used but could be
493 * to check that the 'test' mode CustomerID was equal to '87654321' and that the URL was
494 * set to https://www.eway.com.au/gateway_cvn/xmltest/TestPage.asp
495 *
496 * returns string $errorMsg if any errors found - null if OK
497 *
498 ******************************************************************************************
499 */
500 //function checkConfig( $mode ) // CiviCRM V1.9 Declaration
501 // CiviCRM V2.0 Declaration
502 public function checkConfig() {
503 $errorMsg = array();
504
505 if (empty($this->_paymentProcessor['user_name'])) {
506 $errorMsg[] = ts('eWAY CustomerID is not set for this payment processor');
507 }
508
509 if (empty($this->_paymentProcessor['url_site'])) {
510 $errorMsg[] = ts('eWAY Gateway URL is not set for this payment processor');
511 }
512
513 if (!empty($errorMsg)) {
514 return implode('<p>', $errorMsg);
515 }
516 else {
517 return NULL;
518 }
519 }
520
521 /**
522 * @param $p_eWAY_tran_num
523 * @param $p_trxn_out
524 * @param $p_trxn_back
525 * @param $p_request
526 * @param $p_response
527 */
528 public function send_alert_email($p_eWAY_tran_num, $p_trxn_out, $p_trxn_back, $p_request, $p_response) {
529 // Initialization call is required to use CiviCRM APIs.
530 civicrm_initialize(TRUE);
531
532 list($fromName, $fromEmail) = CRM_Core_BAO_Domain::getNameAndEmail();
533 $from = "$fromName <$fromEmail>";
534
535 $toName = 'Support at eWAY';
536 $toEmail = 'Support@eWAY.com.au';
537
538 $subject = "ALERT: Unique Trxn Number Failure : eWAY Transaction # = [" . $p_eWAY_tran_num . "]";
539
540 $message = "
541 TRXN sent out with request = '$p_trxn_out'.
542 TRXN sent back with response = '$p_trxn_back'.
543
544 This is a ['$this->_mode'] transaction.
545
546
547 Request XML =
548 ---------------------------------------------------------------------------
549 $p_request
550 ---------------------------------------------------------------------------
551
552
553 Response XML =
554 ---------------------------------------------------------------------------
555 $p_response
556 ---------------------------------------------------------------------------
557
558
559 Regards
560
561 The CiviCRM eWAY Payment Processor Module
562 ";
563 //$cc = 'Name@Domain';
564
565 // create the params array
566 $params = array();
567
568 $params['groupName'] = 'eWay Email Sender';
569 $params['from'] = $from;
570 $params['toName'] = $toName;
571 $params['toEmail'] = $toEmail;
572 $params['subject'] = $subject;
573 $params['cc'] = $cc;
574 $params['text'] = $message;
575
576 CRM_Utils_Mail::send($params);
577 }
578 }
579 // end class CRM_Core_Payment_eWAY