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|PropertyBag $params
59 * @param string $component
62 * Result array (containing at least the key payment_status_id)
64 * @throws \Civi\Payment\Exception\PaymentProcessorException
66 public function doPayment(&$params, $component = 'contribute') {
67 $propertyBag = \Civi\Payment\PropertyBag
::cast($params);
68 $this->_component
= $component;
69 $result = $this->setStatusPaymentPending([]);
71 // If we have a $0 amount, skip call to processor and set payment_status to Completed.
72 // Conceivably a processor might override this - perhaps for setting up a token - but we don't
73 // have an example of that at the moment.
74 if ($propertyBag->getAmount() == 0) {
75 $result = $this->setStatusPaymentCompleted($result);
79 if (!defined('CURLOPT_SSLCERT')) {
80 throw new PaymentProcessorException(ts('RealAuth requires curl with SSL support'), 9001);
83 $this->setRealexFields($params);
85 /**********************************************************
86 * Check to see if we have a duplicate before we send
87 **********************************************************/
88 if ($this->checkDupe($params['invoiceID'], CRM_Utils_Array
::value('contributionID', $params))) {
89 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);
92 // Create sha1 hash for request
93 $hashme = "{$this->_getParam('timestamp')}.{$this->_getParam('merchant_ref')}.{$this->_getParam('order_id')}.{$this->_getParam('amount')}.{$this->_getParam('currency')}.{$this->_getParam('card_number')}";
94 $sha1hash = sha1($hashme);
95 $hashme = "$sha1hash.{$this->_getParam('secret')}";
96 $sha1hash = sha1($hashme);
98 // Generate the request xml that is send to Realex Payments.
99 $request_xml = "<request type='auth' timestamp='{$this->_getParam('timestamp')}'>
100 <merchantid>{$this->_getParam('merchant_ref')}</merchantid>
101 <account>{$this->_getParam('account')}</account>
102 <orderid>{$this->_getParam('order_id')}</orderid>
103 <amount currency='{$this->_getParam('currency')}'>{$this->_getParam('amount')}</amount>
105 <number>{$this->_getParam('card_number')}</number>
106 <expdate>{$this->_getParam('exp_date')}</expdate>
107 <type>{$this->_getParam('card_type')}</type>
108 <chname>{$this->_getParam('card_name')}</chname>
109 <issueno>{$this->_getParam('issue_number')}</issueno>
111 <number>{$this->_getParam('cvn')}</number>
115 <autosettle flag='1'/>
116 <sha1hash>$sha1hash</sha1hash>
118 <comment id='1'>{$this->_getParam('comments')}</comment>
121 <varref>{$this->_getParam('varref')}</varref>
125 /**********************************************************
126 * Send to the payment processor using cURL
127 **********************************************************/
129 $submit = curl_init($this->_paymentProcessor
['url_site']);
132 throw new PaymentProcessorException(ts('Could not initiate connection to payment gateway'), 9002);
135 curl_setopt($submit, CURLOPT_HTTPHEADER
, ['SOAPAction: ""']);
136 curl_setopt($submit, CURLOPT_RETURNTRANSFER
, 1);
137 curl_setopt($submit, CURLOPT_TIMEOUT
, 60);
138 curl_setopt($submit, CURLOPT_SSL_VERIFYPEER
, Civi
::settings()->get('verifySSL'));
139 curl_setopt($submit, CURLOPT_HEADER
, 0);
141 // take caching out of the picture
142 curl_setopt($submit, CURLOPT_FORBID_REUSE
, 1);
143 curl_setopt($submit, CURLOPT_FRESH_CONNECT
, 1);
145 // Apply the XML to our curl call
146 curl_setopt($submit, CURLOPT_POST
, 1);
147 curl_setopt($submit, CURLOPT_POSTFIELDS
, $request_xml);
149 $response_xml = curl_exec($submit);
151 if (!$response_xml) {
152 throw new PaymentProcessorException(curl_error($submit), curl_errno($submit));
157 // Tidy up the response xml
158 $response_xml = preg_replace("/[\s\t]/", " ", $response_xml);
159 $response_xml = preg_replace("/[\n\r]/", "", $response_xml);
161 // Parse the response xml
162 $xml_parser = xml_parser_create();
163 if (!xml_parse($xml_parser, $response_xml)) {
164 throw new PaymentProcessorException('XML Error', 9003);
167 $response = $this->xml_parse_into_assoc($response_xml);
168 $response = $response['#return']['RESPONSE'];
170 // Log the Realex response for debugging
171 // CRM_Core_Error::debug_var('REALEX --------- Response from Realex: ', $response, TRUE);
173 // Return an error if authentication was not successful
174 if ($response['RESULT'] !== self
::AUTH_APPROVED
) {
175 throw new PaymentProcessorException($this->getDisplayError($response['RESULT'], ' ' . $response['MESSAGE']));
178 // FIXME: We are using the trxn_result_code column to store all these extra details since there
179 // seems to be nowhere else to put them. This is THE WRONG THING TO DO!
181 'authcode' => $response['AUTHCODE'],
182 'batch_id' => $response['BATCHID'],
183 'message' => $response['MESSAGE'],
184 'trxn_result_code' => $response['RESULT'],
187 $params['trxn_result_code'] = serialize($extras);
188 $params['currencyID'] = $this->_getParam('currency');
189 $result['trxn_id'] = $response['PASREF'];
190 $result['fee_amount'] = 0;
191 $result = $this->setStatusPaymentCompleted($result);
197 * Helper function to convert XML string to multi-dimension array.
203 * An array of the result with following keys:
205 public function xml_parse_into_assoc($xml) {
209 $result['#error'] = FALSE;
210 $result['#return'] = NULL;
212 $xmlparser = xml_parser_create();
213 $ret = xml_parse_into_struct($xmlparser, $xml, $input);
215 xml_parser_free($xmlparser);
218 $result['#return'] = $xml;
222 $result['#return'] = $this->_xml_parse($input);
225 $result['#error'] = ts('Error parsing XML result - error code = %1 at line %2 char %3',
227 1 => xml_get_error_code($xmlparser),
228 2 => xml_get_current_line_number($xmlparser),
229 3 => xml_get_current_column_number($xmlparser),
238 * Private helper for xml_parse_into_assoc, to recursively parsing the result.
245 public function _xml_parse($input, $depth = 1) {
249 foreach ($input as $data) {
250 if ($data['level'] == $depth) {
251 switch ($data['type']) {
253 $output[$data['tag']] = $data['value'] ??
'';
261 $output[$data['tag']] = $this->_xml_parse($children, $depth +
1);
273 * Format the params from the form ready for sending to Realex.
275 * Also perform some validation
277 * @param array $params
279 * @throws \Civi\Payment\Exception\PaymentProcessorException
281 public function setRealexFields(&$params) {
282 if ((int) $params['amount'] <= 0) {
283 throw new PaymentProcessorException(ts('Amount must be positive'), 9001);
286 // format amount to be in smallest possible units
287 //list($bills, $pennies) = explode('.', $params['amount']);
288 $this->_setParam('amount', 100 * $params['amount']);
290 switch (strtolower($params['credit_card_type'])) {
292 $this->_setParam('card_type', 'MC');
293 $this->_setParam('requiresIssueNumber', FALSE);
297 $this->_setParam('card_type', 'VISA');
298 $this->_setParam('requiresIssueNumber', FALSE);
302 $this->_setParam('card_type', 'AMEX');
303 $this->_setParam('requiresIssueNumber', FALSE);
307 $this->_setParam('card_type', 'LASER');
308 $this->_setParam('requiresIssueNumber', FALSE);
313 case 'maestro/switch':
315 $this->_setParam('card_type', 'SWITCH');
316 $this->_setParam('requiresIssueNumber', TRUE);
320 throw new PaymentProcessorException(ts('Credit card type not supported by Realex:') . ' ' . $params['credit_card_type'], 9001);
323 // get the card holder name - cater cor customized billing forms
324 if (isset($params['cardholder_name'])) {
325 $credit_card_name = $params['cardholder_name'];
328 $credit_card_name = $params['first_name'] . " ";
329 if (!empty($params['middle_name'])) {
330 $credit_card_name .= $params['middle_name'] . " ";
332 $credit_card_name .= $params['last_name'];
335 $this->_setParam('card_name', $credit_card_name);
336 $this->_setParam('card_number', str_replace(' ', '', $params['credit_card_number']));
337 $this->_setParam('cvn', $params['cvv2']);
338 $this->_setParam('country', $params['country']);
339 $this->_setParam('post_code', $params['postal_code']);
340 $this->_setParam('order_id', $params['invoiceID']);
341 $params['issue_number'] = ($params['issue_number'] ??
'');
342 $this->_setParam('issue_number', $params['issue_number']);
343 $this->_setParam('varref', $params['contributionType_name']);
344 $comment = $params['description'] . ' (page id:' . $params['contributionPageID'] . ')';
345 $this->_setParam('comments', $comment);
347 // set the currency to the default which can be overrided.
348 $this->_setParam('currency', CRM_Core_Config
::singleton()->defaultCurrency
);
350 // Format the expiry date to MMYY
351 $expmonth = (string) $params['month'];
352 $expmonth = (strlen($expmonth) === 1) ?
'0' . $expmonth : $expmonth;
353 $expyear = substr((string) $params['year'], 2, 2);
354 $this->_setParam('exp_date', $expmonth . $expyear);
356 if (isset($params['credit_card_start_date']) && (strlen($params['credit_card_start_date']['M']) !== 0) &&
357 (strlen($params['credit_card_start_date']['Y']) !== 0)
359 $startmonth = (string) $params['credit_card_start_date']['M'];
360 $startmonth = (strlen($startmonth) === 1) ?
'0' . $startmonth : $startmonth;
361 $startyear = substr((string) $params['credit_card_start_date']['Y'], 2, 2);
362 $this->_setParam('start_date', $startmonth . $startyear);
366 $timestamp = date('YmdHis');
367 $this->_setParam('timestamp', $timestamp);
371 * Get the value of a field if set.
373 * @param string $field
377 * value of the field, or empty string if the field is
380 public function _getParam($field) {
381 if (isset($this->_params
[$field])) {
382 return $this->_params
[$field];
388 * Set a field to the specified value. Value must be a scalar (int,
389 * float, string, or boolean)
391 * @param string $field
392 * @param mixed $value
394 public function _setParam($field, $value) {
395 if (!is_scalar($value)) {
398 $this->_params
[$field] = $value;
402 * This function checks to see if we have the right config values.
405 * the error message if any
407 public function checkConfig() {
409 if (empty($this->_paymentProcessor
['user_name'])) {
410 $error[] = ts('Merchant ID is not set for this payment processor');
413 if (empty($this->_paymentProcessor
['password'])) {
414 $error[] = ts('Secret is not set for this payment processor');
417 if (!empty($error)) {
418 return implode('<p>', $error);
424 * Get the error to display.
426 * @param string $errorCode
427 * @param string $errorMessage
431 protected function getDisplayError($errorCode, $errorMessage): string {
432 if ($errorCode === '101' ||
$errorCode === '102') {
433 $display_error = ts('Card declined by bank. Please try with a different card.');
435 elseif ($errorCode === '103') {
436 $display_error = ts('Card reported lost or stolen. This incident will be reported.');
438 elseif ($errorCode === '501') {
439 $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.');
441 elseif ($errorCode === '509') {
442 $display_error = $errorMessage;
445 $display_error = ts('We were unable to process your payment at this time. Please try again later.');
447 return $display_error;