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 $statuses = CRM_Contribute_BAO_Contribution
::buildOptions('contribution_status_id', 'validate');
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['payment_status_id'] = array_search('Completed', $statuses);
76 $result['payment_status'] = 'Completed';
80 if (!defined('CURLOPT_SSLCERT')) {
81 throw new PaymentProcessorException(ts('RealAuth requires curl with SSL support'), 9001);
84 $result = $this->setRealexFields($params);
86 /**********************************************************
87 * Check to see if we have a duplicate before we send
88 **********************************************************/
89 if ($this->checkDupe($params['invoiceID'], CRM_Utils_Array
::value('contributionID', $params))) {
90 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);
93 // Create sha1 hash for request
94 $hashme = "{$this->_getParam('timestamp')}.{$this->_getParam('merchant_ref')}.{$this->_getParam('order_id')}.{$this->_getParam('amount')}.{$this->_getParam('currency')}.{$this->_getParam('card_number')}";
95 $sha1hash = sha1($hashme);
96 $hashme = "$sha1hash.{$this->_getParam('secret')}";
97 $sha1hash = sha1($hashme);
99 // Generate the request xml that is send to Realex Payments.
100 $request_xml = "<request type='auth' timestamp='{$this->_getParam('timestamp')}'>
101 <merchantid>{$this->_getParam('merchant_ref')}</merchantid>
102 <account>{$this->_getParam('account')}</account>
103 <orderid>{$this->_getParam('order_id')}</orderid>
104 <amount currency='{$this->_getParam('currency')}'>{$this->_getParam('amount')}</amount>
106 <number>{$this->_getParam('card_number')}</number>
107 <expdate>{$this->_getParam('exp_date')}</expdate>
108 <type>{$this->_getParam('card_type')}</type>
109 <chname>{$this->_getParam('card_name')}</chname>
110 <issueno>{$this->_getParam('issue_number')}</issueno>
112 <number>{$this->_getParam('cvn')}</number>
116 <autosettle flag='1'/>
117 <sha1hash>$sha1hash</sha1hash>
119 <comment id='1'>{$this->_getParam('comments')}</comment>
122 <varref>{$this->_getParam('varref')}</varref>
126 /**********************************************************
127 * Send to the payment processor using cURL
128 **********************************************************/
130 $submit = curl_init($this->_paymentProcessor
['url_site']);
133 throw new PaymentProcessorException(ts('Could not initiate connection to payment gateway'), 9002);
136 curl_setopt($submit, CURLOPT_HTTPHEADER
, ['SOAPAction: ""']);
137 curl_setopt($submit, CURLOPT_RETURNTRANSFER
, 1);
138 curl_setopt($submit, CURLOPT_TIMEOUT
, 60);
139 curl_setopt($submit, CURLOPT_SSL_VERIFYPEER
, Civi
::settings()->get('verifySSL'));
140 curl_setopt($submit, CURLOPT_HEADER
, 0);
142 // take caching out of the picture
143 curl_setopt($submit, CURLOPT_FORBID_REUSE
, 1);
144 curl_setopt($submit, CURLOPT_FRESH_CONNECT
, 1);
146 // Apply the XML to our curl call
147 curl_setopt($submit, CURLOPT_POST
, 1);
148 curl_setopt($submit, CURLOPT_POSTFIELDS
, $request_xml);
150 $response_xml = curl_exec($submit);
152 if (!$response_xml) {
153 throw new PaymentProcessorException(curl_error($submit), curl_errno($submit));
158 // Tidy up the response xml
159 $response_xml = preg_replace("/[\s\t]/", " ", $response_xml);
160 $response_xml = preg_replace("/[\n\r]/", "", $response_xml);
162 // Parse the response xml
163 $xml_parser = xml_parser_create();
164 if (!xml_parse($xml_parser, $response_xml)) {
165 throw new PaymentProcessorException('XML Error', 9003);
168 $response = $this->xml_parse_into_assoc($response_xml);
169 $response = $response['#return']['RESPONSE'];
171 // Log the Realex response for debugging
172 // CRM_Core_Error::debug_var('REALEX --------- Response from Realex: ', $response, TRUE);
174 // Return an error if authentication was not successful
175 if ($response['RESULT'] !== self
::AUTH_APPROVED
) {
176 throw new PaymentProcessorException($this->getDisplayError($response['RESULT'], ' ' . $response['MESSAGE']));
179 // FIXME: We are using the trxn_result_code column to store all these extra details since there
180 // seems to be nowhere else to put them. This is THE WRONG THING TO DO!
182 'authcode' => $response['AUTHCODE'],
183 'batch_id' => $response['BATCHID'],
184 'message' => $response['MESSAGE'],
185 'trxn_result_code' => $response['RESULT'],
188 $params['trxn_id'] = $response['PASREF'];
189 $params['trxn_result_code'] = serialize($extras);
190 $params['currencyID'] = $this->_getParam('currency');
191 $params['fee_amount'] = 0;
192 $params['payment_status_id'] = array_search('Completed', $statuses);
193 $params['payment_status'] = 'Completed';
199 * Helper function to convert XML string to multi-dimension array.
205 * An array of the result with following keys:
207 public function xml_parse_into_assoc($xml) {
211 $result['#error'] = FALSE;
212 $result['#return'] = NULL;
214 $xmlparser = xml_parser_create();
215 $ret = xml_parse_into_struct($xmlparser, $xml, $input);
217 xml_parser_free($xmlparser);
220 $result['#return'] = $xml;
224 $result['#return'] = $this->_xml_parse($input);
227 $result['#error'] = ts('Error parsing XML result - error code = %1 at line %2 char %3',
229 1 => xml_get_error_code($xmlparser),
230 2 => xml_get_current_line_number($xmlparser),
231 3 => xml_get_current_column_number($xmlparser),
240 * Private helper for xml_parse_into_assoc, to recursively parsing the result.
247 public function _xml_parse($input, $depth = 1) {
251 foreach ($input as $data) {
252 if ($data['level'] == $depth) {
253 switch ($data['type']) {
255 $output[$data['tag']] = $data['value'] ??
'';
263 $output[$data['tag']] = $this->_xml_parse($children, $depth +
1);
275 * Format the params from the form ready for sending to Realex.
277 * Also perform some validation
279 * @param array $params
281 * @throws \Civi\Payment\Exception\PaymentProcessorException
283 public function setRealexFields(&$params) {
284 if ((int) $params['amount'] <= 0) {
285 throw new PaymentProcessorException(ts('Amount must be positive'), 9001);
288 // format amount to be in smallest possible units
289 //list($bills, $pennies) = explode('.', $params['amount']);
290 $this->_setParam('amount', 100 * $params['amount']);
292 switch (strtolower($params['credit_card_type'])) {
294 $this->_setParam('card_type', 'MC');
295 $this->_setParam('requiresIssueNumber', FALSE);
299 $this->_setParam('card_type', 'VISA');
300 $this->_setParam('requiresIssueNumber', FALSE);
304 $this->_setParam('card_type', 'AMEX');
305 $this->_setParam('requiresIssueNumber', FALSE);
309 $this->_setParam('card_type', 'LASER');
310 $this->_setParam('requiresIssueNumber', FALSE);
315 case 'maestro/switch':
317 $this->_setParam('card_type', 'SWITCH');
318 $this->_setParam('requiresIssueNumber', TRUE);
322 throw new PaymentProcessorException(ts('Credit card type not supported by Realex:') . ' ' . $params['credit_card_type'], 9001);
325 // get the card holder name - cater cor customized billing forms
326 if (isset($params['cardholder_name'])) {
327 $credit_card_name = $params['cardholder_name'];
330 $credit_card_name = $params['first_name'] . " ";
331 if (!empty($params['middle_name'])) {
332 $credit_card_name .= $params['middle_name'] . " ";
334 $credit_card_name .= $params['last_name'];
337 $this->_setParam('card_name', $credit_card_name);
338 $this->_setParam('card_number', str_replace(' ', '', $params['credit_card_number']));
339 $this->_setParam('cvn', $params['cvv2']);
340 $this->_setParam('country', $params['country']);
341 $this->_setParam('post_code', $params['postal_code']);
342 $this->_setParam('order_id', $params['invoiceID']);
343 $params['issue_number'] = ($params['issue_number'] ??
'');
344 $this->_setParam('issue_number', $params['issue_number']);
345 $this->_setParam('varref', $params['contributionType_name']);
346 $comment = $params['description'] . ' (page id:' . $params['contributionPageID'] . ')';
347 $this->_setParam('comments', $comment);
349 // set the currency to the default which can be overrided.
350 $this->_setParam('currency', CRM_Core_Config
::singleton()->defaultCurrency
);
352 // Format the expiry date to MMYY
353 $expmonth = (string) $params['month'];
354 $expmonth = (strlen($expmonth) === 1) ?
'0' . $expmonth : $expmonth;
355 $expyear = substr((string) $params['year'], 2, 2);
356 $this->_setParam('exp_date', $expmonth . $expyear);
358 if (isset($params['credit_card_start_date']) && (strlen($params['credit_card_start_date']['M']) !== 0) &&
359 (strlen($params['credit_card_start_date']['Y']) !== 0)
361 $startmonth = (string) $params['credit_card_start_date']['M'];
362 $startmonth = (strlen($startmonth) === 1) ?
'0' . $startmonth : $startmonth;
363 $startyear = substr((string) $params['credit_card_start_date']['Y'], 2, 2);
364 $this->_setParam('start_date', $startmonth . $startyear);
368 $timestamp = strftime('%Y%m%d%H%M%S');
369 $this->_setParam('timestamp', $timestamp);
373 * Get the value of a field if set.
375 * @param string $field
379 * value of the field, or empty string if the field is
382 public function _getParam($field) {
383 if (isset($this->_params
[$field])) {
384 return $this->_params
[$field];
390 * Set a field to the specified value. Value must be a scalar (int,
391 * float, string, or boolean)
393 * @param string $field
394 * @param mixed $value
396 public function _setParam($field, $value) {
397 if (!is_scalar($value)) {
400 $this->_params
[$field] = $value;
404 * This function checks to see if we have the right config values.
407 * the error message if any
409 public function checkConfig() {
411 if (empty($this->_paymentProcessor
['user_name'])) {
412 $error[] = ts('Merchant ID is not set for this payment processor');
415 if (empty($this->_paymentProcessor
['password'])) {
416 $error[] = ts('Secret is not set for this payment processor');
419 if (!empty($error)) {
420 return implode('<p>', $error);
426 * Get the error to display.
428 * @param string $errorCode
429 * @param string $errorMessage
433 protected function getDisplayError($errorCode, $errorMessage): string {
434 if ($errorCode === '101' ||
$errorCode === '102') {
435 $display_error = ts('Card declined by bank. Please try with a different card.');
437 elseif ($errorCode === '103') {
438 $display_error = ts('Card reported lost or stolen. This incident will be reported.');
440 elseif ($errorCode === '501') {
441 $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.');
443 elseif ($errorCode === '509') {
444 $display_error = $errorMessage;
447 $display_error = ts('We were unable to process your payment at this time. Please try again later.');
449 return $display_error;