Merge pull request #18057 from eileenmcnaughton/single
[civicrm-core.git] / CRM / Core / Payment / AuthorizeNet.php
CommitLineData
6a488035
TO
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
4ae44cc6
RLAR
16use Civi\Payment\Exception\PaymentProcessorException;
17
c866eb5f
TO
18/**
19 * NOTE:
6a488035
TO
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 */
23class CRM_Core_Payment_AuthorizeNet extends CRM_Core_Payment {
7da04cde
TO
24 const CHARSET = 'iso-8859-1';
25 const AUTH_APPROVED = 1;
26 const AUTH_DECLINED = 2;
27 const AUTH_ERROR = 3;
16106615 28 const AUTH_REVIEW = 4;
7da04cde 29 const TIMEZONE = 'America/Denver';
6a488035
TO
30
31 protected $_mode = NULL;
32
be2fb01f 33 protected $_params = [];
6a488035 34
9fa25593 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
6a488035 54 /**
fe482240 55 * Constructor.
6a488035 56 *
6a0b768e
TO
57 * @param string $mode
58 * The mode of operation: live or test.
6a488035 59 *
77b97be7
EM
60 * @param $paymentProcessor
61 *
62 * @return \CRM_Core_Payment_AuthorizeNet
6a488035 63 */
00be9182 64 public function __construct($mode, &$paymentProcessor) {
6a488035
TO
65 $this->_mode = $mode;
66 $this->_paymentProcessor = $paymentProcessor;
6a488035 67
6a488035
TO
68 $this->_setParam('apiLogin', $paymentProcessor['user_name']);
69 $this->_setParam('paymentKey', $paymentProcessor['password']);
70 $this->_setParam('paymentType', 'AIM');
524cd99e 71 $this->_setParam('md5Hash', $paymentProcessor['signature'] ?? NULL);
6a488035 72
6a488035
TO
73 $this->_setParam('timestamp', time());
74 srand(time());
75 $this->_setParam('sequence', rand(1, 1000));
76 }
77
fbcb6fba 78 /**
d09edf64 79 * Should the first payment date be configurable when setting up back office recurring payments.
fbcb6fba
EM
80 * In the case of Authorize.net this is an option
81 * @return bool
82 */
d8ce0d68 83 protected function supportsFutureRecurStartDate() {
fbcb6fba
EM
84 return TRUE;
85 }
86
677fe56c
EM
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
6a488035 103 /**
fe482240 104 * Submit a payment using Advanced Integration Method.
6a488035 105 *
6a0b768e
TO
106 * @param array $params
107 * Assoc array of input parameters for this transaction.
6a488035 108 *
a6c01b45
CW
109 * @return array
110 * the result in a nice formatted array (or an error object)
9fa25593 111 *
112 * @throws \Civi\Payment\Exception\PaymentProcessorException
6a488035 113 */
00be9182 114 public function doDirectPayment(&$params) {
6a488035 115 if (!defined('CURLOPT_SSLCERT')) {
5aa04455 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);
6a488035
TO
119 }
120
121 /*
b44e3f84 122 * recurpayment function does not compile an array & then process it -
6a488035
TO
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;
cd125a40 127 if (!empty($params['is_recur']) && !empty($params['contributionRecurID'])) {
6a488035
TO
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
cd125a40 137 if (!empty($params['is_recur']) && !empty($params['contributionRecurID'])) {
2edc95e6 138 $this->doRecurPayment();
6a488035
TO
139 return $params;
140 }
141
be2fb01f 142 $postFields = [];
6a488035
TO
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
d253aeb8 159 if ($this->checkDupe($authorizeNetFields['x_invoice_num'], CRM_Utils_Array::value('contributionID', $params))) {
39fef483 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);
6a488035
TO
161 }
162
5aa04455 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();
6a488035
TO
170
171 $response_fields = $this->explode_csv($response);
48e3da59 172
173 // fetch available contribution statuses
174 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
175
6a488035
TO
176 // check for application errors
177 // TODO:
178 // AVS, CVV2, CAVV, and other verification results
16106615 179 switch ($response_fields[0]) {
d167bea8 180 case self::AUTH_REVIEW:
16106615 181 $params['payment_status_id'] = array_search('Pending', $contributionStatus);
182 break;
183
d167bea8 184 case self::AUTH_ERROR:
16106615 185 $params['payment_status_id'] = array_search('Failed', $contributionStatus);
d15a29b5 186 $errormsg = $response_fields[2] . ' ' . $response_fields[3];
39fef483 187 throw new PaymentProcessorException($errormsg, $response_fields[1]);
16106615 188
d167bea8 189 case self::AUTH_DECLINED:
16106615 190 $errormsg = $response_fields[2] . ' ' . $response_fields[3];
39fef483 191 throw new PaymentProcessorException($errormsg, $response_fields[1]);
16106615 192
193 default:
194 // Success
524cd99e 195 $params['trxn_id'] = !empty($response_fields[6]) ? $response_fields[6] : $this->getTestTrxnID();
16106615 196 $params['gross_amount'] = $response_fields[9];
197 break;
6a488035 198 }
524cd99e 199
6a488035
TO
200 // TODO: include authorization code?
201
202 return $params;
203 }
204
205 /**
fe482240 206 * Submit an Automated Recurring Billing subscription.
6a488035 207 */
00be9182 208 public function doRecurPayment() {
6a488035
TO
209 $template = CRM_Core_Smarty::singleton();
210
211 $intervalLength = $this->_getParam('frequency_interval');
212 $intervalUnit = $this->_getParam('frequency_unit');
2edc95e6 213 if ($intervalUnit === 'week') {
6a488035
TO
214 $intervalLength *= 7;
215 $intervalUnit = 'days';
216 }
2edc95e6 217 elseif ($intervalUnit === 'year') {
6a488035
TO
218 $intervalLength *= 12;
219 $intervalUnit = 'months';
220 }
31c873bf 221 elseif ($intervalUnit === 'day') {
6a488035 222 $intervalUnit = 'days';
2edc95e6 223 // interval cannot be less than 7 days or more than 1 year
6a488035 224 if ($intervalLength < 7) {
2edc95e6 225 throw new PaymentProcessorException('Payment interval must be at least one week', 9001);
6a488035 226 }
2edc95e6 227 if ($intervalLength > 365) {
228 throw new PaymentProcessorException('Payment interval may not be longer than one year', 9001);
6a488035
TO
229 }
230 }
2edc95e6 231 elseif ($intervalUnit === 'month') {
232 $intervalUnit = 'months';
6a488035 233 if ($intervalLength < 1) {
2edc95e6 234 throw new PaymentProcessorException('Payment interval must be at least one week', 9001);
6a488035 235 }
2edc95e6 236 if ($intervalLength > 12) {
237 throw new PaymentProcessorException('Payment interval may not be longer than one year', 9001);
6a488035
TO
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));
9b873358 266 if (strtotime($startDate->format('Y-m-d')) < strtotime($minDate->format('Y-m-d'))) {
6a488035
TO
267 $startDate->setTimezone(new DateTimeZone(self::TIMEZONE));
268 }
269
481a74f4 270 $template->assign('startDate', $startDate->format('Y-m-d'));
a2dd09cc 271
6a488035 272 $installments = $this->_getParam('installments');
a2dd09cc
DL
273
274 // for open ended subscription totalOccurrences has to be 9999
275 $installments = empty($installments) ? 9999 : $installments;
276 $template->assign('totalOccurrences', $installments);
6a488035
TO
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');
6a488035 299
9fa25593 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') {
884a213d 314 throw new PaymentProcessorException($responseFields['text'], $responseFields['code']);
6a488035
TO
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
a7488080 323 if (!empty($responseFields['subscriptionId'])) {
6a488035
TO
324 $this->_setParam('subscriptionId', $responseFields['subscriptionId']);
325 }
326 }
327
6c786a9b
EM
328 /**
329 * @return array
330 */
00be9182 331 public function _getAuthorizeNetFields() {
518fa0ee
SL
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)) {
6a488035
TO
336 $amount = $this->_getParam('amount');
337 }
be2fb01f 338 $fields = [];
6a488035
TO
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');
5bd23b41 351 $fields['x_invoice_num'] = $this->_getParam('invoiceID');
353ffa53 352 $fields['x_amount'] = $amount;
6a488035
TO
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
6a488035
TO
377 /**
378 * Generate HMAC_MD5
379 *
380 * @param string $key
381 * @param string $data
382 *
a6c01b45
CW
383 * @return string
384 * the HMAC_MD5 encoding string
7c550ca0 385 */
00be9182 386 public function hmac($key, $data) {
6a488035
TO
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 }
353ffa53
TO
401 $key = str_pad($key, $b, chr(0x00));
402 $ipad = str_pad('', $b, chr(0x36));
403 $opad = str_pad('', $b, chr(0x5c));
6a488035
TO
404 $k_ipad = $key ^ $ipad;
405 $k_opad = $key ^ $opad;
406 return md5($k_opad . pack("H*", md5($k_ipad . $data)));
407 }
408 }
409
6a488035 410 /**
fe482240 411 * Calculate and return the transaction fingerprint.
6a488035 412 *
a6c01b45
CW
413 * @return string
414 * fingerprint
7c550ca0 415 */
00be9182 416 public function CalculateFP() {
353ffa53
TO
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');
6a488035
TO
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 *
6a0b768e
TO
431 * @param string $data
432 * A single CSV line.
6a488035 433 *
a6c01b45
CW
434 * @return array
435 * CSV fields
6a488035 436 */
00be9182 437 public function explode_csv($data) {
6a488035
TO
438 $data = trim($data);
439 //make it easier to parse fields with quotes in them
440 $data = str_replace('""', "''", $data);
be2fb01f 441 $fields = [];
6a488035
TO
442
443 while ($data != '') {
be2fb01f 444 $matches = [];
6a488035
TO
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 /**
fe482240 463 * Extract variables from returned XML.
6a488035
TO
464 *
465 * Function is from Authorize.Net sample code, and used
466 * to prevent the requirement of XML functions.
467 *
6a0b768e
TO
468 * @param string $content
469 * XML reply from Authorize.Net.
6a488035 470 *
a6c01b45
CW
471 * @return array
472 * refId, resultCode, code, text, subscriptionId
6a488035 473 */
00be9182 474 public function _parseArbReturn($content) {
353ffa53
TO
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>');
6a488035 479 $subscriptionId = $this->_substring_between($content, '<subscriptionId>', '</subscriptionId>');
be2fb01f 480 return [
6a488035
TO
481 'refId' => $refId,
482 'resultCode' => $resultCode,
483 'code' => $code,
484 'text' => $text,
485 'subscriptionId' => $subscriptionId,
be2fb01f 486 ];
6a488035
TO
487 }
488
489 /**
fe482240 490 * Helper function for _parseArbReturn.
6a488035
TO
491 *
492 * Function is from Authorize.Net sample code, and used to avoid using
493 * PHP5 XML functions
54957108 494 *
495 * @param string $haystack
496 * @param string $start
497 * @param string $end
498 *
499 * @return bool|string
6a488035 500 */
00be9182 501 public function _substring_between(&$haystack, $start, $end) {
6a488035
TO
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 /**
fe482240 513 * Get the value of a field if set.
6a488035 514 *
6a0b768e
TO
515 * @param string $field
516 * The field.
6a488035 517 *
2a6da8d7 518 * @param bool $xmlSafe
72b3a70c
CW
519 * @return mixed
520 * value of the field, or empty string if the field is
16b10e64 521 * not set
6a488035 522 */
00be9182 523 public function _getParam($field, $xmlSafe = FALSE) {
6a488035 524 $value = CRM_Utils_Array::value($field, $this->_params, '');
a2dd09cc 525 if ($xmlSafe) {
be2fb01f 526 $value = str_replace(['&', '"', "'", '<', '>'], '', $value);
a2dd09cc 527 }
6a488035
TO
528 return $value;
529 }
530
6a488035
TO
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 *
a6c01b45
CW
538 * @return bool
539 * false if value is not a scalar, true if successful
6a488035 540 */
00be9182 541 public function _setParam($field, $value) {
6a488035
TO
542 if (!is_scalar($value)) {
543 return FALSE;
544 }
545 else {
546 $this->_params[$field] = $value;
547 }
548 }
549
550 /**
fe482240 551 * This function checks to see if we have the right config values.
6a488035 552 *
a6c01b45
CW
553 * @return string
554 * the error message if any
6a488035 555 */
00be9182 556 public function checkConfig() {
be2fb01f 557 $error = [];
6a488035
TO
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
6c786a9b
EM
574 /**
575 * @return string
576 */
00be9182 577 public function accountLoginURL() {
6a488035
TO
578 return ($this->_mode == 'test') ? 'https://test.authorize.net' : 'https://authorize.net';
579 }
580
6c786a9b
EM
581 /**
582 * @param string $message
9e03a6d0 583 * @param \Civi\Payment\PropertyBag $params
6c786a9b
EM
584 *
585 * @return bool|object
884a213d 586 * @throws \Civi\Payment\Exception\PaymentProcessorException
6c786a9b 587 */
9e03a6d0 588 public function cancelSubscription(&$message = '', $params) {
6a488035
TO
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'));
9e03a6d0 595 $template->assign('subscriptionId', $params->getRecurProcessorID());
6a488035
TO
596
597 $arbXML = $template->fetch('CRM/Contribute/Form/Contribution/AuthorizeNetARB.tpl');
598
884a213d 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();
6a488035
TO
609
610 $responseFields = $this->_ParseArbReturn($response);
611 $message = "{$responseFields['code']}: {$responseFields['text']}";
612
884a213d 613 if ($responseFields['resultCode'] === 'Error') {
614 throw new PaymentProcessorException($responseFields['text'], $responseFields['code']);
6a488035
TO
615 }
616 return TRUE;
617 }
618
6c786a9b 619 /**
884a213d 620 * Update payment details at Authorize.net.
621 *
6c786a9b
EM
622 * @param string $message
623 * @param array $params
624 *
625 * @return bool|object
884a213d 626 *
627 * @throws \Civi\Payment\Exception\PaymentProcessorException
6c786a9b 628 */
be2fb01f 629 public function updateSubscriptionBillingInfo(&$message = '', $params = []) {
6a488035
TO
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
884a213d 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();
6a488035 662
884a213d 663 // submit to authorize.net
6a488035
TO
664 $responseFields = $this->_ParseArbReturn($response);
665 $message = "{$responseFields['code']}: {$responseFields['text']}";
666
884a213d 667 if ($responseFields['resultCode'] === 'Error') {
668 throw new PaymentProcessorException($responseFields['text'], $responseFields['code']);
6a488035
TO
669 }
670 return TRUE;
671 }
672
23de1ac0
EM
673 /**
674 * Process incoming notification.
675 */
9645e182 676 public function handlePaymentNotification() {
23de1ac0
EM
677 $ipnClass = new CRM_Core_Payment_AuthorizeNetIPN(array_merge($_GET, $_REQUEST));
678 $ipnClass->main();
679 }
680
6c786a9b 681 /**
884a213d 682 * Change the amount of the recurring payment.
683 *
6c786a9b
EM
684 * @param string $message
685 * @param array $params
686 *
687 * @return bool|object
884a213d 688 *
689 * @throws \Civi\Payment\Exception\PaymentProcessorException
6c786a9b 690 */
be2fb01f 691 public function changeSubscriptionAmount(&$message = '', $params = []) {
6a488035
TO
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']);
702c1203
JM
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
6a488035
TO
705 $template->assign('amount', $params['amount']);
706
707 $arbXML = $template->fetch('CRM/Contribute/Form/Contribution/AuthorizeNetARB.tpl');
708
884a213d 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();
6a488035 719
6ea16bbf 720 $responseFields = $this->_parseArbReturn($response);
6a488035
TO
721 $message = "{$responseFields['code']}: {$responseFields['text']}";
722
884a213d 723 if ($responseFields['resultCode'] === 'Error') {
4ae44cc6 724 throw new PaymentProcessorException($responseFields['text'], $responseFields['code']);
6a488035
TO
725 }
726 return TRUE;
727 }
96025800 728
524cd99e 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
6a488035 747}