Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
Authorizenet.php
Go to the documentation of this file.
1 <?php
7 
9 use Magento\Framework\HTTP\ZendClientFactory;
10 
16 abstract class Authorizenet extends \Magento\Payment\Model\Method\Cc
17 {
21  const CGI_URL = 'https://secure.authorize.net/gateway/transact.dll';
22 
23  const REQUEST_METHOD_CC = 'CC';
24 
25  const REQUEST_TYPE_AUTH_CAPTURE = 'AUTH_CAPTURE';
26 
27  const REQUEST_TYPE_AUTH_ONLY = 'AUTH_ONLY';
28 
29  const REQUEST_TYPE_CAPTURE_ONLY = 'CAPTURE_ONLY';
30 
31  const REQUEST_TYPE_CREDIT = 'CREDIT';
32 
33  const REQUEST_TYPE_VOID = 'VOID';
34 
35  const REQUEST_TYPE_PRIOR_AUTH_CAPTURE = 'PRIOR_AUTH_CAPTURE';
36 
37  const RESPONSE_DELIM_CHAR = '(~)';
38 
40 
42 
44 
45  const RESPONSE_CODE_HELD = 4;
46 
48 
50 
52 
54 
58  const TRANSACTION_FRAUD_STATE_KEY = 'is_transaction_fraud';
59 
63  const REAL_TRANSACTION_ID_KEY = 'real_transaction_id';
64 
68  const GATEWAY_ACTIONS_LOCKED_STATE_KEY = 'is_gateway_actions_locked';
69 
73  protected $dataHelper;
74 
80  protected $requestFactory;
81 
87  protected $responseFactory;
88 
93 
99  protected $_debugReplacePrivateDataKeys = ['merchantAuthentication', 'x_login'];
100 
105 
126  public function __construct(
127  \Magento\Framework\Model\Context $context,
128  \Magento\Framework\Registry $registry,
129  \Magento\Framework\Api\ExtensionAttributesFactory $extensionFactory,
130  \Magento\Framework\Api\AttributeValueFactory $customAttributeFactory,
131  \Magento\Payment\Helper\Data $paymentData,
132  \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
133  \Magento\Payment\Model\Method\Logger $logger,
134  \Magento\Framework\Module\ModuleListInterface $moduleList,
135  \Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate,
140  ZendClientFactory $httpClientFactory,
141  \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null,
142  \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null,
143  array $data = []
144  ) {
145  $this->dataHelper = $dataHelper;
146  $this->requestFactory = $requestFactory;
147  $this->responseFactory = $responseFactory;
148  $this->transactionService = $transactionService;
149  $this->httpClientFactory = $httpClientFactory;
150 
151  parent::__construct(
152  $context,
153  $registry,
154  $extensionFactory,
155  $customAttributeFactory,
156  $paymentData,
157  $scopeConfig,
158  $logger,
159  $moduleList,
160  $localeDate,
161  $resource,
162  $resourceCollection,
163  $data
164  );
165  }
166 
173  public function canUseForCurrency($currencyCode)
174  {
175  if (!in_array($currencyCode, $this->getAcceptedCurrencyCodes())) {
176  return false;
177  }
178  return true;
179  }
180 
186  public function getAcceptedCurrencyCodes()
187  {
188  if (!$this->hasData('_accepted_currency')) {
189  $acceptedCurrencyCodes = $this->dataHelper->getAllowedCurrencyCodes();
190  $acceptedCurrencyCodes[] = $this->getConfigData('currency');
191  $this->setData('_accepted_currency', $acceptedCurrencyCodes);
192  }
193  return $this->_getData('_accepted_currency');
194  }
195 
202  public function cancel(\Magento\Payment\Model\InfoInterface $payment)
203  {
204  return $this->void($payment);
205  }
206 
214  public function fetchTransactionFraudDetails($transactionId)
215  {
216  $responseXmlDocument = $this->transactionService->getTransactionDetails($this, $transactionId);
217  $response = new \Magento\Framework\DataObject();
218 
219  if (empty($responseXmlDocument->transaction->FDSFilters->FDSFilter)) {
220  return $response;
221  }
222 
223  $response->setFdsFilterAction(
224  $this->dataHelper->getFdsFilterActionLabel((string)$responseXmlDocument->transaction->FDSFilterAction)
225  );
226  $response->setAvsResponse((string)$responseXmlDocument->transaction->AVSResponse);
227  $response->setCardCodeResponse((string)$responseXmlDocument->transaction->cardCodeResponse);
228  $response->setCavvResponse((string)$responseXmlDocument->transaction->CAVVResponse);
229  $response->setFraudFilters($this->getFraudFilters($responseXmlDocument->transaction->FDSFilters));
230 
231  return $response;
232  }
233 
240  protected function getFraudFilters($fraudFilters)
241  {
242  $result = [];
243 
244  foreach ($fraudFilters->FDSFilter as $filer) {
245  $result[] = [
246  'name' => (string)$filer->name,
247  'action' => $this->dataHelper->getFdsFilterActionLabel((string)$filer->action)
248  ];
249  }
250 
251  return $result;
252  }
253 
259  protected function getRequest()
260  {
261  $request = $this->requestFactory->create()
262  ->setXVersion(3.1)
263  ->setXDelimData('True')
264  ->setXRelayResponse('False')
265  ->setXTestRequest($this->getConfigData('test') ? 'TRUE' : 'FALSE')
266  ->setXLogin($this->getConfigData('login'))
267  ->setXTranKey($this->getConfigData('trans_key'));
268  return $request;
269  }
270 
281  protected function buildRequest(\Magento\Framework\DataObject $payment)
282  {
284  $order = $payment->getOrder();
285  $this->setStore($order->getStoreId());
286  $request = $this->getRequest()
287  ->setXType($payment->getAnetTransType())
288  ->setXMethod(self::REQUEST_METHOD_CC);
289 
290  if ($order && $order->getIncrementId()) {
291  $request->setXInvoiceNum($order->getIncrementId());
292  }
293 
294  if ($payment->getAmount()) {
295  $request->setXAmount($payment->getAmount(), 2);
296  $request->setXCurrencyCode($order->getBaseCurrencyCode());
297  }
298 
299  switch ($payment->getAnetTransType()) {
301  $request->setXAllowPartialAuth($this->getConfigData('allow_partial_authorization') ? 'True' : 'False');
302  break;
304  $request->setXAllowPartialAuth($this->getConfigData('allow_partial_authorization') ? 'True' : 'False');
305  break;
311  $request->setXCardNum($payment->getCcLast4());
312  $request->setXTransId($payment->getXTransId());
313  break;
315  $request->setXTransId($payment->getXTransId());
316  break;
318  $request->setXTransId($payment->getXTransId());
319  break;
321  $request->setXAuthCode($payment->getCcAuthCode());
322  break;
323  }
324 
325  if (!empty($order)) {
326  $billing = $order->getBillingAddress();
327  if (!empty($billing)) {
328  $request->setXFirstName($billing->getFirstname())
329  ->setXLastName($billing->getLastname())
330  ->setXCompany($billing->getCompany())
331  ->setXAddress($billing->getStreetLine(1))
332  ->setXCity($billing->getCity())
333  ->setXState($billing->getRegion())
334  ->setXZip($billing->getPostcode())
335  ->setXCountry($billing->getCountryId())
336  ->setXPhone($billing->getTelephone())
337  ->setXFax($billing->getFax())
338  ->setXCustId($order->getCustomerId())
339  ->setXCustomerIp($order->getRemoteIp())
340  ->setXCustomerTaxId($billing->getTaxId())
341  ->setXEmail($order->getCustomerEmail())
342  ->setXEmailCustomer($this->getConfigData('email_customer'))
343  ->setXMerchantEmail($this->getConfigData('merchant_email'));
344  }
345 
346  $shipping = $order->getShippingAddress();
347  if (!empty($shipping)) {
348  $request->setXShipToFirstName($shipping->getFirstname())
349  ->setXShipToLastName($shipping->getLastname())
350  ->setXShipToCompany($shipping->getCompany())
351  ->setXShipToAddress($shipping->getStreetLine(1))
352  ->setXShipToCity($shipping->getCity())
353  ->setXShipToState($shipping->getRegion())
354  ->setXShipToZip($shipping->getPostcode())
355  ->setXShipToCountry($shipping->getCountryId());
356  }
357 
358  $request->setXPoNum($payment->getPoNumber())
359  ->setXTax($order->getBaseTaxAmount())
360  ->setXFreight($order->getBaseShippingAmount());
361  }
362 
363  if ($payment->getCcNumber()) {
364  $request->setXCardNum($payment->getCcNumber())
365  ->setXExpDate(sprintf('%02d-%04d', $payment->getCcExpMonth(), $payment->getCcExpYear()))
366  ->setXCardCode($payment->getCcCid());
367  }
368 
369  return $request;
370  }
371 
379  protected function postRequest(\Magento\Authorizenet\Model\Request $request)
380  {
381  $result = $this->responseFactory->create();
383  $client = $this->httpClientFactory->create();
384  $url = $this->getConfigData('cgi_url') ?: self::CGI_URL;
385  $debugData = ['url' => $url, 'request' => $request->getData()];
386  $client->setUri($url);
387  $client->setConfig(['maxredirects' => 0, 'timeout' => 30]);
388 
389  foreach ($request->getData() as $key => $value) {
390  $request->setData($key, str_replace(self::RESPONSE_DELIM_CHAR, '', $value));
391  }
392 
393  $request->setXDelimChar(self::RESPONSE_DELIM_CHAR);
394  $client->setParameterPost($request->getData());
395  $client->setMethod(\Zend_Http_Client::POST);
396 
397  try {
398  $response = $client->request();
399  $responseBody = $response->getBody();
400  $debugData['response'] = $responseBody;
401  } catch (\Exception $e) {
402  $result->setXResponseCode(-1)
403  ->setXResponseReasonCode($e->getCode())
404  ->setXResponseReasonText($e->getMessage());
405 
406  throw new \Magento\Framework\Exception\LocalizedException(
407  $this->dataHelper->wrapGatewayError($e->getMessage())
408  );
409  } finally {
410  $this->_debug($debugData);
411  }
412 
413  $r = explode(self::RESPONSE_DELIM_CHAR, $responseBody);
414  if ($r) {
415  $result->setXResponseCode((int)str_replace('"', '', $r[0]))
416  ->setXResponseReasonCode((int)str_replace('"', '', $r[2]))
417  ->setXResponseReasonText($r[3])
418  ->setXAvsCode($r[5])
419  ->setXTransId($r[6])
420  ->setXInvoiceNum($r[7])
421  ->setXAmount($r[9])
422  ->setXMethod($r[10])
423  ->setXType($r[11])
424  ->setData('x_MD5_Hash', $r[37])
425  ->setXAccountNumber($r[50]);
426  } else {
427  throw new \Magento\Framework\Exception\LocalizedException(
428  __('Something went wrong in the payment gateway.')
429  );
430  }
431  return $result;
432  }
433 
440  protected function isGatewayActionsLocked($payment)
441  {
442  return $payment->getAdditionalInformation(self::GATEWAY_ACTIONS_LOCKED_STATE_KEY);
443  }
444 }
$response
Definition: 404.php:11
$order
Definition: order.php:55
__()
Definition: __.php:13
$resource
Definition: bulk.php:12
$logger
$payment
Definition: order.php:17
$value
Definition: gender.phtml:16
cancel(\Magento\Payment\Model\InfoInterface $payment)
__construct(\Magento\Framework\Model\Context $context, \Magento\Framework\Registry $registry, \Magento\Framework\Api\ExtensionAttributesFactory $extensionFactory, \Magento\Framework\Api\AttributeValueFactory $customAttributeFactory, \Magento\Payment\Helper\Data $paymentData, \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig, \Magento\Payment\Model\Method\Logger $logger, \Magento\Framework\Module\ModuleListInterface $moduleList, \Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate, \Magento\Authorizenet\Helper\Data $dataHelper, \Magento\Authorizenet\Model\Request\Factory $requestFactory, \Magento\Authorizenet\Model\Response\Factory $responseFactory, TransactionService $transactionService, ZendClientFactory $httpClientFactory, \Magento\Framework\Model\ResourceModel\AbstractResource $resource=null, \Magento\Framework\Data\Collection\AbstractDb $resourceCollection=null, array $data=[])