Update return parameters on all paymentprocessors to match expected result
[civicrm-core.git] / CRM / Core / Payment / Elavon.php
1 <?php
2 /*
3 +----------------------------------------------------------------------------+
4 | Elavon (Nova) Virtual Merchant Core Payment Module for CiviCRM version 5 |
5 +----------------------------------------------------------------------------+
6 | Licensed to CiviCRM under the Academic Free License version 3.0 |
7 | |
8 | Written & Contributed by Eileen McNaughton - Nov March 2008 |
9 +----------------------------------------------------------------------------+
10 */
11
12 use Civi\Payment\Exception\PaymentProcessorException;
13
14 /**
15 * -----------------------------------------------------------------------------------------------
16 * The basic functionality of this processor is that variables from the $params object are transformed
17 * into xml. The xml is submitted to the processor's https site
18 * using curl and the response is translated back into an array using the processor's function.
19 *
20 * If an array ($params) is returned to the calling function the values from
21 * the array are merged into the calling functions array.
22 *
23 * If an result of class error is returned it is treated as a failure. No error denotes a success. Be
24 * WARY of this when coding
25 *
26 * -----------------------------------------------------------------------------------------------
27 */
28 class CRM_Core_Payment_Elavon extends CRM_Core_Payment {
29
30 /**
31 * Constructor.
32 *
33 * @param string $mode
34 * The mode of operation: live or test.
35 *
36 * @param array $paymentProcessor
37 */
38 public function __construct($mode, &$paymentProcessor) {
39 // live or test
40 $this->_mode = $mode;
41 $this->_paymentProcessor = $paymentProcessor;
42 }
43
44 /**
45 * Map fields to parameters.
46 *
47 * This function is set up and put here to make the mapping of fields
48 * from the params object as visually clear as possible for easy editing
49 *
50 * @param array $params
51 *
52 * @return array
53 */
54 public function mapProcessorFieldstoParams($params) {
55 $requestFields['ssl_first_name'] = $params['billing_first_name'];
56 $requestFields['ssl_last_name'] = $params['billing_last_name'];
57 // contact name
58 $requestFields['ssl_ship_to_first_name'] = $params['first_name'];
59 // contact name
60 $requestFields['ssl_ship_to_last_name'] = $params['last_name'];
61 $requestFields['ssl_card_number'] = $params['credit_card_number'];
62 $requestFields['ssl_amount'] = trim($params['amount']);
63 $requestFields['ssl_exp_date'] = sprintf('%02d', (int) $params['month']) . substr($params['year'], 2, 2);
64 $requestFields['ssl_cvv2cvc2'] = $params['cvv2'];
65 // CVV field passed to processor
66 $requestFields['ssl_cvv2cvc2_indicator'] = "1";
67 $requestFields['ssl_avs_address'] = $params['street_address'];
68 $requestFields['ssl_city'] = $params['city'];
69 $requestFields['ssl_state'] = $params['state_province'];
70 $requestFields['ssl_avs_zip'] = $params['postal_code'];
71 $requestFields['ssl_country'] = $params['country'];
72 $requestFields['ssl_email'] = $params['email'];
73 // 32 character string
74 $requestFields['ssl_invoice_number'] = $params['invoiceID'];
75 $requestFields['ssl_transaction_type'] = "CCSALE";
76 $requestFields['ssl_description'] = empty($params['description']) ? "backoffice payment" : $params['description'];
77 $requestFields['ssl_customer_number'] = substr($params['credit_card_number'], -4);
78 // Added two lines below to allow commercial cards to go through as per page 15 of Elavon developer guide
79 $requestFields['ssl_customer_code'] = '1111';
80 $requestFields['ssl_salestax'] = 0.0;
81 return $requestFields;
82 }
83
84 /**
85 * This function sends request and receives response from the processor.
86 *
87 * @param array|PropertyBag $params
88 *
89 * @param string $component
90 *
91 * @return array
92 * Result array (containing at least the key payment_status_id)
93 *
94 * @throws \Civi\Payment\Exception\PaymentProcessorException
95 */
96 public function doPayment(&$params, $component = 'contribute') {
97 $propertyBag = \Civi\Payment\PropertyBag::cast($params);
98 $this->_component = $component;
99 $result = $this->setStatusPaymentPending([]);
100
101 // If we have a $0 amount, skip call to processor and set payment_status to Completed.
102 // Conceivably a processor might override this - perhaps for setting up a token - but we don't
103 // have an example of that at the moment.
104 if ($propertyBag->getAmount() == 0) {
105 $result = $this->setStatusPaymentCompleted($result);
106 return $result;
107 }
108
109 if (isset($params['is_recur']) && $params['is_recur'] == TRUE) {
110 throw new CRM_Core_Exception(ts('Elavon - recurring payments not implemented'));
111 }
112
113 if (!defined('CURLOPT_SSLCERT')) {
114 throw new CRM_Core_Exception(ts('Elavon / Nova Virtual Merchant Gateway requires curl with SSL support'));
115 }
116
117 //Create the array of variables to be sent to the processor from the $params array
118 // passed into this function
119 $requestFields = $this->mapProcessorFieldstoParams($params);
120
121 // define variables for connecting with the gateway
122 $requestFields['ssl_merchant_id'] = $this->_paymentProcessor['user_name'];
123 $requestFields['ssl_user_id'] = $this->_paymentProcessor['password'] ?? NULL;
124 $requestFields['ssl_pin'] = $this->_paymentProcessor['signature'] ?? NULL;
125 $host = $this->_paymentProcessor['url_site'];
126
127 if ($this->_mode === 'test') {
128 $requestFields['ssl_test_mode'] = "TRUE";
129 }
130
131 // Allow further manipulation of the arguments via custom hooks ..
132 CRM_Utils_Hook::alterPaymentProcessorParams($this, $params, $requestFields);
133
134 // Check to see if we have a duplicate before we send
135 if ($this->checkDupe($params['invoiceID'], CRM_Utils_Array::value('contributionID', $params))) {
136 throw new PaymentProcessorException('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. 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.', 9003);
137 }
138
139 // Convert to XML using function below
140 $xml = $this->buildXML($requestFields);
141
142 // Send to the payment processor using cURL
143
144 $chHost = $host . '?xmldata=' . $xml;
145
146 $ch = curl_init($chHost);
147 if (!$ch) {
148 throw new PaymentProcessorException('Could not initiate connection to payment gateway', 9004);
149 }
150
151 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, Civi::settings()->get('verifySSL') ? 2 : 0);
152 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, Civi::settings()->get('verifySSL'));
153 // return the result on success, FALSE on failure
154 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
155 curl_setopt($ch, CURLOPT_TIMEOUT, 36000);
156 // set this for debugging -look for output in apache error log
157 //curl_setopt ($ch,CURLOPT_VERBOSE,1 );
158 // ensures any Location headers are followed
159 if (ini_get('open_basedir') == '') {
160 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
161 }
162
163 // Send the data out over the wire
164 $responseData = curl_exec($ch);
165
166 // See if we had a curl error - if so tell 'em and bail out
167 // NOTE: curl_error does not return a logical value (see its documentation), but
168 // a string, which is empty when there was no error.
169 if ((curl_errno($ch) > 0) || (strlen(curl_error($ch)) > 0)) {
170 curl_close($ch);
171 $errorNum = curl_errno($ch);
172 $errorDesc = curl_error($ch);
173
174 // Paranoia - in the unlikley event that 'curl' errno fails
175 if ($errorNum == 0) {
176 $errorNum = 9005;
177 }
178
179 // Paranoia - in the unlikley event that 'curl' error fails
180 if (strlen($errorDesc) == 0) {
181 $errorDesc = 'Connection to payment gateway failed';
182 }
183 throw new PaymentProcessorException('Curl error - ' . $errorDesc . ' Try this link for more information http://curl.haxx.se/docs/sslcerts.html', $errorNum);
184 }
185
186 // If null data returned - tell 'em and bail out
187 // NOTE: You will not necessarily get a string back, if the request failed for
188 // any reason, the return value will be the boolean false.
189 if (($responseData === FALSE) || (strlen($responseData) == 0)) {
190 curl_close($ch);
191 throw new PaymentProcessorException('Error: Connection to payment gateway failed - no data returned.', 9006);
192 }
193
194 // If gateway returned no data - tell 'em and bail out
195 if (empty($responseData)) {
196 curl_close($ch);
197 throw new PaymentProcessorException('Error: No data returned from payment gateway.', 9007);
198 }
199
200 // Success so far - close the curl and check the data
201 curl_close($ch);
202
203 // Payment successfully sent to gateway - process the response now
204
205 $processorResponse = $this->decodeXMLresponse($responseData);
206 // success in test mode returns response "APPROVED"
207 // test mode always returns trxn_id = 0
208 // fix for CRM-2566
209
210 if ($processorResponse['errorCode']) {
211 throw new PaymentProcessorException("Error: [" . $processorResponse['errorCode'] . " " . $processorResponse['errorName'] . " " . $processorResponse['errorMessage'] . '] - from payment processor', 9010);
212 }
213 if ($processorResponse['ssl_result_message'] === "APPROVED") {
214 if ($this->_mode === 'test') {
215 $query = "SELECT MAX(trxn_id) FROM civicrm_contribution WHERE trxn_id LIKE 'test%'";
216 $trxn_id = (string) CRM_Core_DAO::singleValueQuery($query);
217 $trxn_id = (int) str_replace('test', '', $trxn_id);
218 ++$trxn_id;
219 $result['trxn_id'] = sprintf('test%08d', $trxn_id);
220 return $result;
221 }
222 throw new PaymentProcessorException('Error: [approval code related to test transaction but mode was ' . $this->_mode, 9099);
223 }
224
225 // transaction failed, print the reason
226 if ($processorResponse['ssl_result_message'] !== "APPROVAL") {
227 throw new PaymentProcessorException('Error: [' . $processorResponse['ssl_result_message'] . ' ' . $processorResponse['ssl_result'] . '] - from payment processor', 9009);
228 }
229 else {
230 // Success !
231 if ($this->_mode !== 'test') {
232 // 'trxn_id' is varchar(255) field. returned value is length 37
233 $result['trxn_id'] = $processorResponse['ssl_txn_id'];
234 }
235
236 $params['trxn_result_code'] = $processorResponse['ssl_approval_code'] . "-Cvv2:" . $processorResponse['ssl_cvv2_response'] . "-avs:" . $processorResponse['ssl_avs_response'];
237 $result = $this->setStatusPaymentCompleted($result);
238
239 return $result;
240 }
241 }
242
243 /**
244 * This public function checks to see if we have the right processor config values set.
245 *
246 * NOTE: Called by Events and Contribute to check config params are set prior to trying
247 * register any credit card details
248 *
249 * @return string|null
250 * $errorMsg if any errors found - null if OK
251 *
252 */
253 public function checkConfig() {
254 $errorMsg = [];
255
256 if (empty($this->_paymentProcessor['user_name'])) {
257 $errorMsg[] = ' ' . ts('ssl_merchant_id is not set for this payment processor');
258 }
259
260 if (empty($this->_paymentProcessor['url_site'])) {
261 $errorMsg[] = ' ' . ts('URL is not set for this payment processor');
262 }
263
264 if (!empty($errorMsg)) {
265 return implode('<p>', $errorMsg);
266 }
267 return NULL;
268 }
269
270 /**
271 * @param $requestFields
272 *
273 * @return string
274 */
275 public function buildXML($requestFields) {
276 $xmlFieldLength['ssl_first_name'] = 15;
277 // credit card name
278 $xmlFieldLength['ssl_last_name'] = 15;
279 // contact name
280 $xmlFieldLength['ssl_ship_to_first_name'] = 15;
281 // contact name
282 $xmlFieldLength['ssl_ship_to_last_name'] = 15;
283 $xmlFieldLength['ssl_card_number'] = 19;
284 $xmlFieldLength['ssl_amount'] = 13;
285 $xmlFieldLength['ssl_exp_date'] = 4;
286 $xmlFieldLength['ssl_cvv2cvc2'] = 4;
287 $xmlFieldLength['ssl_cvv2cvc2_indicator'] = 1;
288 $xmlFieldLength['ssl_avs_address'] = 20;
289 $xmlFieldLength['ssl_city'] = 20;
290 $xmlFieldLength['ssl_state'] = 30;
291 $xmlFieldLength['ssl_avs_zip'] = 9;
292 $xmlFieldLength['ssl_country'] = 50;
293 $xmlFieldLength['ssl_email'] = 100;
294 // 32 character string
295 $xmlFieldLength['ssl_invoice_number'] = 25;
296 $xmlFieldLength['ssl_transaction_type'] = 20;
297 $xmlFieldLength['ssl_description'] = 255;
298 $xmlFieldLength['ssl_merchant_id'] = 15;
299 $xmlFieldLength['ssl_user_id'] = 15;
300 $xmlFieldLength['ssl_pin'] = 128;
301 $xmlFieldLength['ssl_test_mode'] = 5;
302 $xmlFieldLength['ssl_salestax'] = 10;
303 $xmlFieldLength['ssl_customer_code'] = 17;
304 $xmlFieldLength['ssl_customer_number'] = 25;
305
306 $xml = '<txn>';
307 foreach ($requestFields as $key => $value) {
308 //dev/core/966 Don't send email through the urlencode.
309 if ($key == 'ssl_email') {
310 $xml .= '<' . $key . '>' . substr($value, 0, $xmlFieldLength[$key]) . '</' . $key . '>';
311 }
312 else {
313 $xml .= '<' . $key . '>' . self::tidyStringforXML($value, $xmlFieldLength[$key]) . '</' . $key . '>';
314 }
315 }
316 $xml .= '</txn>';
317 return $xml;
318 }
319
320 /**
321 * @param $value
322 * @param $fieldlength
323 *
324 * @return string
325 */
326 public function tidyStringforXML($value, $fieldlength) {
327 // the xml is posted to a url so must not contain spaces etc. It also needs to be cut off at a certain
328 // length to match the processor's field length. The cut needs to be made after spaces etc are
329 // transformed but must not include a partial transformed character e.g. %20 must be in or out not half-way
330 $xmlString = substr(rawurlencode($value), 0, $fieldlength);
331 $lastPercent = strrpos($xmlString, '%');
332 if ($lastPercent > $fieldlength - 3) {
333 $xmlString = substr($xmlString, 0, $lastPercent);
334 }
335 return $xmlString;
336 }
337
338 /**
339 * Simple function to use in place of the 'simplexml_load_string' call.
340 *
341 * It returns the NodeValue for a given NodeName
342 * or returns an empty string.
343 *
344 * @param string $NodeName
345 * @param string $strXML
346 * @return string
347 */
348 public function GetNodeValue($NodeName, &$strXML) {
349 $OpeningNodeName = "<" . $NodeName . ">";
350 $ClosingNodeName = "</" . $NodeName . ">";
351
352 $pos1 = stripos($strXML, $OpeningNodeName);
353 $pos2 = stripos($strXML, $ClosingNodeName);
354
355 if (($pos1 === FALSE) || ($pos2 === FALSE)) {
356
357 return '';
358
359 }
360
361 $pos1 += strlen($OpeningNodeName);
362 $len = $pos2 - $pos1;
363
364 $return = substr($strXML, $pos1, $len);
365 // check out rtn values for debug
366 // echo " $NodeName &nbsp &nbsp $return <br>";
367 return ($return);
368 }
369
370 /**
371 * @param string $Xml
372 *
373 * @return mixed
374 */
375 public function decodeXMLresponse($Xml) {
376 $processorResponse = [];
377
378 $processorResponse['ssl_result'] = self::GetNodeValue("ssl_result", $Xml);
379 $processorResponse['ssl_result_message'] = self::GetNodeValue("ssl_result_message", $Xml);
380 $processorResponse['ssl_txn_id'] = self::GetNodeValue("ssl_txn_id", $Xml);
381 $processorResponse['ssl_cvv2_response'] = self::GetNodeValue("ssl_cvv2_response", $Xml);
382 $processorResponse['ssl_avs_response'] = self::GetNodeValue("ssl_avs_response", $Xml);
383 $processorResponse['ssl_approval_code'] = self::GetNodeValue("ssl_approval_code", $Xml);
384 $processorResponse['errorCode'] = self::GetNodeValue("errorCode", $Xml);
385 $processorResponse['errorName'] = self::GetNodeValue("errorName", $Xml);
386 $processorResponse['errorMessage'] = self::GetNodeValue("errorMessage", $Xml);
387
388 return $processorResponse;
389 }
390
391 }