Merge pull request #24117 from civicrm/5.52
[civicrm-core.git] / CRM / Core / Payment / Realex.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
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 +--------------------------------------------------------------------+
10 */
11
12 /*
13 * Copyright (C) 2009
14 * Licensed to CiviCRM under the Academic Free License version 3.0.
15 *
16 * Written and contributed by Kirkdesigns (http://www.kirkdesigns.co.uk)
17 */
18
19 use Civi\Payment\Exception\PaymentProcessorException;
20
21 /**
22 *
23 * @package CRM
24 * @author Tom Kirkpatrick <tkp@kirkdesigns.co.uk>
25 */
26 class CRM_Core_Payment_Realex extends CRM_Core_Payment {
27 const AUTH_APPROVED = '00';
28
29 protected $_mode;
30
31 protected $_params = [];
32
33 /**
34 * Constructor.
35 *
36 * @param string $mode
37 * The mode of operation: live or test.
38 *
39 * @param array $paymentProcessor
40 */
41 public function __construct($mode, &$paymentProcessor) {
42 $this->_mode = $mode;
43 $this->_paymentProcessor = $paymentProcessor;
44
45 $this->_setParam('merchant_ref', $paymentProcessor['user_name']);
46 $this->_setParam('secret', $paymentProcessor['password']);
47 $this->_setParam('account', $paymentProcessor['subject']);
48
49 $this->_setParam('emailCustomer', 'TRUE');
50 srand(time());
51 $this->_setParam('sequence', rand(1, 1000));
52 }
53
54 /**
55 * Submit a payment using Advanced Integration Method.
56 *
57 * @param array|PropertyBag $params
58 *
59 * @param string $component
60 *
61 * @return array
62 * Result array (containing at least the key payment_status_id)
63 *
64 * @throws \Civi\Payment\Exception\PaymentProcessorException
65 */
66 public function doPayment(&$params, $component = 'contribute') {
67 $propertyBag = \Civi\Payment\PropertyBag::cast($params);
68 $this->_component = $component;
69 $result = $this->setStatusPaymentPending([]);
70
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);
76 return $result;
77 }
78
79 if (!defined('CURLOPT_SSLCERT')) {
80 throw new PaymentProcessorException(ts('RealAuth requires curl with SSL support'), 9001);
81 }
82
83 $this->setRealexFields($params);
84
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);
90 }
91
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);
97
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>
104 <card>
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>
110 <cvn>
111 <number>{$this->_getParam('cvn')}</number>
112 <presind>1</presind>
113 </cvn>
114 </card>
115 <autosettle flag='1'/>
116 <sha1hash>$sha1hash</sha1hash>
117 <comments>
118 <comment id='1'>{$this->_getParam('comments')}</comment>
119 </comments>
120 <tssinfo>
121 <varref>{$this->_getParam('varref')}</varref>
122 </tssinfo>
123 </request>";
124
125 /**********************************************************
126 * Send to the payment processor using cURL
127 **********************************************************/
128
129 $submit = curl_init($this->_paymentProcessor['url_site']);
130
131 if (!$submit) {
132 throw new PaymentProcessorException(ts('Could not initiate connection to payment gateway'), 9002);
133 }
134
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);
140
141 // take caching out of the picture
142 curl_setopt($submit, CURLOPT_FORBID_REUSE, 1);
143 curl_setopt($submit, CURLOPT_FRESH_CONNECT, 1);
144
145 // Apply the XML to our curl call
146 curl_setopt($submit, CURLOPT_POST, 1);
147 curl_setopt($submit, CURLOPT_POSTFIELDS, $request_xml);
148
149 $response_xml = curl_exec($submit);
150
151 if (!$response_xml) {
152 throw new PaymentProcessorException(curl_error($submit), curl_errno($submit));
153 }
154
155 curl_close($submit);
156
157 // Tidy up the response xml
158 $response_xml = preg_replace("/[\s\t]/", " ", $response_xml);
159 $response_xml = preg_replace("/[\n\r]/", "", $response_xml);
160
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);
165 }
166
167 $response = $this->xml_parse_into_assoc($response_xml);
168 $response = $response['#return']['RESPONSE'];
169
170 // Log the Realex response for debugging
171 // CRM_Core_Error::debug_var('REALEX --------- Response from Realex: ', $response, TRUE);
172
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']));
176 }
177
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!
180 $extras = [
181 'authcode' => $response['AUTHCODE'],
182 'batch_id' => $response['BATCHID'],
183 'message' => $response['MESSAGE'],
184 'trxn_result_code' => $response['RESULT'],
185 ];
186
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);
192
193 return $result;
194 }
195
196 /**
197 * Helper function to convert XML string to multi-dimension array.
198 *
199 * @param string $xml
200 * an XML string.
201 *
202 * @return array
203 * An array of the result with following keys:
204 */
205 public function xml_parse_into_assoc($xml) {
206 $input = [];
207 $result = [];
208
209 $result['#error'] = FALSE;
210 $result['#return'] = NULL;
211
212 $xmlparser = xml_parser_create();
213 $ret = xml_parse_into_struct($xmlparser, $xml, $input);
214
215 xml_parser_free($xmlparser);
216
217 if (empty($input)) {
218 $result['#return'] = $xml;
219 }
220 else {
221 if ($ret > 0) {
222 $result['#return'] = $this->_xml_parse($input);
223 }
224 else {
225 $result['#error'] = ts('Error parsing XML result - error code = %1 at line %2 char %3',
226 [
227 1 => xml_get_error_code($xmlparser),
228 2 => xml_get_current_line_number($xmlparser),
229 3 => xml_get_current_column_number($xmlparser),
230 ]
231 );
232 }
233 }
234 return $result;
235 }
236
237 /**
238 * Private helper for xml_parse_into_assoc, to recursively parsing the result.
239 *
240 * @param $input
241 * @param int $depth
242 *
243 * @return array
244 */
245 public function _xml_parse($input, $depth = 1) {
246 $output = [];
247 $children = [];
248
249 foreach ($input as $data) {
250 if ($data['level'] == $depth) {
251 switch ($data['type']) {
252 case 'complete':
253 $output[$data['tag']] = $data['value'] ?? '';
254 break;
255
256 case 'open':
257 $children = [];
258 break;
259
260 case 'close':
261 $output[$data['tag']] = $this->_xml_parse($children, $depth + 1);
262 break;
263 }
264 }
265 else {
266 $children[] = $data;
267 }
268 }
269 return $output;
270 }
271
272 /**
273 * Format the params from the form ready for sending to Realex.
274 *
275 * Also perform some validation
276 *
277 * @param array $params
278 *
279 * @throws \Civi\Payment\Exception\PaymentProcessorException
280 */
281 public function setRealexFields(&$params) {
282 if ((int) $params['amount'] <= 0) {
283 throw new PaymentProcessorException(ts('Amount must be positive'), 9001);
284 }
285
286 // format amount to be in smallest possible units
287 //list($bills, $pennies) = explode('.', $params['amount']);
288 $this->_setParam('amount', 100 * $params['amount']);
289
290 switch (strtolower($params['credit_card_type'])) {
291 case 'mastercard':
292 $this->_setParam('card_type', 'MC');
293 $this->_setParam('requiresIssueNumber', FALSE);
294 break;
295
296 case 'visa':
297 $this->_setParam('card_type', 'VISA');
298 $this->_setParam('requiresIssueNumber', FALSE);
299 break;
300
301 case 'amex':
302 $this->_setParam('card_type', 'AMEX');
303 $this->_setParam('requiresIssueNumber', FALSE);
304 break;
305
306 case 'laser':
307 $this->_setParam('card_type', 'LASER');
308 $this->_setParam('requiresIssueNumber', FALSE);
309 break;
310
311 case 'maestro':
312 case 'switch':
313 case 'maestro/switch':
314 case 'solo':
315 $this->_setParam('card_type', 'SWITCH');
316 $this->_setParam('requiresIssueNumber', TRUE);
317 break;
318
319 default:
320 throw new PaymentProcessorException(ts('Credit card type not supported by Realex:') . ' ' . $params['credit_card_type'], 9001);
321 }
322
323 // get the card holder name - cater cor customized billing forms
324 if (isset($params['cardholder_name'])) {
325 $credit_card_name = $params['cardholder_name'];
326 }
327 else {
328 $credit_card_name = $params['first_name'] . " ";
329 if (!empty($params['middle_name'])) {
330 $credit_card_name .= $params['middle_name'] . " ";
331 }
332 $credit_card_name .= $params['last_name'];
333 }
334
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);
346
347 // set the currency to the default which can be overrided.
348 $this->_setParam('currency', CRM_Core_Config::singleton()->defaultCurrency);
349
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);
355
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)
358 ) {
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);
363 }
364
365 // Create timestamp
366 $timestamp = date('YmdHis');
367 $this->_setParam('timestamp', $timestamp);
368 }
369
370 /**
371 * Get the value of a field if set.
372 *
373 * @param string $field
374 * The field.
375 *
376 * @return mixed
377 * value of the field, or empty string if the field is
378 * not set
379 */
380 public function _getParam($field) {
381 if (isset($this->_params[$field])) {
382 return $this->_params[$field];
383 }
384 return '';
385 }
386
387 /**
388 * Set a field to the specified value. Value must be a scalar (int,
389 * float, string, or boolean)
390 *
391 * @param string $field
392 * @param mixed $value
393 */
394 public function _setParam($field, $value) {
395 if (!is_scalar($value)) {
396 return;
397 }
398 $this->_params[$field] = $value;
399 }
400
401 /**
402 * This function checks to see if we have the right config values.
403 *
404 * @return string
405 * the error message if any
406 */
407 public function checkConfig() {
408 $error = [];
409 if (empty($this->_paymentProcessor['user_name'])) {
410 $error[] = ts('Merchant ID is not set for this payment processor');
411 }
412
413 if (empty($this->_paymentProcessor['password'])) {
414 $error[] = ts('Secret is not set for this payment processor');
415 }
416
417 if (!empty($error)) {
418 return implode('<p>', $error);
419 }
420 return NULL;
421 }
422
423 /**
424 * Get the error to display.
425 *
426 * @param string $errorCode
427 * @param string $errorMessage
428 *
429 * @return string
430 */
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.');
434 }
435 elseif ($errorCode === '103') {
436 $display_error = ts('Card reported lost or stolen. This incident will be reported.');
437 }
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.');
440 }
441 elseif ($errorCode === '509') {
442 $display_error = $errorMessage;
443 }
444 else {
445 $display_error = ts('We were unable to process your payment at this time. Please try again later.');
446 }
447 return $display_error;
448 }
449
450 }