Authorizenet.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. declare(strict_types=1);
  7. namespace Magento\Authorizenet\Model;
  8. use Magento\Authorizenet\Model\TransactionService;
  9. use Magento\Framework\HTTP\ZendClientFactory;
  10. /**
  11. * Model for Authorize.net payment method
  12. *
  13. * @SuppressWarnings(PHPMD.TooManyFields)
  14. * @SuppressWarnings(PHPMD.ExcessiveClassComplexity)
  15. * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
  16. * @deprecated 100.3.1 Authorize.net is removing all support for this payment method
  17. */
  18. abstract class Authorizenet extends \Magento\Payment\Model\Method\Cc
  19. {
  20. /**
  21. * AIM gateway url
  22. */
  23. const CGI_URL = 'https://secure.authorize.net/gateway/transact.dll';
  24. const REQUEST_METHOD_CC = 'CC';
  25. const REQUEST_TYPE_AUTH_CAPTURE = 'AUTH_CAPTURE';
  26. const REQUEST_TYPE_AUTH_ONLY = 'AUTH_ONLY';
  27. const REQUEST_TYPE_CAPTURE_ONLY = 'CAPTURE_ONLY';
  28. const REQUEST_TYPE_CREDIT = 'CREDIT';
  29. const REQUEST_TYPE_VOID = 'VOID';
  30. const REQUEST_TYPE_PRIOR_AUTH_CAPTURE = 'PRIOR_AUTH_CAPTURE';
  31. const RESPONSE_DELIM_CHAR = '(~)';
  32. const RESPONSE_CODE_APPROVED = 1;
  33. const RESPONSE_CODE_DECLINED = 2;
  34. const RESPONSE_CODE_ERROR = 3;
  35. const RESPONSE_CODE_HELD = 4;
  36. const RESPONSE_REASON_CODE_APPROVED = 1;
  37. const RESPONSE_REASON_CODE_PENDING_REVIEW_AUTHORIZED = 252;
  38. const RESPONSE_REASON_CODE_PENDING_REVIEW = 253;
  39. const RESPONSE_REASON_CODE_PENDING_REVIEW_DECLINED = 254;
  40. /**
  41. * Transaction fraud state key
  42. */
  43. const TRANSACTION_FRAUD_STATE_KEY = 'is_transaction_fraud';
  44. /**
  45. * Real transaction id key
  46. */
  47. const REAL_TRANSACTION_ID_KEY = 'real_transaction_id';
  48. /**
  49. * Gateway actions locked state key
  50. */
  51. const GATEWAY_ACTIONS_LOCKED_STATE_KEY = 'is_gateway_actions_locked';
  52. /**
  53. * @var \Magento\Authorizenet\Helper\Data
  54. */
  55. protected $dataHelper;
  56. /**
  57. * Request factory
  58. *
  59. * @var \Magento\Authorizenet\Model\RequestFactory
  60. */
  61. protected $requestFactory;
  62. /**
  63. * Response factory
  64. *
  65. * @var \Magento\Authorizenet\Model\ResponseFactory
  66. */
  67. protected $responseFactory;
  68. /**
  69. * @var \Magento\Authorizenet\Model\TransactionService;
  70. */
  71. protected $transactionService;
  72. /**
  73. * Fields that should be replaced in debug with '***'
  74. *
  75. * @var array
  76. */
  77. protected $_debugReplacePrivateDataKeys = ['merchantAuthentication', 'x_login'];
  78. /**
  79. * @var \Magento\Framework\HTTP\ZendClientFactory
  80. */
  81. protected $httpClientFactory;
  82. /**
  83. * @param \Magento\Framework\Model\Context $context
  84. * @param \Magento\Framework\Registry $registry
  85. * @param \Magento\Framework\Api\ExtensionAttributesFactory $extensionFactory
  86. * @param \Magento\Framework\Api\AttributeValueFactory $customAttributeFactory
  87. * @param \Magento\Payment\Helper\Data $paymentData
  88. * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
  89. * @param \Magento\Payment\Model\Method\Logger $logger
  90. * @param \Magento\Framework\Module\ModuleListInterface $moduleList
  91. * @param \Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate
  92. * @param \Magento\Authorizenet\Helper\Data $dataHelper
  93. * @param \Magento\Authorizenet\Model\Request\Factory $requestFactory
  94. * @param \Magento\Authorizenet\Model\Response\Factory $responseFactory
  95. * @param \Magento\Authorizenet\Model\TransactionService $transactionService
  96. * @param \Magento\Framework\HTTP\ZendClientFactory $httpClientFactory
  97. * @param \Magento\Framework\Model\ResourceModel\AbstractResource $resource
  98. * @param \Magento\Framework\Data\Collection\AbstractDb $resourceCollection
  99. * @param array $data
  100. * @SuppressWarnings(PHPMD.ExcessiveParameterList)
  101. */
  102. public function __construct(
  103. \Magento\Framework\Model\Context $context,
  104. \Magento\Framework\Registry $registry,
  105. \Magento\Framework\Api\ExtensionAttributesFactory $extensionFactory,
  106. \Magento\Framework\Api\AttributeValueFactory $customAttributeFactory,
  107. \Magento\Payment\Helper\Data $paymentData,
  108. \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
  109. \Magento\Payment\Model\Method\Logger $logger,
  110. \Magento\Framework\Module\ModuleListInterface $moduleList,
  111. \Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate,
  112. \Magento\Authorizenet\Helper\Data $dataHelper,
  113. \Magento\Authorizenet\Model\Request\Factory $requestFactory,
  114. \Magento\Authorizenet\Model\Response\Factory $responseFactory,
  115. TransactionService $transactionService,
  116. ZendClientFactory $httpClientFactory,
  117. \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null,
  118. \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null,
  119. array $data = []
  120. ) {
  121. $this->dataHelper = $dataHelper;
  122. $this->requestFactory = $requestFactory;
  123. $this->responseFactory = $responseFactory;
  124. $this->transactionService = $transactionService;
  125. $this->httpClientFactory = $httpClientFactory;
  126. parent::__construct(
  127. $context,
  128. $registry,
  129. $extensionFactory,
  130. $customAttributeFactory,
  131. $paymentData,
  132. $scopeConfig,
  133. $logger,
  134. $moduleList,
  135. $localeDate,
  136. $resource,
  137. $resourceCollection,
  138. $data
  139. );
  140. }
  141. /**
  142. * Check method for processing with base currency
  143. *
  144. * @param string $currencyCode
  145. * @return bool
  146. */
  147. public function canUseForCurrency($currencyCode)
  148. {
  149. if (!in_array($currencyCode, $this->getAcceptedCurrencyCodes())) {
  150. return false;
  151. }
  152. return true;
  153. }
  154. /**
  155. * Return array of currency codes supplied by Payment Gateway
  156. *
  157. * @return array
  158. */
  159. public function getAcceptedCurrencyCodes()
  160. {
  161. if (!$this->hasData('_accepted_currency')) {
  162. $acceptedCurrencyCodes = $this->dataHelper->getAllowedCurrencyCodes();
  163. $acceptedCurrencyCodes[] = $this->getConfigData('currency');
  164. $this->setData('_accepted_currency', $acceptedCurrencyCodes);
  165. }
  166. return $this->_getData('_accepted_currency');
  167. }
  168. /**
  169. * Cancel the payment through gateway
  170. *
  171. * @param \Magento\Payment\Model\InfoInterface $payment
  172. * @return $this
  173. */
  174. public function cancel(\Magento\Payment\Model\InfoInterface $payment)
  175. {
  176. return $this->void($payment);
  177. }
  178. /**
  179. * Fetch fraud details
  180. *
  181. * @param string $transactionId
  182. * @return \Magento\Framework\DataObject
  183. * @throws \Magento\Framework\Exception\LocalizedException
  184. */
  185. public function fetchTransactionFraudDetails($transactionId)
  186. {
  187. $responseXmlDocument = $this->transactionService->getTransactionDetails($this, $transactionId);
  188. $response = new \Magento\Framework\DataObject();
  189. if (empty($responseXmlDocument->transaction->FDSFilters->FDSFilter)) {
  190. return $response;
  191. }
  192. $response->setFdsFilterAction(
  193. $this->dataHelper->getFdsFilterActionLabel((string)$responseXmlDocument->transaction->FDSFilterAction)
  194. );
  195. $response->setAvsResponse((string)$responseXmlDocument->transaction->AVSResponse);
  196. $response->setCardCodeResponse((string)$responseXmlDocument->transaction->cardCodeResponse);
  197. $response->setCavvResponse((string)$responseXmlDocument->transaction->CAVVResponse);
  198. $response->setFraudFilters($this->getFraudFilters($responseXmlDocument->transaction->FDSFilters));
  199. return $response;
  200. }
  201. /**
  202. * Get fraud filters
  203. *
  204. * @param \Magento\Framework\Simplexml\Element $fraudFilters
  205. * @return array
  206. */
  207. protected function getFraudFilters($fraudFilters)
  208. {
  209. $result = [];
  210. foreach ($fraudFilters->FDSFilter as $filer) {
  211. $result[] = [
  212. 'name' => (string)$filer->name,
  213. 'action' => $this->dataHelper->getFdsFilterActionLabel((string)$filer->action)
  214. ];
  215. }
  216. return $result;
  217. }
  218. /**
  219. * Return authorize payment request
  220. *
  221. * @return \Magento\Authorizenet\Model\Request
  222. */
  223. protected function getRequest()
  224. {
  225. $request = $this->requestFactory->create()
  226. ->setXVersion(3.1)
  227. ->setXDelimData('True')
  228. ->setXRelayResponse('False')
  229. ->setXTestRequest($this->getConfigData('test') ? 'TRUE' : 'FALSE')
  230. ->setXLogin($this->getConfigData('login'))
  231. ->setXTranKey($this->getConfigData('trans_key'));
  232. return $request;
  233. }
  234. /**
  235. * Prepare request to gateway
  236. *
  237. * @param \Magento\Framework\DataObject|\Magento\Payment\Model\InfoInterface $payment
  238. * @return \Magento\Authorizenet\Model\Request
  239. * @link http://www.authorize.net/support/AIM_guide.pdf
  240. * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  241. * @SuppressWarnings(PHPMD.NPathComplexity)
  242. * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
  243. */
  244. protected function buildRequest(\Magento\Framework\DataObject $payment)
  245. {
  246. /** @var \Magento\Sales\Model\Order $order */
  247. $order = $payment->getOrder();
  248. $this->setStore($order->getStoreId());
  249. $request = $this->getRequest()
  250. ->setXType($payment->getAnetTransType())
  251. ->setXMethod(self::REQUEST_METHOD_CC);
  252. if ($order && $order->getIncrementId()) {
  253. $request->setXInvoiceNum($order->getIncrementId());
  254. }
  255. if ($payment->getAmount()) {
  256. $request->setXAmount($payment->getAmount(), 2);
  257. $request->setXCurrencyCode($order->getBaseCurrencyCode());
  258. }
  259. switch ($payment->getAnetTransType()) {
  260. case self::REQUEST_TYPE_AUTH_CAPTURE:
  261. $request->setXAllowPartialAuth($this->getConfigData('allow_partial_authorization') ? 'True' : 'False');
  262. break;
  263. case self::REQUEST_TYPE_AUTH_ONLY:
  264. $request->setXAllowPartialAuth($this->getConfigData('allow_partial_authorization') ? 'True' : 'False');
  265. break;
  266. case self::REQUEST_TYPE_CREDIT:
  267. /**
  268. * Send last 4 digits of credit card number to authorize.net
  269. * otherwise it will give an error
  270. */
  271. $request->setXCardNum($payment->getCcLast4());
  272. $request->setXTransId($payment->getXTransId());
  273. break;
  274. case self::REQUEST_TYPE_VOID:
  275. $request->setXTransId($payment->getXTransId());
  276. break;
  277. case self::REQUEST_TYPE_PRIOR_AUTH_CAPTURE:
  278. $request->setXTransId($payment->getXTransId());
  279. break;
  280. case self::REQUEST_TYPE_CAPTURE_ONLY:
  281. $request->setXAuthCode($payment->getCcAuthCode());
  282. break;
  283. }
  284. if (!empty($order)) {
  285. $billing = $order->getBillingAddress();
  286. if (!empty($billing)) {
  287. $request->setXFirstName($billing->getFirstname())
  288. ->setXLastName($billing->getLastname())
  289. ->setXCompany($billing->getCompany())
  290. ->setXAddress($billing->getStreetLine(1))
  291. ->setXCity($billing->getCity())
  292. ->setXState($billing->getRegion())
  293. ->setXZip($billing->getPostcode())
  294. ->setXCountry($billing->getCountryId())
  295. ->setXPhone($billing->getTelephone())
  296. ->setXFax($billing->getFax())
  297. ->setXCustId($order->getCustomerId())
  298. ->setXCustomerIp($order->getRemoteIp())
  299. ->setXCustomerTaxId($billing->getTaxId())
  300. ->setXEmail($order->getCustomerEmail())
  301. ->setXEmailCustomer($this->getConfigData('email_customer'))
  302. ->setXMerchantEmail($this->getConfigData('merchant_email'));
  303. }
  304. $shipping = $order->getShippingAddress();
  305. if (!empty($shipping)) {
  306. $request->setXShipToFirstName($shipping->getFirstname())
  307. ->setXShipToLastName($shipping->getLastname())
  308. ->setXShipToCompany($shipping->getCompany())
  309. ->setXShipToAddress($shipping->getStreetLine(1))
  310. ->setXShipToCity($shipping->getCity())
  311. ->setXShipToState($shipping->getRegion())
  312. ->setXShipToZip($shipping->getPostcode())
  313. ->setXShipToCountry($shipping->getCountryId());
  314. }
  315. $request->setXPoNum($payment->getPoNumber())
  316. ->setXTax($order->getBaseTaxAmount())
  317. ->setXFreight($order->getBaseShippingAmount());
  318. }
  319. if ($payment->getCcNumber()) {
  320. $request->setXCardNum($payment->getCcNumber())
  321. ->setXExpDate(sprintf('%02d-%04d', $payment->getCcExpMonth(), $payment->getCcExpYear()))
  322. ->setXCardCode($payment->getCcCid());
  323. }
  324. return $request;
  325. }
  326. /**
  327. * Post request to gateway and return response
  328. *
  329. * @param \Magento\Authorizenet\Model\Request $request
  330. * @return \Magento\Authorizenet\Model\Response
  331. * @throws \Magento\Framework\Exception\LocalizedException
  332. */
  333. protected function postRequest(\Magento\Authorizenet\Model\Request $request)
  334. {
  335. $result = $this->responseFactory->create();
  336. /** @var \Magento\Framework\HTTP\ZendClient $client */
  337. $client = $this->httpClientFactory->create();
  338. $url = $this->getConfigData('cgi_url') ?: self::CGI_URL;
  339. $debugData = ['url' => $url, 'request' => $request->getData()];
  340. $client->setUri($url);
  341. $client->setConfig(['maxredirects' => 0, 'timeout' => 30]);
  342. foreach ($request->getData() as $key => $value) {
  343. $request->setData($key, str_replace(self::RESPONSE_DELIM_CHAR, '', $value));
  344. }
  345. $request->setXDelimChar(self::RESPONSE_DELIM_CHAR);
  346. $client->setParameterPost($request->getData());
  347. $client->setMethod(\Zend_Http_Client::POST);
  348. try {
  349. $response = $client->request();
  350. $responseBody = $response->getBody();
  351. $debugData['response'] = $responseBody;
  352. } catch (\Exception $e) {
  353. $result->setXResponseCode(-1)
  354. ->setXResponseReasonCode($e->getCode())
  355. ->setXResponseReasonText($e->getMessage());
  356. throw new \Magento\Framework\Exception\LocalizedException(
  357. $this->dataHelper->wrapGatewayError($e->getMessage())
  358. );
  359. } finally {
  360. $this->_debug($debugData);
  361. }
  362. $r = explode(self::RESPONSE_DELIM_CHAR, $responseBody);
  363. if ($r) {
  364. $result->setXResponseCode((int)str_replace('"', '', $r[0]))
  365. ->setXResponseReasonCode((int)str_replace('"', '', $r[2]))
  366. ->setXResponseReasonText($r[3])
  367. ->setXAvsCode($r[5])
  368. ->setXTransId($r[6])
  369. ->setXInvoiceNum($r[7])
  370. ->setXAmount($r[9])
  371. ->setXMethod($r[10])
  372. ->setXType($r[11])
  373. ->setData('x_MD5_Hash', $r[37])
  374. ->setXAccountNumber($r[50]);
  375. } else {
  376. throw new \Magento\Framework\Exception\LocalizedException(
  377. __('Something went wrong in the payment gateway.')
  378. );
  379. }
  380. return $result;
  381. }
  382. /**
  383. * If gateway actions are locked return true
  384. *
  385. * @param \Magento\Payment\Model\InfoInterface $payment
  386. * @return bool
  387. */
  388. protected function isGatewayActionsLocked($payment)
  389. {
  390. return $payment->getAdditionalInformation(self::GATEWAY_ACTIONS_LOCKED_STATE_KEY);
  391. }
  392. }