CRM-15771 fix inconsistencies with test vs live instances by making key more complex
[civicrm-core.git] / CRM / Core / Payment / eWAY.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
39de6fd5 4 | CiviCRM version 4.6 |
6a488035
TO
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 +--------------------------------------------------------------------+
39de6fd5 29 | eWAY Core Payment Module for CiviCRM version 4.6 & 1.9 |
6a488035
TO
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 **/
93class CRM_Core_Payment_eWAY extends CRM_Core_Payment {
94 # (not used, implicit in the API, might need to convert?)
7da04cde 95 const CHARSET = 'UTF-8';
6a488035
TO
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 the mode of operation: live or test
110 *
dd244018
EM
111 * @param $paymentProcessor
112 *
113 * @return \CRM_Core_Payment_eWAY *******************************************************
114 */
00be9182 115 public function __construct($mode, &$paymentProcessor) {
52767de0 116 // require Standard eWAY API libraries
6a488035
TO
117 require_once 'eWAY/eWAY_GatewayRequest.php';
118 require_once 'eWAY/eWAY_GatewayResponse.php';
119
120 // live or test
121 $this->_mode = $mode;
122 $this->_paymentProcessor = $paymentProcessor;
123 $this->_processorName = ts('eWay');
124 }
125
126 /**
100fef9d 127 * Singleton function used to manage this object
6a488035
TO
128 *
129 * @param string $mode the mode of operation: live or test
130 *
dd244018
EM
131 * @param object $paymentProcessor
132 * @param null $paymentForm
133 * @param bool $force
134 *
6a488035
TO
135 * @return object
136 * @static
6a488035 137 */
00be9182 138 public static function &singleton($mode, &$paymentProcessor, &$paymentForm = NULL, $force = false) {
52767de0
EM
139 if (!empty($paymentProcessor['id'])) {
140 $cacheKey = $paymentProcessor['id'];
6a488035 141 }
52767de0
EM
142 else {
143 //@todo eliminated instances of this in favour of id-specific instances.
144 $cacheKey = $mode . '_' . $paymentProcessor['name'];
145 }
146
147 if (self::$_singleton[$cacheKey] === NULL) {
148 self::$_singleton[$cacheKey] = new CRM_Core_Payment_eWAY($mode, $paymentProcessor);
149 }
150 return self::$_singleton[$cacheKey];
6a488035
TO
151 }
152
153 /**********************************************************
154 * This function sends request and receives response from
155 * eWAY payment process
156 **********************************************************/
00be9182 157 public function doDirectPayment(&$params) {
d597ad57 158 if (CRM_Utils_Array::value('is_recur', $params) == TRUE) {
6a488035
TO
159 CRM_Core_Error::fatal(ts('eWAY - recurring payments not implemented'));
160 }
161
162 if (!defined('CURLOPT_SSLCERT')) {
163 CRM_Core_Error::fatal(ts('eWAY - Gateway requires curl with SSL support'));
164 }
165
166 // eWAY Client ID
167 $ewayCustomerID = $this->_paymentProcessor['user_name'];
168 // eWAY Gateway URL
169 $gateway_URL = $this->_paymentProcessor['url_site'];
170
171 //------------------------------------
172 // create eWAY gateway objects
173 //------------------------------------
174 $eWAYRequest = new GatewayRequest;
175
176 if (($eWAYRequest == NULL) || (!($eWAYRequest instanceof GatewayRequest))) {
177 return self::errorExit(9001, "Error: Unable to create eWAY Request object.");
178 }
179
180 $eWAYResponse = new GatewayResponse;
181
182 if (($eWAYResponse == NULL) || (!($eWAYResponse instanceof GatewayResponse))) {
183 return self::errorExit(9002, "Error: Unable to create eWAY Response object.");
184 }
185
186 /*
187 //-------------------------------------------------------------
188 // NOTE: eWAY Doesn't use the following at the moment:
189 //-------------------------------------------------------------
190 $creditCardType = $params['credit_card_type'];
191 $currentcyID = $params['currencyID'];
192 $country = $params['country'];
193 */
194
195
196 //-------------------------------------------------------------
197 // Prepare some composite data from _paymentProcessor fields
198 //-------------------------------------------------------------
199 $fullAddress = $params['street_address'] . ", " . $params['city'] . ", " . $params['state_province'] . ".";
200 $expireYear = substr($params['year'], 2, 2);
201 $expireMonth = sprintf('%02d', (int) $params['month']);
202 // CiviCRM V1.9 - Picks up reasonable description
203 //$description = $params['amount_level'];
204 // CiviCRM V2.0 - Picks up description
205 $description = $params['description'];
206 $txtOptions = "";
207
208 $amountInCents = round(((float) $params['amount']) * 100);
209
210 $credit_card_name = $params['first_name'] . " ";
211 if (strlen($params['middle_name']) > 0) {
212 $credit_card_name .= $params['middle_name'] . " ";
213 }
214 $credit_card_name .= $params['last_name'];
215
216 //----------------------------------------------------------------------------------------------------
217 // We use CiviCRM's param's 'invoiceID' as the unique transaction token to feed to eWAY
218 // Trouble is that eWAY only accepts 16 chars for the token, while CiviCRM's invoiceID is an 32.
219 // As its made from a "$invoiceID = md5(uniqid(rand(), true));" then using the fierst 16 chars
220 // should be alright
221 //----------------------------------------------------------------------------------------------------
222 $uniqueTrnxNum = substr($params['invoiceID'], 0, 16);
223
224 //----------------------------------------------------------------------------------------------------
225 // OPTIONAL: If TEST Card Number force an Override of URL and CutomerID.
226 // During testing CiviCRM once used the LIVE URL.
227 // This code can be uncommented to override the LIVE URL that if CiviCRM does that again.
228 //----------------------------------------------------------------------------------------------------
229 // if ( ( $gateway_URL == "https://www.eway.com.au/gateway_cvn/xmlpayment.asp")
230 // && ( $params['credit_card_number'] == "4444333322221111" ) ) {
231 // $ewayCustomerID = "87654321";
232 // $gateway_URL = "https://www.eway.com.au/gateway_cvn/xmltest/testpage.asp";
233 // }
234
235 //----------------------------------------------------------------------------------------------------
236 // Now set the payment details - see http://www.eway.com.au/Support/Developer/PaymentsRealTime.aspx
237 //----------------------------------------------------------------------------------------------------
238 // 8 Chars - ewayCustomerID - Required
239 $eWAYRequest->EwayCustomerID($ewayCustomerID);
240 // 12 Chars - ewayTotalAmount (in cents) - Required
241 $eWAYRequest->InvoiceAmount($amountInCents);
242 // 50 Chars - ewayCustomerFirstName
243 $eWAYRequest->PurchaserFirstName($params['first_name']);
244 // 50 Chars - ewayCustomerLastName
245 $eWAYRequest->PurchaserLastName($params['last_name']);
246 // 50 Chars - ewayCustomerEmail
247 $eWAYRequest->PurchaserEmailAddress($params['email']);
248 // 255 Chars - ewayCustomerAddress
249 $eWAYRequest->PurchaserAddress($fullAddress);
250 // 6 Chars - ewayCustomerPostcode
251 $eWAYRequest->PurchaserPostalCode($params['postal_code']);
252 // 1000 Chars - ewayCustomerInvoiceDescription
253 $eWAYRequest->InvoiceDescription($description);
254 // 50 Chars - ewayCustomerInvoiceRef
255 $eWAYRequest->InvoiceReference($params['invoiceID']);
256 // 50 Chars - ewayCardHoldersName - Required
257 $eWAYRequest->CardHolderName($credit_card_name);
258 // 20 Chars - ewayCardNumber - Required
259 $eWAYRequest->CardNumber($params['credit_card_number']);
260 // 2 Chars - ewayCardExpiryMonth - Required
261 $eWAYRequest->CardExpiryMonth($expireMonth);
262 // 2 Chars - ewayCardExpiryYear - Required
263 $eWAYRequest->CardExpiryYear($expireYear);
264 // 4 Chars - ewayCVN - Required if CVN Gateway used
265 $eWAYRequest->CVN($params['cvv2']);
266 // 16 Chars - ewayTrxnNumber
267 $eWAYRequest->TransactionNumber($uniqueTrnxNum);
268 // 255 Chars - ewayOption1
269 $eWAYRequest->EwayOption1($txtOptions);
270 // 255 Chars - ewayOption2
271 $eWAYRequest->EwayOption2($txtOptions);
272 // 255 Chars - ewayOption3
273 $eWAYRequest->EwayOption3($txtOptions);
274
275 $eWAYRequest->CustomerIPAddress($params['ip_address']);
276 $eWAYRequest->CustomerBillingCountry($params['country']);
277
278 // Allow further manipulation of the arguments via custom hooks ..
279 CRM_Utils_Hook::alterPaymentProcessorParams($this, $params, $eWAYRequest);
280
281 //----------------------------------------------------------------------------------------------------
282 // Check to see if we have a duplicate before we send
283 //----------------------------------------------------------------------------------------------------
284 if ($this->_checkDupe($params['invoiceID'])) {
285 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.');
286 }
287
288 //----------------------------------------------------------------------------------------------------
289 // Convert to XML and send the payment information
290 //----------------------------------------------------------------------------------------------------
291 $requestxml = $eWAYRequest->ToXML();
292
293 $submit = curl_init($gateway_URL);
294
295 if (!$submit) {
296 return self::errorExit(9004, 'Could not initiate connection to payment gateway');
297 }
298
299 curl_setopt($submit, CURLOPT_POST, TRUE);
300 // return the result on success, FALSE on failure
301 curl_setopt($submit, CURLOPT_RETURNTRANSFER, TRUE);
302 curl_setopt($submit, CURLOPT_POSTFIELDS, $requestxml);
303 curl_setopt($submit, CURLOPT_TIMEOUT, 36000);
304 // if open_basedir or safe_mode are enabled in PHP settings CURLOPT_FOLLOWLOCATION won't work so don't apply it
305 // it's not really required CRM-5841
306 if (ini_get('open_basedir') == '' && ini_get('safe_mode' == 'Off')) {
307 // ensures any Location headers are followed
308 curl_setopt($submit, CURLOPT_FOLLOWLOCATION, 1);
309 }
310
311 // Send the data out over the wire
312 //--------------------------------
313 $responseData = curl_exec($submit);
314
315 //----------------------------------------------------------------------------------------------------
316 // See if we had a curl error - if so tell 'em and bail out
317 //
318 // NOTE: curl_error does not return a logical value (see its documentation), but
319 // a string, which is empty when there was no error.
320 //----------------------------------------------------------------------------------------------------
321 if ((curl_errno($submit) > 0) || (strlen(curl_error($submit)) > 0)) {
322 $errorNum = curl_errno($submit);
323 $errorDesc = curl_error($submit);
324
325 // Paranoia - in the unlikley event that 'curl' errno fails
326 if ($errorNum == 0)
327 $errorNum = 9005;
328
329 // Paranoia - in the unlikley event that 'curl' error fails
330 if (strlen($errorDesc) == 0)
331 $errorDesc = "Connection to eWAY payment gateway failed";
332
333 return self::errorExit($errorNum, $errorDesc);
334 }
335
336 //----------------------------------------------------------------------------------------------------
337 // If null data returned - tell 'em and bail out
338 //
339 // NOTE: You will not necessarily get a string back, if the request failed for
340 // any reason, the return value will be the boolean false.
341 //----------------------------------------------------------------------------------------------------
342 if (($responseData === FALSE) || (strlen($responseData) == 0)) {
343 return self::errorExit(9006, "Error: Connection to payment gateway failed - no data returned.");
344 }
345
346 //----------------------------------------------------------------------------------------------------
347 // If gateway returned no data - tell 'em and bail out
348 //----------------------------------------------------------------------------------------------------
349 if (empty($responseData)) {
350 return self::errorExit(9007, "Error: No data returned from payment gateway.");
351 }
352
353 //----------------------------------------------------------------------------------------------------
354 // Success so far - close the curl and check the data
355 //----------------------------------------------------------------------------------------------------
356 curl_close($submit);
357
358 //----------------------------------------------------------------------------------------------------
ceb10dc7 359 // Payment successfully sent to gateway - process the response now
6a488035
TO
360 //----------------------------------------------------------------------------------------------------
361 $eWAYResponse->ProcessResponse($responseData);
362
363 //----------------------------------------------------------------------------------------------------
364 // See if we got an OK result - if not tell 'em and bail out
365 //----------------------------------------------------------------------------------------------------
366 if (self::isError($eWAYResponse)) {
367 $eWayTrxnError = $eWAYResponse->Error();
09e49db4 368 CRM_Core_Error::debug_var('eWay Error', $eWayTrxnError, TRUE, TRUE);
6a488035
TO
369 if (substr($eWayTrxnError, 0, 6) == "Error:") {
370 return self::errorExit(9008, $eWayTrxnError);
371 }
372 $eWayErrorCode = substr($eWayTrxnError, 0, 2);
373 $eWayErrorDesc = substr($eWayTrxnError, 3);
374
375 return self::errorExit(9008, "Error: [" . $eWayErrorCode . "] - " . $eWayErrorDesc . ".");
376 }
377
378 //-----------------------------------------------------------------------------------------------------
379 // Cross-Check - the unique 'TrxnReference' we sent out should match the just received 'TrxnReference'
380 //
381 // PLEASE NOTE: If this occurs (which is highly unlikely) its a serious error as it would mean we have
382 // received an OK status from eWAY, but their Gateway has not returned the correct unique
383 // token - ie something is broken, BUT money has been taken from the client's account,
384 // so we can't very well error-out as CiviCRM will then not process the registration.
385 // There is an error message commented out here but my prefered response to this unlikley
386 // possibility is to email 'support@eWAY.com.au'
387 //-----------------------------------------------------------------------------------------------------
388 $eWayTrxnReference_OUT = $eWAYRequest->GetTransactionNumber();
389 $eWayTrxnReference_IN = $eWAYResponse->InvoiceReference();
390
391 if ($eWayTrxnReference_IN != $eWayTrxnReference_OUT) {
392 // 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.");
393
394 self::send_alert_email($eWAYResponse->TransactionNumber(),
395 $eWayTrxnReference_OUT, $eWayTrxnReference_IN, $requestxml, $responseData
396 );
397 }
398
399 /*
400 //----------------------------------------------------------------------------------------------------
401 // Test mode always returns trxn_id = 0 - so we fix that here
402 //
403 // NOTE: This code was taken from the AuthorizeNet payment processor, however it now appears
404 // unecessary for the eWAY gateway - Left here in case it proves useful
405 //----------------------------------------------------------------------------------------------------
406 if ( $this->_mode == 'test' ) {
407 $query = "SELECT MAX(trxn_id) FROM civicrm_contribution WHERE trxn_id LIKE 'test%'";
408 $p = array( );
409 $trxn_id = strval( CRM_Core_Dao::singleValueQuery( $query, $p ) );
410 $trxn_id = str_replace( 'test', '', $trxn_id );
411 $trxn_id = intval($trxn_id) + 1;
412 $params['trxn_id'] = sprintf('test%08d', $trxn_id);
413 } else {
414 $params['trxn_id'] = $eWAYResponse->TransactionNumber();
415 }
416 */
417
418
419 //=============
420 // Success !
421 //=============
422 $beaglestatus = $eWAYResponse->BeagleScore();
423 if (!empty($beaglestatus)) {
424 $beaglestatus = ": " . $beaglestatus;
425 }
426 $params['trxn_result_code'] = $eWAYResponse->Status() . $beaglestatus;
427 $params['gross_amount'] = $eWAYResponse->Amount();
428 $params['trxn_id'] = $eWAYResponse->TransactionNumber();
429
430 return $params;
431 }
432 // end function doDirectPayment
433
434 /**
435 * Checks to see if invoice_id already exists in db
436 *
437 * @param int $invoiceId The ID to check
438 *
439 * @return bool True if ID exists, else false
440 */
00be9182 441 public function _checkDupe($invoiceId) {
6a488035
TO
442 $contribution = new CRM_Contribute_DAO_Contribution();
443 $contribution->invoice_id = $invoiceId;
444 return $contribution->find();
445 }
446
447 /*************************************************************************************************
448 * This function checks the eWAY response status - returning a boolean false if status != 'true'
449 *************************************************************************************************/
00be9182 450 public function isError(&$response) {
6a488035
TO
451 $status = $response->Status();
452
453 if ((stripos($status, "true")) === FALSE) {
454 return TRUE;
455 }
456 return FALSE;
457 }
458
459 /**************************************************
460 * Produces error message and returns from class
461 **************************************************/
00be9182 462 public function &errorExit($errorCode = NULL, $errorMessage = NULL) {
6a488035
TO
463 $e = CRM_Core_Error::singleton();
464
465 if ($errorCode) {
466 $e->push($errorCode, 0, NULL, $errorMessage);
467 }
468 else {
469 $e->push(9000, 0, NULL, 'Unknown System Error.');
470 }
471 return $e;
472 }
473
474 /**************************************************
475 * NOTE: 'doTransferCheckout' not implemented
476 **************************************************/
00be9182 477 public function doTransferCheckout(&$params, $component) {
6a488035
TO
478 CRM_Core_Error::fatal(ts('This function is not implemented'));
479 }
480
481 /********************************************************************************************
482 * This public function checks to see if we have the right processor config values set
483 *
484 * NOTE: Called by Events and Contribute to check config params are set prior to trying
485 * register any credit card details
486 *
77b97be7
EM
487 * @return null|string
488 * @internal param string $mode the mode we are operating in (live or test) - not used but could be
6a488035
TO
489 * to check that the 'test' mode CustomerID was equal to '87654321' and that the URL was
490 * set to https://www.eway.com.au/gateway_cvn/xmltest/TestPage.asp
491 *
492 * returns string $errorMsg if any errors found - null if OK
493 *
77b97be7
EM
494 ******************************************************************************************
495 */
6a488035
TO
496 //function checkConfig( $mode ) // CiviCRM V1.9 Declaration
497 // CiviCRM V2.0 Declaration
00be9182 498 public function checkConfig() {
6a488035
TO
499 $errorMsg = array();
500
501 if (empty($this->_paymentProcessor['user_name'])) {
502 $errorMsg[] = ts('eWAY CustomerID is not set for this payment processor');
503 }
504
505 if (empty($this->_paymentProcessor['url_site'])) {
506 $errorMsg[] = ts('eWAY Gateway URL is not set for this payment processor');
507 }
508
509 if (!empty($errorMsg)) {
510 return implode('<p>', $errorMsg);
511 }
512 else {
513 return NULL;
514 }
515 }
516
6c786a9b
EM
517 /**
518 * @param $p_eWAY_tran_num
519 * @param $p_trxn_out
520 * @param $p_trxn_back
521 * @param $p_request
522 * @param $p_response
523 */
00be9182 524 public function send_alert_email($p_eWAY_tran_num, $p_trxn_out, $p_trxn_back, $p_request, $p_response) {
6a488035
TO
525 // Initialization call is required to use CiviCRM APIs.
526 civicrm_initialize(TRUE);
527
528
529 list($fromName, $fromEmail) = CRM_Core_BAO_Domain::getNameAndEmail();
530 $from = "$fromName <$fromEmail>";
531
532 $toName = 'Support at eWAY';
533 $toEmail = 'Support@eWAY.com.au';
534
535 $subject = "ALERT: Unique Trxn Number Failure : eWAY Transaction # = [" . $p_eWAY_tran_num . "]";
536
537 $message = "
538TRXN sent out with request = '$p_trxn_out'.
539TRXN sent back with response = '$p_trxn_back'.
540
541This is a ['$this->_mode'] transaction.
542
543
544Request XML =
545---------------------------------------------------------------------------
546$p_request
547---------------------------------------------------------------------------
548
549
550Response XML =
551---------------------------------------------------------------------------
552$p_response
553---------------------------------------------------------------------------
554
555
556Regards
557
558The CiviCRM eWAY Payment Processor Module
559";
560 //$cc = 'Name@Domain';
561
562 // create the params array
563 $params = array();
564
565 $params['groupName'] = 'eWay Email Sender';
566 $params['from'] = $from;
567 $params['toName'] = $toName;
568 $params['toEmail'] = $toEmail;
569 $params['subject'] = $subject;
570 $params['cc'] = $cc;
571 $params['text'] = $message;
572
573 CRM_Utils_Mail::send($params);
574 }
575}
576// end class CRM_Core_Payment_eWAY