Merge pull request #17513 from JMAConsulting/core-1795
[civicrm-core.git] / CRM / Core / Payment / AuthorizeNet.php
1 <?php
2 /*
3 * Copyright (C) 2007
4 * Licensed to CiviCRM under the Academic Free License version 3.0.
5 *
6 * Written and contributed by Ideal Solution, LLC (http://www.idealso.com)
7 *
8 */
9
10 /**
11 *
12 * @package CRM
13 * @author Marshal Newrock <marshal@idealso.com>
14 */
15
16 use Civi\Payment\Exception\PaymentProcessorException;
17
18 /**
19 * NOTE:
20 * When looking up response codes in the Authorize.Net API, they
21 * begin at one, so always delete one from the "Position in Response"
22 */
23 class CRM_Core_Payment_AuthorizeNet extends CRM_Core_Payment {
24 const CHARSET = 'iso-8859-1';
25 const AUTH_APPROVED = 1;
26 const AUTH_DECLINED = 2;
27 const AUTH_ERROR = 3;
28 const AUTH_REVIEW = 4;
29 const TIMEZONE = 'America/Denver';
30
31 protected $_mode = NULL;
32
33 protected $_params = [];
34
35 /**
36 * @var GuzzleHttp\Client
37 */
38 protected $guzzleClient;
39
40 /**
41 * @return \GuzzleHttp\Client
42 */
43 public function getGuzzleClient(): \GuzzleHttp\Client {
44 return $this->guzzleClient ?? new \GuzzleHttp\Client();
45 }
46
47 /**
48 * @param \GuzzleHttp\Client $guzzleClient
49 */
50 public function setGuzzleClient(\GuzzleHttp\Client $guzzleClient) {
51 $this->guzzleClient = $guzzleClient;
52 }
53
54 /**
55 * Constructor.
56 *
57 * @param string $mode
58 * The mode of operation: live or test.
59 *
60 * @param $paymentProcessor
61 *
62 * @return \CRM_Core_Payment_AuthorizeNet
63 */
64 public function __construct($mode, &$paymentProcessor) {
65 $this->_mode = $mode;
66 $this->_paymentProcessor = $paymentProcessor;
67
68 $this->_setParam('apiLogin', $paymentProcessor['user_name']);
69 $this->_setParam('paymentKey', $paymentProcessor['password']);
70 $this->_setParam('paymentType', 'AIM');
71 $this->_setParam('md5Hash', $paymentProcessor['signature'] ?? NULL);
72
73 $this->_setParam('timestamp', time());
74 srand(time());
75 $this->_setParam('sequence', rand(1, 1000));
76 }
77
78 /**
79 * Should the first payment date be configurable when setting up back office recurring payments.
80 * In the case of Authorize.net this is an option
81 * @return bool
82 */
83 protected function supportsFutureRecurStartDate() {
84 return TRUE;
85 }
86
87 /**
88 * Can recurring contributions be set against pledges.
89 *
90 * In practice all processors that use the baseIPN function to finish transactions or
91 * call the completetransaction api support this by looking up previous contributions in the
92 * series and, if there is a prior contribution against a pledge, and the pledge is not complete,
93 * adding the new payment to the pledge.
94 *
95 * However, only enabling for processors it has been tested against.
96 *
97 * @return bool
98 */
99 protected function supportsRecurContributionsForPledges() {
100 return TRUE;
101 }
102
103 /**
104 * Submit a payment using Advanced Integration Method.
105 *
106 * @param array $params
107 * Assoc array of input parameters for this transaction.
108 *
109 * @return array
110 * the result in a nice formatted array (or an error object)
111 *
112 * @throws \Civi\Payment\Exception\PaymentProcessorException
113 */
114 public function doDirectPayment(&$params) {
115 if (!defined('CURLOPT_SSLCERT')) {
116 // Note that guzzle doesn't necessarily require CURL, although it prefers it. But we should leave this error
117 // here unless someone suggests it is not required since it's likely helpful.
118 throw new PaymentProcessorException('Authorize.Net requires curl with SSL support', 9001);
119 }
120
121 /*
122 * recurpayment function does not compile an array & then process it -
123 * - the tpl does the transformation so adding call to hook here
124 * & giving it a change to act on the params array
125 */
126 $newParams = $params;
127 if (!empty($params['is_recur']) && !empty($params['contributionRecurID'])) {
128 CRM_Utils_Hook::alterPaymentProcessorParams($this,
129 $params,
130 $newParams
131 );
132 }
133 foreach ($newParams as $field => $value) {
134 $this->_setParam($field, $value);
135 }
136
137 if (!empty($params['is_recur']) && !empty($params['contributionRecurID'])) {
138 $this->doRecurPayment();
139 return $params;
140 }
141
142 $postFields = [];
143 $authorizeNetFields = $this->_getAuthorizeNetFields();
144
145 // Set up our call for hook_civicrm_paymentProcessor,
146 // since we now have our parameters as assigned for the AIM back end.
147 CRM_Utils_Hook::alterPaymentProcessorParams($this,
148 $params,
149 $authorizeNetFields
150 );
151
152 foreach ($authorizeNetFields as $field => $value) {
153 // CRM-7419, since double quote is used as enclosure while doing csv parsing
154 $value = ($field == 'x_description') ? str_replace('"', "'", $value) : $value;
155 $postFields[] = $field . '=' . urlencode($value);
156 }
157
158 // Authorize.Net will not refuse duplicates, so we should check if the user already submitted this transaction
159 if ($this->checkDupe($authorizeNetFields['x_invoice_num'], CRM_Utils_Array::value('contributionID', $params))) {
160 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 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);
161 }
162
163 $response = (string) $this->getGuzzleClient()->post($this->_paymentProcessor['url_site'], [
164 'body' => implode('&', $postFields),
165 'curl' => [
166 CURLOPT_RETURNTRANSFER => TRUE,
167 CURLOPT_SSL_VERIFYPEER => Civi::settings()->get('verifySSL'),
168 ],
169 ])->getBody();
170
171 $response_fields = $this->explode_csv($response);
172
173 // fetch available contribution statuses
174 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
175
176 // check for application errors
177 // TODO:
178 // AVS, CVV2, CAVV, and other verification results
179 switch ($response_fields[0]) {
180 case self::AUTH_REVIEW:
181 $params['payment_status_id'] = array_search('Pending', $contributionStatus);
182 break;
183
184 case self::AUTH_ERROR:
185 $params['payment_status_id'] = array_search('Failed', $contributionStatus);
186 $errormsg = $response_fields[2] . ' ' . $response_fields[3];
187 throw new PaymentProcessorException($errormsg, $response_fields[1]);
188
189 case self::AUTH_DECLINED:
190 $errormsg = $response_fields[2] . ' ' . $response_fields[3];
191 throw new PaymentProcessorException($errormsg, $response_fields[1]);
192
193 default:
194 // Success
195 $params['trxn_id'] = !empty($response_fields[6]) ? $response_fields[6] : $this->getTestTrxnID();
196 $params['gross_amount'] = $response_fields[9];
197 break;
198 }
199
200 // TODO: include authorization code?
201
202 return $params;
203 }
204
205 /**
206 * Submit an Automated Recurring Billing subscription.
207 */
208 public function doRecurPayment() {
209 $template = CRM_Core_Smarty::singleton();
210
211 $intervalLength = $this->_getParam('frequency_interval');
212 $intervalUnit = $this->_getParam('frequency_unit');
213 if ($intervalUnit === 'week') {
214 $intervalLength *= 7;
215 $intervalUnit = 'days';
216 }
217 elseif ($intervalUnit === 'year') {
218 $intervalLength *= 12;
219 $intervalUnit = 'months';
220 }
221 elseif ($intervalUnit === 'day') {
222 $intervalUnit = 'days';
223 // interval cannot be less than 7 days or more than 1 year
224 if ($intervalLength < 7) {
225 throw new PaymentProcessorException('Payment interval must be at least one week', 9001);
226 }
227 if ($intervalLength > 365) {
228 throw new PaymentProcessorException('Payment interval may not be longer than one year', 9001);
229 }
230 }
231 elseif ($intervalUnit === 'month') {
232 $intervalUnit = 'months';
233 if ($intervalLength < 1) {
234 throw new PaymentProcessorException('Payment interval must be at least one week', 9001);
235 }
236 if ($intervalLength > 12) {
237 throw new PaymentProcessorException('Payment interval may not be longer than one year', 9001);
238 }
239 }
240
241 $template->assign('intervalLength', $intervalLength);
242 $template->assign('intervalUnit', $intervalUnit);
243
244 $template->assign('apiLogin', $this->_getParam('apiLogin'));
245 $template->assign('paymentKey', $this->_getParam('paymentKey'));
246 $template->assign('refId', substr($this->_getParam('invoiceID'), 0, 20));
247
248 //for recurring, carry first contribution id
249 $template->assign('invoiceNumber', $this->_getParam('contributionID'));
250 $firstPaymentDate = $this->_getParam('receive_date');
251 if (!empty($firstPaymentDate)) {
252 //allow for post dated payment if set in form
253 $startDate = date_create($firstPaymentDate);
254 }
255 else {
256 $startDate = date_create();
257 }
258 /* Format start date in Mountain Time to avoid Authorize.net error E00017
259 * we do this only if the day we are setting our start time to is LESS than the current
260 * day in mountaintime (ie. the server time of the A-net server). A.net won't accept a date
261 * earlier than the current date on it's server so if we are in PST we might need to use mountain
262 * time to bring our date forward. But if we are submitting something future dated we want
263 * the date we entered to be respected
264 */
265 $minDate = date_create('now', new DateTimeZone(self::TIMEZONE));
266 if (strtotime($startDate->format('Y-m-d')) < strtotime($minDate->format('Y-m-d'))) {
267 $startDate->setTimezone(new DateTimeZone(self::TIMEZONE));
268 }
269
270 $template->assign('startDate', $startDate->format('Y-m-d'));
271
272 $installments = $this->_getParam('installments');
273
274 // for open ended subscription totalOccurrences has to be 9999
275 $installments = empty($installments) ? 9999 : $installments;
276 $template->assign('totalOccurrences', $installments);
277
278 $template->assign('amount', $this->_getParam('amount'));
279
280 $template->assign('cardNumber', $this->_getParam('credit_card_number'));
281 $exp_month = str_pad($this->_getParam('month'), 2, '0', STR_PAD_LEFT);
282 $exp_year = $this->_getParam('year');
283 $template->assign('expirationDate', $exp_year . '-' . $exp_month);
284
285 // name rather than description is used in the tpl - see http://www.authorize.net/support/ARB_guide.pdf
286 $template->assign('name', $this->_getParam('description', TRUE));
287
288 $template->assign('email', $this->_getParam('email'));
289 $template->assign('contactID', $this->_getParam('contactID'));
290 $template->assign('billingFirstName', $this->_getParam('billing_first_name'));
291 $template->assign('billingLastName', $this->_getParam('billing_last_name'));
292 $template->assign('billingAddress', $this->_getParam('street_address', TRUE));
293 $template->assign('billingCity', $this->_getParam('city', TRUE));
294 $template->assign('billingState', $this->_getParam('state_province'));
295 $template->assign('billingZip', $this->_getParam('postal_code', TRUE));
296 $template->assign('billingCountry', $this->_getParam('country'));
297
298 $arbXML = $template->fetch('CRM/Contribute/Form/Contribution/AuthorizeNetARB.tpl');
299
300 // Submit to authorize.net
301 $response = $this->getGuzzleClient()->post($this->_paymentProcessor['url_recur'], [
302 'headers' => [
303 'Content-Type' => 'text/xml; charset=UTF8',
304 ],
305 'body' => $arbXML,
306 'curl' => [
307 CURLOPT_RETURNTRANSFER => TRUE,
308 CURLOPT_SSL_VERIFYPEER => Civi::settings()->get('verifySSL'),
309 ],
310 ]);
311 $responseFields = $this->_ParseArbReturn((string) $response->getBody());
312
313 if ($responseFields['resultCode'] === 'Error') {
314 throw new PaymentProcessorException($responseFields['text'], $responseFields['code']);
315 }
316
317 // update recur processor_id with subscriptionId
318 CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_ContributionRecur', $this->_getParam('contributionRecurID'),
319 'processor_id', $responseFields['subscriptionId']
320 );
321 //only impact of assigning this here is is can be used to cancel the subscription in an automated test
322 // if it isn't cancelled a duplicate transaction error occurs
323 if (!empty($responseFields['subscriptionId'])) {
324 $this->_setParam('subscriptionId', $responseFields['subscriptionId']);
325 }
326 }
327
328 /**
329 * @return array
330 */
331 public function _getAuthorizeNetFields() {
332 //Total amount is from the form contribution field
333 $amount = $this->_getParam('total_amount');
334 //CRM-9894 would this ever be the case??
335 if (empty($amount)) {
336 $amount = $this->_getParam('amount');
337 }
338 $fields = [];
339 $fields['x_login'] = $this->_getParam('apiLogin');
340 $fields['x_tran_key'] = $this->_getParam('paymentKey');
341 $fields['x_email_customer'] = $this->_getParam('emailCustomer');
342 $fields['x_first_name'] = $this->_getParam('billing_first_name');
343 $fields['x_last_name'] = $this->_getParam('billing_last_name');
344 $fields['x_address'] = $this->_getParam('street_address');
345 $fields['x_city'] = $this->_getParam('city');
346 $fields['x_state'] = $this->_getParam('state_province');
347 $fields['x_zip'] = $this->_getParam('postal_code');
348 $fields['x_country'] = $this->_getParam('country');
349 $fields['x_customer_ip'] = $this->_getParam('ip_address');
350 $fields['x_email'] = $this->_getParam('email');
351 $fields['x_invoice_num'] = $this->_getParam('invoiceID');
352 $fields['x_amount'] = $amount;
353 $fields['x_currency_code'] = $this->_getParam('currencyID');
354 $fields['x_description'] = $this->_getParam('description');
355 $fields['x_cust_id'] = $this->_getParam('contactID');
356 if ($this->_getParam('paymentType') == 'AIM') {
357 $fields['x_relay_response'] = 'FALSE';
358 // request response in CSV format
359 $fields['x_delim_data'] = 'TRUE';
360 $fields['x_delim_char'] = ',';
361 $fields['x_encap_char'] = '"';
362 // cc info
363 $fields['x_card_num'] = $this->_getParam('credit_card_number');
364 $fields['x_card_code'] = $this->_getParam('cvv2');
365 $exp_month = str_pad($this->_getParam('month'), 2, '0', STR_PAD_LEFT);
366 $exp_year = $this->_getParam('year');
367 $fields['x_exp_date'] = "$exp_month/$exp_year";
368 }
369
370 if ($this->_mode != 'live') {
371 $fields['x_test_request'] = 'TRUE';
372 }
373
374 return $fields;
375 }
376
377 /**
378 * Generate HMAC_MD5
379 *
380 * @param string $key
381 * @param string $data
382 *
383 * @return string
384 * the HMAC_MD5 encoding string
385 */
386 public function hmac($key, $data) {
387 if (function_exists('mhash')) {
388 // Use PHP mhash extension
389 return (bin2hex(mhash(MHASH_MD5, $data, $key)));
390 }
391 else {
392 // RFC 2104 HMAC implementation for php.
393 // Creates an md5 HMAC.
394 // Eliminates the need to install mhash to compute a HMAC
395 // Hacked by Lance Rushing
396 // byte length for md5
397 $b = 64;
398 if (strlen($key) > $b) {
399 $key = pack("H*", md5($key));
400 }
401 $key = str_pad($key, $b, chr(0x00));
402 $ipad = str_pad('', $b, chr(0x36));
403 $opad = str_pad('', $b, chr(0x5c));
404 $k_ipad = $key ^ $ipad;
405 $k_opad = $key ^ $opad;
406 return md5($k_opad . pack("H*", md5($k_ipad . $data)));
407 }
408 }
409
410 /**
411 * Calculate and return the transaction fingerprint.
412 *
413 * @return string
414 * fingerprint
415 */
416 public function CalculateFP() {
417 $x_tran_key = $this->_getParam('paymentKey');
418 $loginid = $this->_getParam('apiLogin');
419 $sequence = $this->_getParam('sequence');
420 $timestamp = $this->_getParam('timestamp');
421 $amount = $this->_getParam('amount');
422 $currency = $this->_getParam('currencyID');
423 $transaction = "$loginid^$sequence^$timestamp^$amount^$currency";
424 return $this->hmac($x_tran_key, $transaction);
425 }
426
427 /**
428 * Split a CSV file. Requires , as delimiter and " as enclosure.
429 * Based off notes from http://php.net/fgetcsv
430 *
431 * @param string $data
432 * A single CSV line.
433 *
434 * @return array
435 * CSV fields
436 */
437 public function explode_csv($data) {
438 $data = trim($data);
439 //make it easier to parse fields with quotes in them
440 $data = str_replace('""', "''", $data);
441 $fields = [];
442
443 while ($data != '') {
444 $matches = [];
445 if ($data[0] == '"') {
446 // handle quoted fields
447 preg_match('/^"(([^"]|\\")*?)",?(.*)$/', $data, $matches);
448
449 $fields[] = str_replace("''", '"', $matches[1]);
450 $data = $matches[3];
451 }
452 else {
453 preg_match('/^([^,]*),?(.*)$/', $data, $matches);
454
455 $fields[] = $matches[1];
456 $data = $matches[2];
457 }
458 }
459 return $fields;
460 }
461
462 /**
463 * Extract variables from returned XML.
464 *
465 * Function is from Authorize.Net sample code, and used
466 * to prevent the requirement of XML functions.
467 *
468 * @param string $content
469 * XML reply from Authorize.Net.
470 *
471 * @return array
472 * refId, resultCode, code, text, subscriptionId
473 */
474 public function _parseArbReturn($content) {
475 $refId = $this->_substring_between($content, '<refId>', '</refId>');
476 $resultCode = $this->_substring_between($content, '<resultCode>', '</resultCode>');
477 $code = $this->_substring_between($content, '<code>', '</code>');
478 $text = $this->_substring_between($content, '<text>', '</text>');
479 $subscriptionId = $this->_substring_between($content, '<subscriptionId>', '</subscriptionId>');
480 return [
481 'refId' => $refId,
482 'resultCode' => $resultCode,
483 'code' => $code,
484 'text' => $text,
485 'subscriptionId' => $subscriptionId,
486 ];
487 }
488
489 /**
490 * Helper function for _parseArbReturn.
491 *
492 * Function is from Authorize.Net sample code, and used to avoid using
493 * PHP5 XML functions
494 *
495 * @param string $haystack
496 * @param string $start
497 * @param string $end
498 *
499 * @return bool|string
500 */
501 public function _substring_between(&$haystack, $start, $end) {
502 if (strpos($haystack, $start) === FALSE || strpos($haystack, $end) === FALSE) {
503 return FALSE;
504 }
505 else {
506 $start_position = strpos($haystack, $start) + strlen($start);
507 $end_position = strpos($haystack, $end);
508 return substr($haystack, $start_position, $end_position - $start_position);
509 }
510 }
511
512 /**
513 * Get the value of a field if set.
514 *
515 * @param string $field
516 * The field.
517 *
518 * @param bool $xmlSafe
519 * @return mixed
520 * value of the field, or empty string if the field is
521 * not set
522 */
523 public function _getParam($field, $xmlSafe = FALSE) {
524 $value = CRM_Utils_Array::value($field, $this->_params, '');
525 if ($xmlSafe) {
526 $value = str_replace(['&', '"', "'", '<', '>'], '', $value);
527 }
528 return $value;
529 }
530
531 /**
532 * Set a field to the specified value. Value must be a scalar (int,
533 * float, string, or boolean)
534 *
535 * @param string $field
536 * @param mixed $value
537 *
538 * @return bool
539 * false if value is not a scalar, true if successful
540 */
541 public function _setParam($field, $value) {
542 if (!is_scalar($value)) {
543 return FALSE;
544 }
545 else {
546 $this->_params[$field] = $value;
547 }
548 }
549
550 /**
551 * This function checks to see if we have the right config values.
552 *
553 * @return string
554 * the error message if any
555 */
556 public function checkConfig() {
557 $error = [];
558 if (empty($this->_paymentProcessor['user_name'])) {
559 $error[] = ts('APILogin is not set for this payment processor');
560 }
561
562 if (empty($this->_paymentProcessor['password'])) {
563 $error[] = ts('Key is not set for this payment processor');
564 }
565
566 if (!empty($error)) {
567 return implode('<p>', $error);
568 }
569 else {
570 return NULL;
571 }
572 }
573
574 /**
575 * @return string
576 */
577 public function accountLoginURL() {
578 return ($this->_mode == 'test') ? 'https://test.authorize.net' : 'https://authorize.net';
579 }
580
581 /**
582 * @param string $message
583 * @param \Civi\Payment\PropertyBag $params
584 *
585 * @return bool|object
586 * @throws \Civi\Payment\Exception\PaymentProcessorException
587 */
588 public function cancelSubscription(&$message = '', $params) {
589 $template = CRM_Core_Smarty::singleton();
590
591 $template->assign('subscriptionType', 'cancel');
592
593 $template->assign('apiLogin', $this->_getParam('apiLogin'));
594 $template->assign('paymentKey', $this->_getParam('paymentKey'));
595 $template->assign('subscriptionId', $params->getRecurProcessorID());
596
597 $arbXML = $template->fetch('CRM/Contribute/Form/Contribution/AuthorizeNetARB.tpl');
598
599 $response = (string) $this->getGuzzleClient()->post($this->_paymentProcessor['url_recur'], [
600 'headers' => [
601 'Content-Type' => 'text/xml; charset=UTF8',
602 ],
603 'body' => $arbXML,
604 'curl' => [
605 CURLOPT_RETURNTRANSFER => TRUE,
606 CURLOPT_SSL_VERIFYPEER => Civi::settings()->get('verifySSL'),
607 ],
608 ])->getBody();
609
610 $responseFields = $this->_ParseArbReturn($response);
611 $message = "{$responseFields['code']}: {$responseFields['text']}";
612
613 if ($responseFields['resultCode'] === 'Error') {
614 throw new PaymentProcessorException($responseFields['text'], $responseFields['code']);
615 }
616 return TRUE;
617 }
618
619 /**
620 * Update payment details at Authorize.net.
621 *
622 * @param string $message
623 * @param array $params
624 *
625 * @return bool|object
626 *
627 * @throws \Civi\Payment\Exception\PaymentProcessorException
628 */
629 public function updateSubscriptionBillingInfo(&$message = '', $params = []) {
630 $template = CRM_Core_Smarty::singleton();
631 $template->assign('subscriptionType', 'updateBilling');
632
633 $template->assign('apiLogin', $this->_getParam('apiLogin'));
634 $template->assign('paymentKey', $this->_getParam('paymentKey'));
635 $template->assign('subscriptionId', $params['subscriptionId']);
636
637 $template->assign('cardNumber', $params['credit_card_number']);
638 $exp_month = str_pad($params['month'], 2, '0', STR_PAD_LEFT);
639 $exp_year = $params['year'];
640 $template->assign('expirationDate', $exp_year . '-' . $exp_month);
641
642 $template->assign('billingFirstName', $params['first_name']);
643 $template->assign('billingLastName', $params['last_name']);
644 $template->assign('billingAddress', $params['street_address']);
645 $template->assign('billingCity', $params['city']);
646 $template->assign('billingState', $params['state_province']);
647 $template->assign('billingZip', $params['postal_code']);
648 $template->assign('billingCountry', $params['country']);
649
650 $arbXML = $template->fetch('CRM/Contribute/Form/Contribution/AuthorizeNetARB.tpl');
651
652 $response = (string) $this->getGuzzleClient()->post($this->_paymentProcessor['url_recur'], [
653 'headers' => [
654 'Content-Type' => 'text/xml; charset=UTF8',
655 ],
656 'body' => $arbXML,
657 'curl' => [
658 CURLOPT_RETURNTRANSFER => TRUE,
659 CURLOPT_SSL_VERIFYPEER => Civi::settings()->get('verifySSL'),
660 ],
661 ])->getBody();
662
663 // submit to authorize.net
664 $responseFields = $this->_ParseArbReturn($response);
665 $message = "{$responseFields['code']}: {$responseFields['text']}";
666
667 if ($responseFields['resultCode'] === 'Error') {
668 throw new PaymentProcessorException($responseFields['text'], $responseFields['code']);
669 }
670 return TRUE;
671 }
672
673 /**
674 * Process incoming notification.
675 */
676 public static function handlePaymentNotification() {
677 $ipnClass = new CRM_Core_Payment_AuthorizeNetIPN(array_merge($_GET, $_REQUEST));
678 $ipnClass->main();
679 }
680
681 /**
682 * Change the amount of the recurring payment.
683 *
684 * @param string $message
685 * @param array $params
686 *
687 * @return bool|object
688 *
689 * @throws \Civi\Payment\Exception\PaymentProcessorException
690 */
691 public function changeSubscriptionAmount(&$message = '', $params = []) {
692 $template = CRM_Core_Smarty::singleton();
693
694 $template->assign('subscriptionType', 'update');
695
696 $template->assign('apiLogin', $this->_getParam('apiLogin'));
697 $template->assign('paymentKey', $this->_getParam('paymentKey'));
698
699 $template->assign('subscriptionId', $params['subscriptionId']);
700
701 // for open ended subscription totalOccurrences has to be 9999
702 $installments = empty($params['installments']) ? 9999 : $params['installments'];
703 $template->assign('totalOccurrences', $installments);
704
705 $template->assign('amount', $params['amount']);
706
707 $arbXML = $template->fetch('CRM/Contribute/Form/Contribution/AuthorizeNetARB.tpl');
708
709 $response = (string) $this->getGuzzleClient()->post($this->_paymentProcessor['url_recur'], [
710 'headers' => [
711 'Content-Type' => 'text/xml; charset=UTF8',
712 ],
713 'body' => $arbXML,
714 'curl' => [
715 CURLOPT_RETURNTRANSFER => TRUE,
716 CURLOPT_SSL_VERIFYPEER => Civi::settings()->get('verifySSL'),
717 ],
718 ])->getBody();
719
720 $responseFields = $this->_parseArbReturn($response);
721 $message = "{$responseFields['code']}: {$responseFields['text']}";
722
723 if ($responseFields['resultCode'] === 'Error') {
724 throw new PaymentProcessorException($responseFields['text'], $responseFields['code']);
725 }
726 return TRUE;
727 }
728
729 /**
730 * Get an appropriate test trannsaction id.
731 *
732 * @return string
733 */
734 protected function getTestTrxnID() {
735 // test mode always returns trxn_id = 0
736 // also live mode in CiviCRM with test mode set in
737 // Authorize.Net return $response_fields[6] = 0
738 // hence treat that also as test mode transaction
739 // fix for CRM-2566
740 $query = "SELECT MAX(trxn_id) FROM civicrm_contribution WHERE trxn_id RLIKE 'test[0-9]+'";
741 $trxn_id = (string) (CRM_Core_DAO::singleValueQuery($query));
742 $trxn_id = str_replace('test', '', $trxn_id);
743 $trxn_id = (int) ($trxn_id) + 1;
744 return sprintf('test%08d', $trxn_id);
745 }
746
747 }