3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
14 * Licensed to CiviCRM under the Academic Free License version 3.0.
16 * Written and contributed by Kirkdesigns (http://www.kirkdesigns.co.uk)
19 use Civi\Payment\Exception\PaymentProcessorException
;
24 * @author Tom Kirkpatrick <tkp@kirkdesigns.co.uk>
26 class CRM_Core_Payment_Realex
extends CRM_Core_Payment
{
27 const AUTH_APPROVED
= '00';
31 protected $_params = [];
37 * The mode of operation: live or test.
39 * @param array $paymentProcessor
41 public function __construct($mode, &$paymentProcessor) {
43 $this->_paymentProcessor
= $paymentProcessor;
45 $this->_setParam('merchant_ref', $paymentProcessor['user_name']);
46 $this->_setParam('secret', $paymentProcessor['password']);
47 $this->_setParam('account', $paymentProcessor['subject']);
49 $this->_setParam('emailCustomer', 'TRUE');
51 $this->_setParam('sequence', rand(1, 1000));
55 * Submit a payment using Advanced Integration Method.
57 * @param array $params
58 * Assoc array of input parameters for this transaction.
61 * the result in a nice formatted array (or an error object)
63 * @throws \Civi\Payment\Exception\PaymentProcessorException
65 public function doDirectPayment(&$params) {
67 if (!defined('CURLOPT_SSLCERT')) {
68 throw new PaymentProcessorException(ts('RealAuth requires curl with SSL support'), 9001);
71 $result = $this->setRealexFields($params);
73 /**********************************************************
74 * Check to see if we have a duplicate before we send
75 **********************************************************/
76 if ($this->checkDupe($params['invoiceID'], CRM_Utils_Array
::value('contributionID', $params))) {
77 throw new PaymentProcessorException(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.'), 9004);
80 // Create sha1 hash for request
81 $hashme = "{$this->_getParam('timestamp')}.{$this->_getParam('merchant_ref')}.{$this->_getParam('order_id')}.{$this->_getParam('amount')}.{$this->_getParam('currency')}.{$this->_getParam('card_number')}";
82 $sha1hash = sha1($hashme);
83 $hashme = "$sha1hash.{$this->_getParam('secret')}";
84 $sha1hash = sha1($hashme);
86 // Generate the request xml that is send to Realex Payments.
87 $request_xml = "<request type='auth' timestamp='{$this->_getParam('timestamp')}'>
88 <merchantid>{$this->_getParam('merchant_ref')}</merchantid>
89 <account>{$this->_getParam('account')}</account>
90 <orderid>{$this->_getParam('order_id')}</orderid>
91 <amount currency='{$this->_getParam('currency')}'>{$this->_getParam('amount')}</amount>
93 <number>{$this->_getParam('card_number')}</number>
94 <expdate>{$this->_getParam('exp_date')}</expdate>
95 <type>{$this->_getParam('card_type')}</type>
96 <chname>{$this->_getParam('card_name')}</chname>
97 <issueno>{$this->_getParam('issue_number')}</issueno>
99 <number>{$this->_getParam('cvn')}</number>
103 <autosettle flag='1'/>
104 <sha1hash>$sha1hash</sha1hash>
106 <comment id='1'>{$this->_getParam('comments')}</comment>
109 <varref>{$this->_getParam('varref')}</varref>
113 /**********************************************************
114 * Send to the payment processor using cURL
115 **********************************************************/
117 $submit = curl_init($this->_paymentProcessor
['url_site']);
120 throw new PaymentProcessorException(ts('Could not initiate connection to payment gateway'), 9002);
123 curl_setopt($submit, CURLOPT_HTTPHEADER
, ['SOAPAction: ""']);
124 curl_setopt($submit, CURLOPT_RETURNTRANSFER
, 1);
125 curl_setopt($submit, CURLOPT_TIMEOUT
, 60);
126 curl_setopt($submit, CURLOPT_SSL_VERIFYPEER
, Civi
::settings()->get('verifySSL'));
127 curl_setopt($submit, CURLOPT_HEADER
, 0);
129 // take caching out of the picture
130 curl_setopt($submit, CURLOPT_FORBID_REUSE
, 1);
131 curl_setopt($submit, CURLOPT_FRESH_CONNECT
, 1);
133 // Apply the XML to our curl call
134 curl_setopt($submit, CURLOPT_POST
, 1);
135 curl_setopt($submit, CURLOPT_POSTFIELDS
, $request_xml);
137 $response_xml = curl_exec($submit);
139 if (!$response_xml) {
140 throw new PaymentProcessorException(curl_error($submit), curl_errno($submit));
145 // Tidy up the response xml
146 $response_xml = preg_replace("/[\s\t]/", " ", $response_xml);
147 $response_xml = preg_replace("/[\n\r]/", "", $response_xml);
149 // Parse the response xml
150 $xml_parser = xml_parser_create();
151 if (!xml_parse($xml_parser, $response_xml)) {
152 throw new PaymentProcessorException('XML Error', 9003);
155 $response = $this->xml_parse_into_assoc($response_xml);
156 $response = $response['#return']['RESPONSE'];
158 // Log the Realex response for debugging
159 // CRM_Core_Error::debug_var('REALEX --------- Response from Realex: ', $response, TRUE);
161 // Return an error if authentication was not successful
162 if ($response['RESULT'] !== self
::AUTH_APPROVED
) {
163 throw new PaymentProcessorException($this->getDisplayError($response['RESULT'], ' ' . $response['MESSAGE']));
166 // FIXME: We are using the trxn_result_code column to store all these extra details since there
167 // seems to be nowhere else to put them. This is THE WRONG THING TO DO!
169 'authcode' => $response['AUTHCODE'],
170 'batch_id' => $response['BATCHID'],
171 'message' => $response['MESSAGE'],
172 'trxn_result_code' => $response['RESULT'],
175 $params['trxn_id'] = $response['PASREF'];
176 $params['trxn_result_code'] = serialize($extras);
177 $params['currencyID'] = $this->_getParam('currency');
178 $params['gross_amount'] = $this->_getParam('amount');
179 $params['fee_amount'] = 0;
185 * Helper function to convert XML string to multi-dimension array.
191 * An array of the result with following keys:
193 public function xml_parse_into_assoc($xml) {
197 $result['#error'] = FALSE;
198 $result['#return'] = NULL;
200 $xmlparser = xml_parser_create();
201 $ret = xml_parse_into_struct($xmlparser, $xml, $input);
203 xml_parser_free($xmlparser);
206 $result['#return'] = $xml;
210 $result['#return'] = $this->_xml_parse($input);
213 $result['#error'] = ts('Error parsing XML result - error code = %1 at line %2 char %3',
215 1 => xml_get_error_code($xmlparser),
216 2 => xml_get_current_line_number($xmlparser),
217 3 => xml_get_current_column_number($xmlparser),
226 * Private helper for xml_parse_into_assoc, to recursively parsing the result.
233 public function _xml_parse($input, $depth = 1) {
237 foreach ($input as $data) {
238 if ($data['level'] == $depth) {
239 switch ($data['type']) {
241 $output[$data['tag']] = $data['value'] ??
'';
249 $output[$data['tag']] = $this->_xml_parse($children, $depth +
1);
261 * Format the params from the form ready for sending to Realex.
263 * Also perform some validation
265 * @param array $params
267 * @throws \Civi\Payment\Exception\PaymentProcessorException
269 public function setRealexFields(&$params) {
270 if ((int) $params['amount'] <= 0) {
271 throw new PaymentProcessorException(ts('Amount must be positive'), 9001);
274 // format amount to be in smallest possible units
275 //list($bills, $pennies) = explode('.', $params['amount']);
276 $this->_setParam('amount', 100 * $params['amount']);
278 switch (strtolower($params['credit_card_type'])) {
280 $this->_setParam('card_type', 'MC');
281 $this->_setParam('requiresIssueNumber', FALSE);
285 $this->_setParam('card_type', 'VISA');
286 $this->_setParam('requiresIssueNumber', FALSE);
290 $this->_setParam('card_type', 'AMEX');
291 $this->_setParam('requiresIssueNumber', FALSE);
295 $this->_setParam('card_type', 'LASER');
296 $this->_setParam('requiresIssueNumber', FALSE);
301 case 'maestro/switch':
303 $this->_setParam('card_type', 'SWITCH');
304 $this->_setParam('requiresIssueNumber', TRUE);
308 throw new PaymentProcessorException(ts('Credit card type not supported by Realex:') . ' ' . $params['credit_card_type'], 9001);
311 // get the card holder name - cater cor customized billing forms
312 if (isset($params['cardholder_name'])) {
313 $credit_card_name = $params['cardholder_name'];
316 $credit_card_name = $params['first_name'] . " ";
317 if (!empty($params['middle_name'])) {
318 $credit_card_name .= $params['middle_name'] . " ";
320 $credit_card_name .= $params['last_name'];
323 $this->_setParam('card_name', $credit_card_name);
324 $this->_setParam('card_number', str_replace(' ', '', $params['credit_card_number']));
325 $this->_setParam('cvn', $params['cvv2']);
326 $this->_setParam('country', $params['country']);
327 $this->_setParam('post_code', $params['postal_code']);
328 $this->_setParam('order_id', $params['invoiceID']);
329 $params['issue_number'] = ($params['issue_number'] ??
'');
330 $this->_setParam('issue_number', $params['issue_number']);
331 $this->_setParam('varref', $params['contributionType_name']);
332 $comment = $params['description'] . ' (page id:' . $params['contributionPageID'] . ')';
333 $this->_setParam('comments', $comment);
335 // set the currency to the default which can be overrided.
336 $this->_setParam('currency', CRM_Core_Config
::singleton()->defaultCurrency
);
338 // Format the expiry date to MMYY
339 $expmonth = (string) $params['month'];
340 $expmonth = (strlen($expmonth) === 1) ?
'0' . $expmonth : $expmonth;
341 $expyear = substr((string) $params['year'], 2, 2);
342 $this->_setParam('exp_date', $expmonth . $expyear);
344 if (isset($params['credit_card_start_date']) && (strlen($params['credit_card_start_date']['M']) !== 0) &&
345 (strlen($params['credit_card_start_date']['Y']) !== 0)
347 $startmonth = (string) $params['credit_card_start_date']['M'];
348 $startmonth = (strlen($startmonth) === 1) ?
'0' . $startmonth : $startmonth;
349 $startyear = substr((string) $params['credit_card_start_date']['Y'], 2, 2);
350 $this->_setParam('start_date', $startmonth . $startyear);
354 $timestamp = strftime('%Y%m%d%H%M%S');
355 $this->_setParam('timestamp', $timestamp);
359 * Get the value of a field if set.
361 * @param string $field
365 * value of the field, or empty string if the field is
368 public function _getParam($field) {
369 if (isset($this->_params
[$field])) {
370 return $this->_params
[$field];
376 * Set a field to the specified value. Value must be a scalar (int,
377 * float, string, or boolean)
379 * @param string $field
380 * @param mixed $value
382 public function _setParam($field, $value) {
383 if (!is_scalar($value)) {
386 $this->_params
[$field] = $value;
390 * This function checks to see if we have the right config values.
393 * the error message if any
395 public function checkConfig() {
397 if (empty($this->_paymentProcessor
['user_name'])) {
398 $error[] = ts('Merchant ID is not set for this payment processor');
401 if (empty($this->_paymentProcessor
['password'])) {
402 $error[] = ts('Secret is not set for this payment processor');
405 if (!empty($error)) {
406 return implode('<p>', $error);
412 * Get the error to display.
414 * @param string $errorCode
415 * @param string $errorMessage
419 protected function getDisplayError($errorCode, $errorMessage): string {
420 if ($errorCode === '101' ||
$errorCode === '102') {
421 $display_error = ts('Card declined by bank. Please try with a different card.');
423 elseif ($errorCode === '103') {
424 $display_error = ts('Card reported lost or stolen. This incident will be reported.');
426 elseif ($errorCode === '501') {
427 $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.');
429 elseif ($errorCode === '509') {
430 $display_error = $errorMessage;
433 $display_error = ts('We were unable to process your payment at this time. Please try again later.');
435 return $display_error;