3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
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)
38 * @author Tom Kirkpatrick <tkp@kirkdesigns.co.uk>
41 class CRM_Core_Payment_Realex
extends CRM_Core_Payment
{
42 const AUTH_APPROVED
= '00';
44 protected $_mode = NULL;
46 protected $_params = array();
49 * We only need one instance of this object. So we use the singleton
50 * pattern and cache the instance in this variable
55 static private $_singleton = NULL;
61 * The mode of operation: live or test.
63 * @param $paymentProcessor
65 * @return \CRM_Core_Payment_Realex
67 public function __construct($mode, &$paymentProcessor) {
69 $this->_paymentProcessor
= $paymentProcessor;
70 $this->_processorName
= ts('Realex');
72 $this->_setParam('merchant_ref', $paymentProcessor['user_name']);
73 $this->_setParam('secret', $paymentProcessor['password']);
74 $this->_setParam('account', $paymentProcessor['subject']);
76 $this->_setParam('emailCustomer', 'TRUE');
78 $this->_setParam('sequence', rand(1, 1000));
82 * @param array $params
86 public function setExpressCheckOut(&$params) {
87 CRM_Core_Error
::fatal(ts('This function is not implemented'));
95 public function getExpressCheckoutDetails($token) {
96 CRM_Core_Error
::fatal(ts('This function is not implemented'));
100 * @param array $params
104 public function doExpressCheckout(&$params) {
105 CRM_Core_Error
::fatal(ts('This function is not implemented'));
109 * @param array $params
113 public function doTransferCheckout(&$params) {
114 CRM_Core_Error
::fatal(ts('This function is not implemented'));
118 * Submit a payment using Advanced Integration Method
120 * @param array $params
121 * Assoc array of input parameters for this transaction.
123 * @return array the result in a nice formatted array (or an error object)
125 public function doDirectPayment(&$params) {
127 if (!defined('CURLOPT_SSLCERT')) {
128 return self
::error(9001, ts('RealAuth requires curl with SSL support'));
131 $result = $this->setRealexFields($params);
133 if ($result !== TRUE) {
137 /**********************************************************
138 * Check to see if we have a duplicate before we send
139 **********************************************************/
140 if ($this->_checkDupe($this->_getParam('order_id'))) {
141 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.'));
144 // Create sha1 hash for request
145 $hashme = "{$this->_getParam('timestamp')}.{$this->_getParam('merchant_ref')}.{$this->_getParam('order_id')}.{$this->_getParam('amount')}.{$this->_getParam('currency')}.{$this->_getParam('card_number')}";
146 $sha1hash = sha1($hashme);
147 $hashme = "$sha1hash.{$this->_getParam('secret')}";
148 $sha1hash = sha1($hashme);
150 // Generate the request xml that is send to Realex Payments.
151 $request_xml = "<request type='auth' timestamp='{$this->_getParam('timestamp')}'>
152 <merchantid>{$this->_getParam('merchant_ref')}</merchantid>
153 <account>{$this->_getParam('account')}</account>
154 <orderid>{$this->_getParam('order_id')}</orderid>
155 <amount currency='{$this->_getParam('currency')}'>{$this->_getParam('amount')}</amount>
157 <number>{$this->_getParam('card_number')}</number>
158 <expdate>{$this->_getParam('exp_date')}</expdate>
159 <type>{$this->_getParam('card_type')}</type>
160 <chname>{$this->_getParam('card_name')}</chname>
161 <issueno>{$this->_getParam('issue_number')}</issueno>
163 <number>{$this->_getParam('cvn')}</number>
167 <autosettle flag='1'/>
168 <sha1hash>$sha1hash</sha1hash>
170 <comment id='1'>{$this->_getParam('comments')}</comment>
173 <varref>{$this->_getParam('varref')}</varref>
177 /**********************************************************
178 * Send to the payment processor using cURL
179 **********************************************************/
181 $submit = curl_init($this->_paymentProcessor
['url_site']);
184 return self
::error(9002, ts('Could not initiate connection to payment gateway'));
187 curl_setopt($submit, CURLOPT_HTTPHEADER
, array('SOAPAction: ""'));
188 curl_setopt($submit, CURLOPT_RETURNTRANSFER
, 1);
189 curl_setopt($submit, CURLOPT_TIMEOUT
, 60);
190 curl_setopt($submit, CURLOPT_SSL_VERIFYPEER
, CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'verifySSL'));
191 curl_setopt($submit, CURLOPT_HEADER
, 0);
193 // take caching out of the picture
194 curl_setopt($submit, CURLOPT_FORBID_REUSE
, 1);
195 curl_setopt($submit, CURLOPT_FRESH_CONNECT
, 1);
197 // Apply the XML to our curl call
198 curl_setopt($submit, CURLOPT_POST
, 1);
199 curl_setopt($submit, CURLOPT_POSTFIELDS
, $request_xml);
201 $response_xml = curl_exec($submit);
203 if (!$response_xml) {
204 return self
::error(curl_errno($submit), curl_error($submit));
209 // Tidy up the responce xml
210 $response_xml = preg_replace("/[\s\t]/", " ", $response_xml);
211 $response_xml = preg_replace("/[\n\r]/", "", $response_xml);
213 // Parse the response xml
214 $xml_parser = xml_parser_create();
215 if (!xml_parse($xml_parser, $response_xml)) {
216 return self
::error(9003, 'XML Error');
219 $response = $this->xml_parse_into_assoc($response_xml);
220 $response = $response['#return']['RESPONSE'];
222 // Log the Realex response for debugging
223 // CRM_Core_Error::debug_var('REALEX --------- Response from Realex: ', $response, TRUE);
225 // Return an error if authentication was not successful
226 if ($response['RESULT'] !== self
::AUTH_APPROVED
) {
227 return self
::error($response['RESULT'], ' ' . $response['MESSAGE']);
230 // Check the response hash
231 $hashme = "{$this->_getParam('timestamp')}.{$this->_getParam('merchant_ref')}.{$this->_getParam('order_id')}.{$response['RESULT']}.{$response['MESSAGE']}.{$response['PASREF']}.{$response['AUTHCODE']}";
232 $sha1hash = sha1($hashme);
233 $hashme = "$sha1hash.{$this->_getParam('secret')}";
234 $sha1hash = sha1($hashme);
236 if ($response['SHA1HASH'] != $sha1hash) {
237 // FIXME: Need to actually check this - I couldn't get the
238 // hashes to match so I'm commenting out for now'
239 // return self::error( 9001, "Hash error, please report this to the webmaster" );
242 // FIXME: We are using the trxn_result_code column to store all these extra details since there
243 // seems to be nowhere else to put them. This is THE WRONG THING TO DO!
245 'authcode' => $response['AUTHCODE'],
246 'batch_id' => $response['BATCHID'],
247 'message' => $response['MESSAGE'],
248 'trxn_result_code' => $response['RESULT'],
251 $params['trxn_id'] = $response['PASREF'];
252 $params['trxn_result_code'] = serialize($extras);
253 $params['currencyID'] = $this->_getParam('currency');
254 $params['gross_amount'] = $this->_getParam('amount');
255 $params['fee_amount'] = 0;
261 * Helper function to convert XML string to multi-dimension array.
266 * @return array An array of the result with following keys:
268 public function xml_parse_into_assoc($xml) {
272 $result['#error'] = FALSE;
273 $result['#return'] = NULL;
275 $xmlparser = xml_parser_create();
276 $ret = xml_parse_into_struct($xmlparser, $xml, $input);
278 xml_parser_free($xmlparser);
281 $result['#return'] = $xml;
285 $result['#return'] = $this->_xml_parse($input);
288 $result['#error'] = ts('Error parsing XML result - error code = %1 at line %2 char %3',
290 1 => xml_get_error_code($xmlparser),
291 2 => xml_get_current_line_number($xmlparser),
292 3 => xml_get_current_column_number($xmlparser),
300 // private helper for xml_parse_into_assoc, to recusively parsing the result
307 public function _xml_parse($input, $depth = 1) {
311 foreach ($input as $data) {
312 if ($data['level'] == $depth) {
313 switch ($data['type']) {
315 $output[$data['tag']] = isset($data['value']) ?
$data['value'] : '';
323 $output[$data['tag']] = $this->_xml_parse($children, $depth +
1);
335 * Format the params from the form ready for sending to Realex. Also perform some validation
337 public function setRealexFields(&$params) {
338 if ((int) $params['amount'] <= 0) {
339 return self
::error(9001, ts('Amount must be positive'));
342 // format amount to be in smallest possible units
343 //list($bills, $pennies) = explode('.', $params['amount']);
344 $this->_setParam('amount', 100 * $params['amount']);
346 switch (strtolower($params['credit_card_type'])) {
348 $this->_setParam('card_type', 'MC');
349 $this->_setParam('requiresIssueNumber', FALSE);
353 $this->_setParam('card_type', 'VISA');
354 $this->_setParam('requiresIssueNumber', FALSE);
358 $this->_setParam('card_type', 'AMEX');
359 $this->_setParam('requiresIssueNumber', FALSE);
363 $this->_setParam('card_type', 'LASER');
364 $this->_setParam('requiresIssueNumber', FALSE);
369 case 'maestro/switch':
371 $this->_setParam('card_type', 'SWITCH');
372 $this->_setParam('requiresIssueNumber', TRUE);
376 return self
::error(9001, ts('Credit card type not supported by Realex:') . ' ' . $params['credit_card_type']);
379 // get the card holder name - cater cor customized billing forms
380 if (isset($params['cardholder_name'])) {
381 $credit_card_name = $params['cardholder_name'];
384 $credit_card_name = $params['first_name'] . " ";
385 if (!empty($params['middle_name'])) {
386 $credit_card_name .= $params['middle_name'] . " ";
388 $credit_card_name .= $params['last_name'];
391 $this->_setParam('card_name', $credit_card_name);
392 $this->_setParam('card_number', str_replace(' ', '', $params['credit_card_number']));
393 $this->_setParam('cvn', $params['cvv2']);
394 $this->_setParam('country', $params['country']);
395 $this->_setParam('post_code', $params['postal_code']);
396 $this->_setParam('order_id', $params['invoiceID']);
397 $params['issue_number'] = (isset($params['issue_number']) ?
$params['issue_number'] : '');
398 $this->_setParam('issue_number', $params['issue_number']);
399 $this->_setParam('varref', $params['contributionType_name']);
400 $comment = $params['description'] . ' (page id:' . $params['contributionPageID'] . ')';
401 $this->_setParam('comments', $comment);
402 //$this->_setParam('currency', $params['currencyID']);
404 // set the currency to the default which can be overrided.
405 $config = CRM_Core_Config
::singleton();
406 $this->_setParam('currency', $config->defaultCurrency
);
408 // Format the expiry date to MMYY
409 $expmonth = (string) $params['month'];
410 $expmonth = (strlen($expmonth) === 1) ?
'0' . $expmonth : $expmonth;
411 $expyear = substr((string) $params['year'], 2, 2);
412 $this->_setParam('exp_date', $expmonth . $expyear);
414 if (isset($params['credit_card_start_date']) && (strlen($params['credit_card_start_date']['M']) !== 0) &&
415 (strlen($params['credit_card_start_date']['Y']) !== 0)
417 $startmonth = (string) $params['credit_card_start_date']['M'];
418 $startmonth = (strlen($startmonth) === 1) ?
'0' . $startmonth : $startmonth;
419 $startyear = substr((string) $params['credit_card_start_date']['Y'], 2, 2);
420 $this->_setParam('start_date', $startmonth . $startyear);
424 $timestamp = strftime("%Y%m%d%H%M%S");
425 $this->_setParam('timestamp', $timestamp);
431 * Checks to see if invoice_id already exists in db
433 * @param int $invoiceId
436 * @return bool True if ID exists, else false
438 public function _checkDupe($invoiceId) {
439 $contribution = new CRM_Contribute_DAO_Contribution();
440 $contribution->invoice_id
= $invoiceId;
441 return $contribution->find();
445 * Get the value of a field if set
447 * @param string $field
450 * @return mixed value of the field, or empty string if the field is
453 public function _getParam($field) {
454 if (isset($this->_params
[$field])) {
455 return $this->_params
[$field];
463 * Set a field to the specified value. Value must be a scalar (int,
464 * float, string, or boolean)
466 * @param string $field
467 * @param mixed $value
469 * @return bool false if value is not a scalar, true if successful
471 public function _setParam($field, $value) {
472 if (!is_scalar($value)) {
476 $this->_params
[$field] = $value;
481 * @param null $errorCode
482 * @param null $errorMessage
486 public function &error($errorCode = NULL, $errorMessage = NULL) {
487 $e = CRM_Core_Error
::singleton();
490 if ($errorCode == '101' ||
$errorCode == '102') {
491 $display_error = ts('Card declined by bank. Please try with a different card.');
493 elseif ($errorCode == '103') {
494 $display_error = ts('Card reported lost or stolen. This incident will be reported.');
496 elseif ($errorCode == '501') {
497 $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.");
499 elseif ($errorCode == '509') {
500 $display_error = $errorMessage;
503 $display_error = ts('We were unable to process your payment at this time. Please try again later.');
505 $e->push($errorCode, 0, NULL, $display_error);
508 $e->push(9001, 0, NULL, ts('We were unable to process your payment at this time. Please try again later.'));
514 * This function checks to see if we have the right config values
516 * @return string the error message if any
518 public function checkConfig() {
520 if (empty($this->_paymentProcessor
['user_name'])) {
521 $error[] = ts('Merchant ID is not set for this payment processor');
524 if (empty($this->_paymentProcessor
['password'])) {
525 $error[] = ts('Secret is not set for this payment processor');
528 if (!empty($error)) {
529 return implode('<p>', $error);