3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
29 * Licensed to CiviCRM under the Academic Free License version 3.0.
31 * Written and contributed by Kirkdesigns (http://www.kirkdesigns.co.uk)
38 * @author Tom Kirkpatrick <tkp@kirkdesigns.co.uk>
41 class CRM_Core_Payment_Realex
extends CRM_Core_Payment
{
42 const AUTH_APPROVED
= '00';
44 protected $_mode = NULL;
46 protected $_params = array();
49 * We only need one instance of this object. So we use the singleton
50 * pattern and cache the instance in this variable
55 static private $_singleton = NULL;
60 * @param string $mode the mode of operation: live or test
62 * @param $paymentProcessor
64 * @return \CRM_Core_Payment_Realex
66 public function __construct($mode, &$paymentProcessor) {
68 $this->_paymentProcessor
= $paymentProcessor;
69 $this->_processorName
= ts('Realex');
71 $this->_setParam('merchant_ref', $paymentProcessor['user_name']);
72 $this->_setParam('secret', $paymentProcessor['password']);
73 $this->_setParam('account', $paymentProcessor['subject']);
75 $this->_setParam('emailCustomer', 'TRUE');
77 $this->_setParam('sequence', rand(1, 1000));
81 * Singleton function used to manage this object
83 * @param string $mode the mode of operation: live or test
85 * @param object $paymentProcessor
90 public static function &singleton($mode, &$paymentProcessor, &$paymentForm = NULL, $force = false) {
91 $processorName = $paymentProcessor['name'];
92 if (self
::$_singleton[$processorName] === NULL) {
93 self
::$_singleton[$processorName] = new CRM_Core_Payment_Realex($mode, $paymentProcessor);
95 return self
::$_singleton[$processorName];
99 * @param array $params
103 public function setExpressCheckOut(&$params) {
104 CRM_Core_Error
::fatal(ts('This function is not implemented'));
112 public function getExpressCheckoutDetails($token) {
113 CRM_Core_Error
::fatal(ts('This function is not implemented'));
117 * @param array $params
121 public function doExpressCheckout(&$params) {
122 CRM_Core_Error
::fatal(ts('This function is not implemented'));
126 * @param array $params
130 public function doTransferCheckout(&$params) {
131 CRM_Core_Error
::fatal(ts('This function is not implemented'));
135 * Submit a payment using Advanced Integration Method
137 * @param array $params assoc array of input parameters for this transaction
139 * @return array the result in a nice formatted array (or an error object)
141 public function doDirectPayment(&$params) {
143 if (!defined('CURLOPT_SSLCERT')) {
144 return self
::error(9001, ts('RealAuth requires curl with SSL support'));
147 $result = $this->setRealexFields($params);
149 if ($result !== TRUE) {
153 /**********************************************************
154 * Check to see if we have a duplicate before we send
155 **********************************************************/
156 if ($this->_checkDupe($this->_getParam('order_id'))) {
157 return self
::error(9004, ts('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 Authorize.net. 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.'));
160 // Create sha1 hash for request
161 $hashme = "{$this->_getParam('timestamp')}.{$this->_getParam('merchant_ref')}.{$this->_getParam('order_id')}.{$this->_getParam('amount')}.{$this->_getParam('currency')}.{$this->_getParam('card_number')}";
162 $sha1hash = sha1($hashme);
163 $hashme = "$sha1hash.{$this->_getParam('secret')}";
164 $sha1hash = sha1($hashme);
167 // Generate the request xml that is send to Realex Payments.
168 $request_xml = "<request type='auth' timestamp='{$this->_getParam('timestamp')}'>
169 <merchantid>{$this->_getParam('merchant_ref')}</merchantid>
170 <account>{$this->_getParam('account')}</account>
171 <orderid>{$this->_getParam('order_id')}</orderid>
172 <amount currency='{$this->_getParam('currency')}'>{$this->_getParam('amount')}</amount>
174 <number>{$this->_getParam('card_number')}</number>
175 <expdate>{$this->_getParam('exp_date')}</expdate>
176 <type>{$this->_getParam('card_type')}</type>
177 <chname>{$this->_getParam('card_name')}</chname>
178 <issueno>{$this->_getParam('issue_number')}</issueno>
180 <number>{$this->_getParam('cvn')}</number>
184 <autosettle flag='1'/>
185 <sha1hash>$sha1hash</sha1hash>
187 <comment id='1'>{$this->_getParam('comments')}</comment>
190 <varref>{$this->_getParam('varref')}</varref>
194 /**********************************************************
195 * Send to the payment processor using cURL
196 **********************************************************/
198 $submit = curl_init($this->_paymentProcessor
['url_site']);
201 return self
::error(9002, ts('Could not initiate connection to payment gateway'));
204 curl_setopt($submit, CURLOPT_HTTPHEADER
, array('SOAPAction: ""'));
205 curl_setopt($submit, CURLOPT_RETURNTRANSFER
, 1);
206 curl_setopt($submit, CURLOPT_TIMEOUT
, 60);
207 curl_setopt($submit, CURLOPT_SSL_VERIFYPEER
, CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'verifySSL'));
208 curl_setopt($submit, CURLOPT_HEADER
, 0);
210 // take caching out of the picture
211 curl_setopt($submit, CURLOPT_FORBID_REUSE
, 1);
212 curl_setopt($submit, CURLOPT_FRESH_CONNECT
, 1);
214 // Apply the XML to our curl call
215 curl_setopt($submit, CURLOPT_POST
, 1);
216 curl_setopt($submit, CURLOPT_POSTFIELDS
, $request_xml);
218 $response_xml = curl_exec($submit);
220 if (!$response_xml) {
221 return self
::error(curl_errno($submit), curl_error($submit));
226 // Tidy up the responce xml
227 $response_xml = preg_replace("/[\s\t]/", " ", $response_xml);
228 $response_xml = preg_replace("/[\n\r]/", "", $response_xml);
230 // Parse the response xml
231 $xml_parser = xml_parser_create();
232 if (!xml_parse($xml_parser, $response_xml)) {
233 return self
::error(9003, 'XML Error');
236 $response = $this->xml_parse_into_assoc($response_xml);
237 $response = $response['#return']['RESPONSE'];
239 // Log the Realex response for debugging
240 // CRM_Core_Error::debug_var('REALEX --------- Response from Realex: ', $response, TRUE);
242 // Return an error if authentication was not successful
243 if ($response['RESULT'] !== self
::AUTH_APPROVED
) {
244 return self
::error($response['RESULT'], ' ' . $response['MESSAGE']);
247 // Check the response hash
248 $hashme = "{$this->_getParam('timestamp')}.{$this->_getParam('merchant_ref')}.{$this->_getParam('order_id')}.{$response['RESULT']}.{$response['MESSAGE']}.{$response['PASREF']}.{$response['AUTHCODE']}";
249 $sha1hash = sha1($hashme);
250 $hashme = "$sha1hash.{$this->_getParam('secret')}";
251 $sha1hash = sha1($hashme);
253 if ($response['SHA1HASH'] != $sha1hash) {
254 // FIXME: Need to actually check this - I couldn't get the
255 // hashes to match so I'm commenting out for now'
256 // return self::error( 9001, "Hash error, please report this to the webmaster" );
259 // FIXME: We are using the trxn_result_code column to store all these extra details since there
260 // seems to be nowhere else to put them. This is THE WRONG THING TO DO!
262 'authcode' => $response['AUTHCODE'],
263 'batch_id' => $response['BATCHID'],
264 'message' => $response['MESSAGE'],
265 'trxn_result_code' => $response['RESULT'],
268 $params['trxn_id'] = $response['PASREF'];
269 $params['trxn_result_code'] = serialize($extras);
270 $params['currencyID'] = $this->_getParam('currency');
271 $params['gross_amount'] = $this->_getParam('amount');
272 $params['fee_amount'] = 0;
278 * Helper function to convert XML string to multi-dimension array.
283 * @return array An array of the result with following keys:
285 public function xml_parse_into_assoc($xml) {
289 $result['#error'] = FALSE;
290 $result['#return'] = NULL;
292 $xmlparser = xml_parser_create();
293 $ret = xml_parse_into_struct($xmlparser, $xml, $input);
295 xml_parser_free($xmlparser);
298 $result['#return'] = $xml;
302 $result['#return'] = $this->_xml_parse($input);
305 $result['#error'] = ts('Error parsing XML result - error code = %1 at line %2 char %3',
307 1 => xml_get_error_code($xmlparser),
308 2 => xml_get_current_line_number($xmlparser),
309 3 => xml_get_current_column_number($xmlparser)
317 // private helper for xml_parse_into_assoc, to recusively parsing the result
324 public function _xml_parse($input, $depth = 1) {
328 foreach ($input as $data) {
329 if ($data['level'] == $depth) {
330 switch ($data['type']) {
332 $output[$data['tag']] = isset($data['value']) ?
$data['value'] : '';
340 $output[$data['tag']] = $this->_xml_parse($children, $depth +
1);
352 * Format the params from the form ready for sending to Realex. Also perform some validation
354 public function setRealexFields(&$params) {
355 if ((int)$params['amount'] <= 0) {
356 return self
::error(9001, ts('Amount must be positive'));
359 // format amount to be in smallest possible units
360 //list($bills, $pennies) = explode('.', $params['amount']);
361 $this->_setParam('amount', 100 * $params['amount']);
363 switch (strtolower($params['credit_card_type'])) {
365 $this->_setParam('card_type', 'MC');
366 $this->_setParam('requiresIssueNumber', FALSE);
370 $this->_setParam('card_type', 'VISA');
371 $this->_setParam('requiresIssueNumber', FALSE);
375 $this->_setParam('card_type', 'AMEX');
376 $this->_setParam('requiresIssueNumber', FALSE);
380 $this->_setParam('card_type', 'LASER');
381 $this->_setParam('requiresIssueNumber', FALSE);
386 case 'maestro/switch':
388 $this->_setParam('card_type', 'SWITCH');
389 $this->_setParam('requiresIssueNumber', TRUE);
393 return self
::error(9001, ts('Credit card type not supported by Realex:') . ' ' . $params['credit_card_type']);
396 // get the card holder name - cater cor customized billing forms
397 if (isset($params['cardholder_name'])) {
398 $credit_card_name = $params['cardholder_name'];
401 $credit_card_name = $params['first_name'] . " ";
402 if (!empty($params['middle_name'])) {
403 $credit_card_name .= $params['middle_name'] . " ";
405 $credit_card_name .= $params['last_name'];
408 $this->_setParam('card_name', $credit_card_name);
409 $this->_setParam('card_number', str_replace(' ', '', $params['credit_card_number']));
410 $this->_setParam('cvn', $params['cvv2']);
411 $this->_setParam('country', $params['country']);
412 $this->_setParam('post_code', $params['postal_code']);
413 $this->_setParam('order_id', $params['invoiceID']);
414 $params['issue_number'] = (isset($params['issue_number']) ?
$params['issue_number'] : '');
415 $this->_setParam('issue_number', $params['issue_number']);
416 $this->_setParam('varref', $params['contributionType_name']);
417 $comment = $params['description'] . ' (page id:' . $params['contributionPageID'] . ')';
418 $this->_setParam('comments', $comment);
419 //$this->_setParam('currency', $params['currencyID']);
421 // set the currency to the default which can be overrided.
422 $config = CRM_Core_Config
::singleton();
423 $this->_setParam('currency', $config->defaultCurrency
);
425 // Format the expiry date to MMYY
426 $expmonth = (string)$params['month'];
427 $expmonth = (strlen($expmonth) === 1) ?
'0' . $expmonth : $expmonth;
428 $expyear = substr((string)$params['year'], 2, 2);
429 $this->_setParam('exp_date', $expmonth . $expyear);
431 if (isset($params['credit_card_start_date']) && (strlen($params['credit_card_start_date']['M']) !== 0) &&
432 (strlen($params['credit_card_start_date']['Y']) !== 0)
434 $startmonth = (string)$params['credit_card_start_date']['M'];
435 $startmonth = (strlen($startmonth) === 1) ?
'0' . $startmonth : $startmonth;
436 $startyear = substr((string)$params['credit_card_start_date']['Y'], 2, 2);
437 $this->_setParam('start_date', $startmonth . $startyear);
441 $timestamp = strftime("%Y%m%d%H%M%S");
442 $this->_setParam('timestamp', $timestamp);
448 * Checks to see if invoice_id already exists in db
450 * @param int $invoiceId The ID to check
452 * @return bool True if ID exists, else false
454 public function _checkDupe($invoiceId) {
455 $contribution = new CRM_Contribute_DAO_Contribution();
456 $contribution->invoice_id
= $invoiceId;
457 return $contribution->find();
461 * Get the value of a field if set
463 * @param string $field the field
465 * @return mixed value of the field, or empty string if the field is
468 public function _getParam($field) {
469 if (isset($this->_params
[$field])) {
470 return $this->_params
[$field];
478 * Set a field to the specified value. Value must be a scalar (int,
479 * float, string, or boolean)
481 * @param string $field
482 * @param mixed $value
484 * @return bool false if value is not a scalar, true if successful
486 public function _setParam($field, $value) {
487 if (!is_scalar($value)) {
491 $this->_params
[$field] = $value;
496 * @param null $errorCode
497 * @param null $errorMessage
501 public function &error($errorCode = NULL, $errorMessage = NULL) {
502 $e = CRM_Core_Error
::singleton();
505 if ($errorCode == '101' ||
$errorCode == '102') {
506 $display_error = ts('Card declined by bank. Please try with a different card.');
508 elseif ($errorCode == '103') {
509 $display_error = ts('Card reported lost or stolen. This incident will be reported.');
511 elseif ($errorCode == '501') {
512 $display_error = ts("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 for this transaction. 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.");
514 elseif ($errorCode == '509') {
515 $display_error = $errorMessage;
518 $display_error = ts('We were unable to process your payment at this time. Please try again later.');
520 $e->push($errorCode, 0, NULL, $display_error);
523 $e->push(9001, 0, NULL, ts('We were unable to process your payment at this time. Please try again later.'));
529 * This function checks to see if we have the right config values
531 * @return string the error message if any
533 public function checkConfig() {
535 if (empty($this->_paymentProcessor
['user_name'])) {
536 $error[] = ts('Merchant ID is not set for this payment processor');
539 if (empty($this->_paymentProcessor
['password'])) {
540 $error[] = ts('Secret is not set for this payment processor');
543 if (!empty($error)) {
544 return implode('<p>', $error);