3 +--------------------------------------------------------------------+
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)
37 * @author Tom Kirkpatrick <tkp@kirkdesigns.co.uk>
40 class CRM_Core_Payment_Realex
extends CRM_Core_Payment
{
41 const AUTH_APPROVED
= '00';
43 protected $_mode = NULL;
45 protected $_params = [];
51 * The mode of operation: live or test.
53 * @param $paymentProcessor
55 * @return \CRM_Core_Payment_Realex
57 public function __construct($mode, &$paymentProcessor) {
59 $this->_paymentProcessor
= $paymentProcessor;
61 $this->_setParam('merchant_ref', $paymentProcessor['user_name']);
62 $this->_setParam('secret', $paymentProcessor['password']);
63 $this->_setParam('account', $paymentProcessor['subject']);
65 $this->_setParam('emailCustomer', 'TRUE');
67 $this->_setParam('sequence', rand(1, 1000));
71 * Submit a payment using Advanced Integration Method.
73 * @param array $params
74 * Assoc array of input parameters for this transaction.
77 * the result in a nice formatted array (or an error object)
79 public function doDirectPayment(&$params) {
81 if (!defined('CURLOPT_SSLCERT')) {
82 return self
::error(9001, ts('RealAuth requires curl with SSL support'));
85 $result = $this->setRealexFields($params);
87 if ($result !== TRUE) {
91 /**********************************************************
92 * Check to see if we have a duplicate before we send
93 **********************************************************/
94 if ($this->checkDupe($params['invoiceID'], CRM_Utils_Array
::value('contributionID', $params))) {
95 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.'));
98 // Create sha1 hash for request
99 $hashme = "{$this->_getParam('timestamp')}.{$this->_getParam('merchant_ref')}.{$this->_getParam('order_id')}.{$this->_getParam('amount')}.{$this->_getParam('currency')}.{$this->_getParam('card_number')}";
100 $sha1hash = sha1($hashme);
101 $hashme = "$sha1hash.{$this->_getParam('secret')}";
102 $sha1hash = sha1($hashme);
104 // Generate the request xml that is send to Realex Payments.
105 $request_xml = "<request type='auth' timestamp='{$this->_getParam('timestamp')}'>
106 <merchantid>{$this->_getParam('merchant_ref')}</merchantid>
107 <account>{$this->_getParam('account')}</account>
108 <orderid>{$this->_getParam('order_id')}</orderid>
109 <amount currency='{$this->_getParam('currency')}'>{$this->_getParam('amount')}</amount>
111 <number>{$this->_getParam('card_number')}</number>
112 <expdate>{$this->_getParam('exp_date')}</expdate>
113 <type>{$this->_getParam('card_type')}</type>
114 <chname>{$this->_getParam('card_name')}</chname>
115 <issueno>{$this->_getParam('issue_number')}</issueno>
117 <number>{$this->_getParam('cvn')}</number>
121 <autosettle flag='1'/>
122 <sha1hash>$sha1hash</sha1hash>
124 <comment id='1'>{$this->_getParam('comments')}</comment>
127 <varref>{$this->_getParam('varref')}</varref>
131 /**********************************************************
132 * Send to the payment processor using cURL
133 **********************************************************/
135 $submit = curl_init($this->_paymentProcessor
['url_site']);
138 return self
::error(9002, ts('Could not initiate connection to payment gateway'));
141 curl_setopt($submit, CURLOPT_HTTPHEADER
, ['SOAPAction: ""']);
142 curl_setopt($submit, CURLOPT_RETURNTRANSFER
, 1);
143 curl_setopt($submit, CURLOPT_TIMEOUT
, 60);
144 curl_setopt($submit, CURLOPT_SSL_VERIFYPEER
, Civi
::settings()->get('verifySSL'));
145 curl_setopt($submit, CURLOPT_HEADER
, 0);
147 // take caching out of the picture
148 curl_setopt($submit, CURLOPT_FORBID_REUSE
, 1);
149 curl_setopt($submit, CURLOPT_FRESH_CONNECT
, 1);
151 // Apply the XML to our curl call
152 curl_setopt($submit, CURLOPT_POST
, 1);
153 curl_setopt($submit, CURLOPT_POSTFIELDS
, $request_xml);
155 $response_xml = curl_exec($submit);
157 if (!$response_xml) {
158 return self
::error(curl_errno($submit), curl_error($submit));
163 // Tidy up the response xml
164 $response_xml = preg_replace("/[\s\t]/", " ", $response_xml);
165 $response_xml = preg_replace("/[\n\r]/", "", $response_xml);
167 // Parse the response xml
168 $xml_parser = xml_parser_create();
169 if (!xml_parse($xml_parser, $response_xml)) {
170 return self
::error(9003, 'XML Error');
173 $response = $this->xml_parse_into_assoc($response_xml);
174 $response = $response['#return']['RESPONSE'];
176 // Log the Realex response for debugging
177 // CRM_Core_Error::debug_var('REALEX --------- Response from Realex: ', $response, TRUE);
179 // Return an error if authentication was not successful
180 if ($response['RESULT'] !== self
::AUTH_APPROVED
) {
181 return self
::error($response['RESULT'], ' ' . $response['MESSAGE']);
184 // Check the response hash
185 $hashme = "{$this->_getParam('timestamp')}.{$this->_getParam('merchant_ref')}.{$this->_getParam('order_id')}.{$response['RESULT']}.{$response['MESSAGE']}.{$response['PASREF']}.{$response['AUTHCODE']}";
186 $sha1hash = sha1($hashme);
187 $hashme = "$sha1hash.{$this->_getParam('secret')}";
188 $sha1hash = sha1($hashme);
190 if ($response['SHA1HASH'] != $sha1hash) {
191 // FIXME: Need to actually check this - I couldn't get the
192 // hashes to match so I'm commenting out for now'
193 // return self::error( 9001, "Hash error, please report this to the webmaster" );
196 // FIXME: We are using the trxn_result_code column to store all these extra details since there
197 // seems to be nowhere else to put them. This is THE WRONG THING TO DO!
199 'authcode' => $response['AUTHCODE'],
200 'batch_id' => $response['BATCHID'],
201 'message' => $response['MESSAGE'],
202 'trxn_result_code' => $response['RESULT'],
205 $params['trxn_id'] = $response['PASREF'];
206 $params['trxn_result_code'] = serialize($extras);
207 $params['currencyID'] = $this->_getParam('currency');
208 $params['gross_amount'] = $this->_getParam('amount');
209 $params['fee_amount'] = 0;
215 * Helper function to convert XML string to multi-dimension array.
221 * An array of the result with following keys:
223 public function xml_parse_into_assoc($xml) {
227 $result['#error'] = FALSE;
228 $result['#return'] = NULL;
230 $xmlparser = xml_parser_create();
231 $ret = xml_parse_into_struct($xmlparser, $xml, $input);
233 xml_parser_free($xmlparser);
236 $result['#return'] = $xml;
240 $result['#return'] = $this->_xml_parse($input);
243 $result['#error'] = ts('Error parsing XML result - error code = %1 at line %2 char %3',
245 1 => xml_get_error_code($xmlparser),
246 2 => xml_get_current_line_number($xmlparser),
247 3 => xml_get_current_column_number($xmlparser),
256 * Private helper for xml_parse_into_assoc, to recusively parsing the result
262 public function _xml_parse($input, $depth = 1) {
266 foreach ($input as $data) {
267 if ($data['level'] == $depth) {
268 switch ($data['type']) {
270 $output[$data['tag']] = $data['value'] ??
'';
278 $output[$data['tag']] = $this->_xml_parse($children, $depth +
1);
290 * Format the params from the form ready for sending to Realex.
292 * Also perform some validation
294 * @param array $params
298 public function setRealexFields(&$params) {
299 if ((int) $params['amount'] <= 0) {
300 return self
::error(9001, ts('Amount must be positive'));
303 // format amount to be in smallest possible units
304 //list($bills, $pennies) = explode('.', $params['amount']);
305 $this->_setParam('amount', 100 * $params['amount']);
307 switch (strtolower($params['credit_card_type'])) {
309 $this->_setParam('card_type', 'MC');
310 $this->_setParam('requiresIssueNumber', FALSE);
314 $this->_setParam('card_type', 'VISA');
315 $this->_setParam('requiresIssueNumber', FALSE);
319 $this->_setParam('card_type', 'AMEX');
320 $this->_setParam('requiresIssueNumber', FALSE);
324 $this->_setParam('card_type', 'LASER');
325 $this->_setParam('requiresIssueNumber', FALSE);
330 case 'maestro/switch':
332 $this->_setParam('card_type', 'SWITCH');
333 $this->_setParam('requiresIssueNumber', TRUE);
337 return self
::error(9001, ts('Credit card type not supported by Realex:') . ' ' . $params['credit_card_type']);
340 // get the card holder name - cater cor customized billing forms
341 if (isset($params['cardholder_name'])) {
342 $credit_card_name = $params['cardholder_name'];
345 $credit_card_name = $params['first_name'] . " ";
346 if (!empty($params['middle_name'])) {
347 $credit_card_name .= $params['middle_name'] . " ";
349 $credit_card_name .= $params['last_name'];
352 $this->_setParam('card_name', $credit_card_name);
353 $this->_setParam('card_number', str_replace(' ', '', $params['credit_card_number']));
354 $this->_setParam('cvn', $params['cvv2']);
355 $this->_setParam('country', $params['country']);
356 $this->_setParam('post_code', $params['postal_code']);
357 $this->_setParam('order_id', $params['invoiceID']);
358 $params['issue_number'] = ($params['issue_number'] ??
'');
359 $this->_setParam('issue_number', $params['issue_number']);
360 $this->_setParam('varref', $params['contributionType_name']);
361 $comment = $params['description'] . ' (page id:' . $params['contributionPageID'] . ')';
362 $this->_setParam('comments', $comment);
363 //$this->_setParam('currency', $params['currencyID']);
365 // set the currency to the default which can be overrided.
366 $config = CRM_Core_Config
::singleton();
367 $this->_setParam('currency', $config->defaultCurrency
);
369 // Format the expiry date to MMYY
370 $expmonth = (string) $params['month'];
371 $expmonth = (strlen($expmonth) === 1) ?
'0' . $expmonth : $expmonth;
372 $expyear = substr((string) $params['year'], 2, 2);
373 $this->_setParam('exp_date', $expmonth . $expyear);
375 if (isset($params['credit_card_start_date']) && (strlen($params['credit_card_start_date']['M']) !== 0) &&
376 (strlen($params['credit_card_start_date']['Y']) !== 0)
378 $startmonth = (string) $params['credit_card_start_date']['M'];
379 $startmonth = (strlen($startmonth) === 1) ?
'0' . $startmonth : $startmonth;
380 $startyear = substr((string) $params['credit_card_start_date']['Y'], 2, 2);
381 $this->_setParam('start_date', $startmonth . $startyear);
385 $timestamp = strftime("%Y%m%d%H%M%S");
386 $this->_setParam('timestamp', $timestamp);
392 * Get the value of a field if set.
394 * @param string $field
398 * value of the field, or empty string if the field is
401 public function _getParam($field) {
402 if (isset($this->_params
[$field])) {
403 return $this->_params
[$field];
411 * Set a field to the specified value. Value must be a scalar (int,
412 * float, string, or boolean)
414 * @param string $field
415 * @param mixed $value
418 * false if value is not a scalar, true if successful
420 public function _setParam($field, $value) {
421 if (!is_scalar($value)) {
425 $this->_params
[$field] = $value;
430 * @param null $errorCode
431 * @param null $errorMessage
435 public function &error($errorCode = NULL, $errorMessage = NULL) {
436 $e = CRM_Core_Error
::singleton();
439 if ($errorCode == '101' ||
$errorCode == '102') {
440 $display_error = ts('Card declined by bank. Please try with a different card.');
442 elseif ($errorCode == '103') {
443 $display_error = ts('Card reported lost or stolen. This incident will be reported.');
445 elseif ($errorCode == '501') {
446 $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.");
448 elseif ($errorCode == '509') {
449 $display_error = $errorMessage;
452 $display_error = ts('We were unable to process your payment at this time. Please try again later.');
454 $e->push($errorCode, 0, NULL, $display_error);
457 $e->push(9001, 0, NULL, ts('We were unable to process your payment at this time. Please try again later.'));
463 * This function checks to see if we have the right config values.
466 * the error message if any
468 public function checkConfig() {
470 if (empty($this->_paymentProcessor
['user_name'])) {
471 $error[] = ts('Merchant ID is not set for this payment processor');
474 if (empty($this->_paymentProcessor
['password'])) {
475 $error[] = ts('Secret is not set for this payment processor');
478 if (!empty($error)) {
479 return implode('<p>', $error);