AbstractApi.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659
  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\Paypal\Model\Api;
  8. use Magento\Payment\Helper\Formatter;
  9. use Magento\Payment\Model\Method\Logger;
  10. /**
  11. * Abstract class for Paypal API wrappers
  12. */
  13. abstract class AbstractApi extends \Magento\Framework\DataObject
  14. {
  15. use Formatter;
  16. /**
  17. * Config instance
  18. *
  19. * @var \Magento\Paypal\Model\Config
  20. */
  21. protected $_config;
  22. /**
  23. * Global private to public interface map
  24. * @var array
  25. */
  26. protected $_globalMap = [];
  27. /**
  28. * Filter callbacks for exporting $this data to API call
  29. *
  30. * @var array
  31. */
  32. protected $_exportToRequestFilters = [];
  33. /**
  34. * Filter callbacks for importing API result to $this data
  35. *
  36. * @var array
  37. */
  38. protected $_importFromRequestFilters = [];
  39. /**
  40. * Line items export to request mapping settings
  41. *
  42. * @var array
  43. */
  44. protected $_lineItemExportItemsFormat = [];
  45. /**
  46. * @var array
  47. */
  48. protected $_lineItemExportItemsFilters = [
  49. 'name' => 'strval'
  50. ];
  51. /**
  52. * @var array
  53. */
  54. protected $_lineItemTotalExportMap = [];
  55. /**
  56. * PayPal shopping cart instance
  57. *
  58. * @var \Magento\Paypal\Model\Cart
  59. */
  60. protected $_cart;
  61. /**
  62. * Shipping options export to request mapping settings
  63. *
  64. * @var array
  65. */
  66. protected $_shippingOptionsExportItemsFormat = [];
  67. /**
  68. * Fields that should be replaced in debug with '***'
  69. *
  70. * @var array
  71. */
  72. protected $_debugReplacePrivateDataKeys = [];
  73. /**
  74. * Customer address
  75. *
  76. * @var \Magento\Customer\Helper\Address
  77. */
  78. protected $_customerAddress;
  79. /**
  80. * @var \Psr\Log\LoggerInterface
  81. */
  82. protected $_logger;
  83. /**
  84. * @var Logger
  85. */
  86. protected $customLogger;
  87. /**
  88. * @var \Magento\Framework\Locale\ResolverInterface
  89. */
  90. protected $_localeResolver;
  91. /**
  92. * @var \Magento\Directory\Model\RegionFactory
  93. */
  94. protected $_regionFactory;
  95. /**
  96. * By default is looking for first argument as array and assigns it as object
  97. * attributes This behavior may change in child classes
  98. *
  99. * @param \Magento\Customer\Helper\Address $customerAddress
  100. * @param \Psr\Log\LoggerInterface $logger
  101. * @param Logger $customLogger
  102. * @param \Magento\Framework\Locale\ResolverInterface $localeResolver
  103. * @param \Magento\Directory\Model\RegionFactory $regionFactory
  104. * @param array $data
  105. */
  106. public function __construct(
  107. \Magento\Customer\Helper\Address $customerAddress,
  108. \Psr\Log\LoggerInterface $logger,
  109. Logger $customLogger,
  110. \Magento\Framework\Locale\ResolverInterface $localeResolver,
  111. \Magento\Directory\Model\RegionFactory $regionFactory,
  112. array $data = []
  113. ) {
  114. $this->_customerAddress = $customerAddress;
  115. $this->_logger = $logger;
  116. $this->customLogger = $customLogger;
  117. $this->_localeResolver = $localeResolver;
  118. $this->_regionFactory = $regionFactory;
  119. parent::__construct($data);
  120. }
  121. /**
  122. * Return Paypal Api user name based on config data
  123. *
  124. * @return string
  125. */
  126. public function getApiUsername()
  127. {
  128. return $this->_config->getValue('apiUsername');
  129. }
  130. /**
  131. * Return Paypal Api password based on config data
  132. *
  133. * @return string
  134. */
  135. public function getApiPassword()
  136. {
  137. return $this->_config->getValue('apiPassword');
  138. }
  139. /**
  140. * Return Paypal Api signature based on config data
  141. *
  142. * @return string
  143. */
  144. public function getApiSignature()
  145. {
  146. return $this->_config->getValue('apiSignature');
  147. }
  148. /**
  149. * Return Paypal Api certificate based on config data
  150. *
  151. * @return string
  152. */
  153. public function getApiCertificate()
  154. {
  155. return $this->_config->getApiCertificate();
  156. }
  157. /**
  158. * BN code getter
  159. *
  160. * @return string
  161. */
  162. public function getBuildNotationCode()
  163. {
  164. return $this->_config->getBuildNotationCode();
  165. }
  166. /**
  167. * Return Paypal Api proxy status based on config data
  168. *
  169. * @return bool
  170. * @SuppressWarnings(PHPMD.BooleanGetMethodName)
  171. */
  172. public function getUseProxy()
  173. {
  174. return $this->_getDataOrConfig('use_proxy', false);
  175. }
  176. /**
  177. * Return Paypal Api proxy host based on config data
  178. *
  179. * @return string
  180. */
  181. public function getProxyHost()
  182. {
  183. return $this->_getDataOrConfig('proxy_host', '127.0.0.1');
  184. }
  185. /**
  186. * Return Paypal Api proxy port based on config data
  187. *
  188. * @return string
  189. */
  190. public function getProxyPort()
  191. {
  192. return $this->_getDataOrConfig('proxy_port', '808');
  193. }
  194. /**
  195. * PayPal page CSS getter
  196. *
  197. * @return string
  198. */
  199. public function getPageStyle()
  200. {
  201. return $this->_getDataOrConfig('page_style');
  202. }
  203. /**
  204. * PayPal page header image URL getter
  205. *
  206. * @return string
  207. */
  208. public function getHdrimg()
  209. {
  210. return $this->_getDataOrConfig('paypal_hdrimg');
  211. }
  212. /**
  213. * PayPal page header border color getter
  214. *
  215. * @return string
  216. */
  217. public function getHdrbordercolor()
  218. {
  219. return $this->_getDataOrConfig('paypal_hdrbordercolor');
  220. }
  221. /**
  222. * PayPal page header background color getter
  223. *
  224. * @return string
  225. */
  226. public function getHdrbackcolor()
  227. {
  228. return $this->_getDataOrConfig('paypal_hdrbackcolor');
  229. }
  230. /**
  231. * PayPal page "payflow color" (?) getter
  232. *
  233. * @return string
  234. */
  235. public function getPayflowcolor()
  236. {
  237. return $this->_getDataOrConfig('paypal_payflowcolor');
  238. }
  239. /**
  240. * Payment action getter
  241. *
  242. * @return string
  243. */
  244. public function getPaymentAction()
  245. {
  246. return $this->_getDataOrConfig('payment_action');
  247. }
  248. /**
  249. * PayPal merchant email getter
  250. *
  251. * @return string
  252. */
  253. public function getBusinessAccount()
  254. {
  255. return $this->_getDataOrConfig('business_account');
  256. }
  257. /**
  258. * Import $this public data to specified object or array
  259. *
  260. * @param array|\Magento\Framework\DataObject $to
  261. * @param array $publicMap
  262. * @return array|\Magento\Framework\DataObject
  263. */
  264. public function import($to, array $publicMap = [])
  265. {
  266. return \Magento\Framework\DataObject\Mapper::accumulateByMap([$this, 'getDataUsingMethod'], $to, $publicMap);
  267. }
  268. /**
  269. * Export $this public data from specified object or array
  270. *
  271. * @param array|\Magento\Framework\DataObject $from
  272. * @param array $publicMap
  273. * @return $this
  274. */
  275. public function export($from, array $publicMap = [])
  276. {
  277. \Magento\Framework\DataObject\Mapper::accumulateByMap($from, [$this, 'setDataUsingMethod'], $publicMap);
  278. return $this;
  279. }
  280. /**
  281. * Set PayPal cart instance
  282. *
  283. * @param \Magento\Paypal\Model\Cart $cart
  284. * @return $this
  285. */
  286. public function setPaypalCart(\Magento\Paypal\Model\Cart $cart)
  287. {
  288. $this->_cart = $cart;
  289. return $this;
  290. }
  291. /**
  292. * Config instance setter
  293. *
  294. * @param \Magento\Paypal\Model\Config $config
  295. * @return $this
  296. */
  297. public function setConfigObject(\Magento\Paypal\Model\Config $config)
  298. {
  299. $this->_config = $config;
  300. return $this;
  301. }
  302. /**
  303. * Current locale code getter
  304. *
  305. * @return string
  306. */
  307. public function getLocale()
  308. {
  309. return $this->_localeResolver->getLocale();
  310. }
  311. /**
  312. * Always take into account
  313. *
  314. * @return int
  315. */
  316. public function getFraudManagementFiltersEnabled()
  317. {
  318. return 1;
  319. }
  320. /**
  321. * Export $this public data to private request array
  322. *
  323. * @param array $privateRequestMap
  324. * @param array $request
  325. * @return array
  326. */
  327. protected function &_exportToRequest(array $privateRequestMap, array $request = [])
  328. {
  329. $map = [];
  330. foreach ($privateRequestMap as $key) {
  331. if (isset($this->_globalMap[$key])) {
  332. $map[$this->_globalMap[$key]] = $key;
  333. }
  334. }
  335. $result = \Magento\Framework\DataObject\Mapper::accumulateByMap([$this, 'getDataUsingMethod'], $request, $map);
  336. foreach ($privateRequestMap as $key) {
  337. if (isset($this->_exportToRequestFilters[$key]) && isset($result[$key])) {
  338. $callback = $this->_exportToRequestFilters[$key];
  339. $privateKey = $result[$key];
  340. $publicKey = $map[$this->_globalMap[$key]];
  341. $result[$key] = call_user_func([$this, $callback], $privateKey, $publicKey);
  342. }
  343. }
  344. return $result;
  345. }
  346. /**
  347. * Import $this public data from a private response array
  348. *
  349. * @param array $privateResponseMap
  350. * @param array $response
  351. * @return void
  352. */
  353. protected function _importFromResponse(array $privateResponseMap, array $response)
  354. {
  355. $map = [];
  356. foreach ($privateResponseMap as $key) {
  357. if (isset($this->_globalMap[$key])) {
  358. $map[$key] = $this->_globalMap[$key];
  359. }
  360. if (isset($response[$key]) && isset($this->_importFromRequestFilters[$key])) {
  361. $callback = $this->_importFromRequestFilters[$key];
  362. $response[$key] = call_user_func([$this, $callback], $response[$key], $key, $map[$key]);
  363. }
  364. }
  365. \Magento\Framework\DataObject\Mapper::accumulateByMap($response, [$this, 'setDataUsingMethod'], $map);
  366. }
  367. /**
  368. * Prepare line items request
  369. *
  370. * Returns true if there were line items added
  371. *
  372. * @param array &$request
  373. * @param int $i
  374. * @return true|null
  375. * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  376. */
  377. protected function _exportLineItems(array &$request, $i = 0)
  378. {
  379. if (!$this->_cart) {
  380. return;
  381. }
  382. // always add cart totals, even if line items are not requested
  383. if ($this->_lineItemTotalExportMap) {
  384. foreach ($this->_cart->getAmounts() as $key => $total) {
  385. if (isset($this->_lineItemTotalExportMap[$key])) {
  386. // !empty($total)
  387. $privateKey = $this->_lineItemTotalExportMap[$key];
  388. $total = round($total, 2);
  389. $request[$privateKey] = $this->formatPrice($total);
  390. }
  391. }
  392. }
  393. // add cart line items
  394. $items = $this->_cart->getAllItems();
  395. if (empty($items) || !$this->getIsLineItemsEnabled()) {
  396. return;
  397. }
  398. $result = null;
  399. foreach ($items as $item) {
  400. foreach ($this->_lineItemExportItemsFormat as $publicKey => $privateFormat) {
  401. $result = true;
  402. $value = $item->getDataUsingMethod($publicKey);
  403. $request[sprintf($privateFormat, $i)] = $this->formatValue($value, $publicKey);
  404. }
  405. $i++;
  406. }
  407. return $result;
  408. }
  409. /**
  410. * Prepare shipping options request
  411. *
  412. * Returns false if there are no shipping options
  413. *
  414. * @param array &$request
  415. * @param int $i
  416. * @return bool
  417. */
  418. protected function _exportShippingOptions(array &$request, $i = 0)
  419. {
  420. $options = $this->getShippingOptions();
  421. if (empty($options)) {
  422. return false;
  423. }
  424. foreach ($options as $option) {
  425. foreach ($this->_shippingOptionsExportItemsFormat as $publicKey => $privateFormat) {
  426. $value = $option->getDataUsingMethod($publicKey);
  427. if (is_float($value)) {
  428. $value = $this->formatPrice($value);
  429. }
  430. if (is_bool($value)) {
  431. $value = $this->_filterBool($value);
  432. }
  433. $request[sprintf($privateFormat, $i)] = $value;
  434. }
  435. $i++;
  436. }
  437. return true;
  438. }
  439. /**
  440. * Filter boolean values in API calls
  441. *
  442. * @param mixed $value
  443. * @return string
  444. */
  445. protected function _filterBool($value)
  446. {
  447. return $value ? 'true' : 'false';
  448. }
  449. /**
  450. * Filter int values in API calls
  451. *
  452. * @param mixed $value
  453. * @return int
  454. */
  455. protected function _filterInt($value)
  456. {
  457. return (int)$value;
  458. }
  459. /**
  460. * Unified getter that looks in data or falls back to config
  461. *
  462. * @param string $key
  463. * @param mixed|null $default
  464. * @return mixed
  465. */
  466. protected function _getDataOrConfig($key, $default = null)
  467. {
  468. if ($this->hasData($key)) {
  469. return $this->getData($key);
  470. }
  471. return $this->_config->getValue($key) ? $this->_config->getValue($key) : $default;
  472. }
  473. /**
  474. * Region_id workaround: PayPal requires state code, try to find one in the address
  475. *
  476. * @param \Magento\Framework\DataObject $address
  477. * @return string
  478. */
  479. protected function _lookupRegionCodeFromAddress(\Magento\Framework\DataObject $address)
  480. {
  481. $regionId = $address->getData('region_id');
  482. if ($regionId) {
  483. $region = $this->_regionFactory->create()->load($regionId);
  484. if ($region->getId()) {
  485. return $region->getCode();
  486. }
  487. }
  488. return '';
  489. }
  490. /**
  491. * Street address workaround: divides address lines into parts by specified keys
  492. * (keys should go as 3rd, 4th[...] parameters)
  493. *
  494. * @param \Magento\Framework\DataObject $address
  495. * @param array $to
  496. * @return void
  497. */
  498. protected function _importStreetFromAddress(\Magento\Framework\DataObject $address, array &$to)
  499. {
  500. $keys = func_get_args();
  501. array_shift($keys);
  502. array_shift($keys);
  503. $street = $address->getStreet();
  504. if (!$keys || !$street || !is_array($street)) {
  505. return;
  506. }
  507. $street = $this->_customerAddress->convertStreetLines($address->getStreet(), count($keys));
  508. $i = 0;
  509. foreach ($keys as $key) {
  510. $to[$key] = isset($street[$i]) ? $street[$i] : '';
  511. $i++;
  512. }
  513. }
  514. /**
  515. * Build query string from request
  516. *
  517. * @param array $request
  518. * @return string
  519. */
  520. protected function _buildQuery($request)
  521. {
  522. return http_build_query($request);
  523. }
  524. /**
  525. * Filter qty in API calls
  526. *
  527. * Paypal note: The value for quantity must be a positive integer. Null, zero, or negative numbers are not allowed.
  528. *
  529. * @param float|string|int $value
  530. * @return string
  531. */
  532. protected function _filterQty($value)
  533. {
  534. return (int)$value;
  535. }
  536. /**
  537. * Log debug data to file
  538. *
  539. * @param mixed $debugData
  540. * @return void
  541. */
  542. protected function _debug($debugData)
  543. {
  544. $this->customLogger->debug(
  545. $debugData,
  546. (array)$this->getDebugReplacePrivateDataKeys(),
  547. (bool)$this->getDebugFlag()
  548. );
  549. }
  550. /**
  551. * Define if debugging is enabled
  552. *
  553. * @return bool
  554. * @SuppressWarnings(PHPMD.BooleanGetMethodName)
  555. */
  556. public function getDebugFlag()
  557. {
  558. return $this->_config->getValue('debug');
  559. }
  560. /**
  561. * Check whether API certificate authentication should be used
  562. *
  563. * @return bool
  564. * @SuppressWarnings(PHPMD.BooleanGetMethodName)
  565. */
  566. public function getUseCertAuthentication()
  567. {
  568. return (bool)$this->_config->getValue('apiAuthentication');
  569. }
  570. /**
  571. * Return replace keys for debug data
  572. *
  573. * @return array
  574. */
  575. public function getDebugReplacePrivateDataKeys()
  576. {
  577. return $this->_debugReplacePrivateDataKeys;
  578. }
  579. /**
  580. * Formats value according to configured filters or converts to 0.00 format if value is float.
  581. *
  582. * @param string|int|float|\Magento\Framework\Phrase $value
  583. * @param string $publicKey
  584. * @return string
  585. */
  586. private function formatValue($value, $publicKey)
  587. {
  588. if (!empty($this->_lineItemExportItemsFilters[$publicKey])) {
  589. $callback = $this->_lineItemExportItemsFilters[$publicKey];
  590. $value = method_exists($this, $callback) ? $this->{$callback}($value) : $callback($value);
  591. }
  592. if (is_float($value)) {
  593. $value = $this->formatPrice($value);
  594. }
  595. return $value;
  596. }
  597. }