Guest User

Untitled

a guest
Apr 24th, 2018
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 16.61 KB | None | 0 0
  1. <?php
  2.  
  3. /**
  4. * @var MagentoCheckoutModelSession
  5. */
  6. protected $session;
  7.  
  8. /**
  9. *
  10. * @var PsrLogLoggerInterface
  11. */
  12. protected $_logger;
  13.  
  14. /**
  15. *
  16. * @var type
  17. */
  18. protected $_checkoutSession;
  19. /**
  20. *
  21. * @var MagentoStoreModelStoreManagerInterface
  22. */
  23. protected $_storeManager;
  24.  
  25. /**
  26. * @var MagentoFrameworkLocaleResolverInterface
  27. */
  28. protected $_localeResolver;
  29.  
  30. /**
  31. * @var OrderManagementInterface
  32. */
  33. protected $orderManagement;
  34.  
  35. /**
  36. * @var MagentoFrameworkObjectManagerInterface
  37. */
  38. protected $_objectManager;
  39.  
  40. public function __construct(
  41. MagentoFrameworkAppHelperContext $context,
  42. MagentoFrameworkViewLayoutFactory $layoutFactory,
  43. MagentoPaymentModelMethodFactory $paymentMethodFactory,
  44. MagentoStoreModelAppEmulation $appEmulation,
  45. MagentoPaymentModelConfig $paymentConfig,
  46. MagentoFrameworkAppConfigInitial $initialConfig,
  47. MagentoStoreModelStoreManagerInterface $storeManager,
  48. MagentoCheckoutModelSession $session,
  49. OrderManagementInterface $orderManagement,
  50. MagentoFrameworkObjectManagerInterface $objectManager,
  51. MagentoFrameworkLocaleResolverInterface $localeResolver
  52. ) {
  53. parent::__construct($context,$layoutFactory, $paymentMethodFactory, $appEmulation, $paymentConfig, $initialConfig);
  54. $this->_storeManager = $storeManager;
  55. $this->session = $session;
  56. $logger = $context->getLogger();
  57. $this->_localeResolver = $localeResolver;
  58. $this->orderManagement = $orderManagement;
  59. $this->_objectManager = $objectManager;
  60. }
  61.  
  62. public function setMethodCode($code) {
  63. $this->_code = $code;
  64. }
  65.  
  66. public function getConfig($config_path)
  67. {
  68. return $this->scopeConfig->getValue(
  69. $config_path,
  70. MagentoStoreModelScopeInterface::SCOPE_STORE
  71. );
  72. }
  73.  
  74. public function getMainConfigData($config_field)
  75. {
  76. return $this->scopeConfig->getValue(
  77. ('payment/payfort_fort/'.$config_field),
  78. MagentoStoreModelScopeInterface::SCOPE_STORE
  79. );
  80. }
  81.  
  82. public function getPaymentPageRedirectData($order) {
  83. $paymentMethod = $order->getPayment()->getMethod();
  84. $orderId = $order->getRealOrderId();
  85. $currency = $order->getOrderCurrency()->getCurrencyCode();
  86. $amount = $this->convertFortAmount($order->getGrandTotal(), $currency);
  87. $language = $this->getLanguage();
  88. $gatewayParams = array(
  89. 'amount' => $amount,
  90. 'currency' => strtoupper($currency),
  91. 'merchant_identifier' => $this->getMainConfigData('merchant_identifier'),
  92. 'access_code' => $this->getMainConfigData('access_code'),
  93. 'merchant_reference' => $orderId,
  94. 'customer_email' => trim( $order->getCustomerEmail() ),
  95. 'command' => $this->getMainConfigData('command'),
  96. 'language' => $language,
  97. 'return_url' => $this->getReturnUrl('payfortfort/payment/response')
  98. );
  99. if($paymentMethod == PayfortFortModelMethodSadad::CODE) {
  100. $gatewayParams['payment_option'] = 'SADAD';
  101. }
  102. elseif ($paymentMethod == PayfortFortModelMethodNaps::CODE)
  103. {
  104. $gatewayParams['payment_option'] = 'NAPS';
  105. $gatewayParams['order_description'] = $orderId;
  106. }
  107. $gatewayParams['signature'] = $this->calculateSignature($gatewayParams, 'request');
  108. $gatewayUrl = $this->getGatewayUrl('redirection');
  109.  
  110. $debugMsg = "Fort Redirect Request Parameters n".print_r($gatewayParams, 1);
  111. $this->log($debugMsg);
  112. return array('url' => $gatewayUrl, 'params' => $gatewayParams);
  113. }
  114.  
  115. public function getOrderCustomerName($order) {
  116. $customerName = '';
  117. if( $order->getCustomerId() === null ){
  118. $customerName = $order->getBillingAddress()->getFirstname(). ' ' . $order->getBillingAddress()->getLastname();
  119. }
  120. else{
  121. $customerName = $order->getCustomerName();
  122. }
  123. return trim($customerName);
  124. }
  125. public function getMerchantPageData($order) {
  126. $language = $this->getLanguage();
  127. $orderId = $order->getRealOrderId();
  128. $gatewayParams = array(
  129. 'merchant_identifier' => $this->getMainConfigData('merchant_identifier'),
  130. 'access_code' => $this->getMainConfigData('access_code'),
  131. 'merchant_reference' => $orderId,
  132. 'service_command' => 'TOKENIZATION',
  133. 'language' => $language,
  134. 'return_url' => $this->getReturnUrl('payfortfort/payment/merchantPageResponse'),
  135. );
  136. //calculate request signature
  137. $signature = $this->calculateSignature($gatewayParams, 'request');
  138. $gatewayParams['signature'] = $signature;
  139.  
  140. $gatewayUrl = $this->getGatewayUrl();
  141.  
  142. $debugMsg = "Fort Merchant Page Request Parameters n".print_r($gatewayParams, true);
  143. $this->log($debugMsg);
  144.  
  145. return array('url' => $gatewayUrl, 'params' => $gatewayParams);
  146. }
  147.  
  148. public function isMerchantPageMethod($order) {
  149. $paymentMethod = $order->getPayment()->getMethod();
  150. if($paymentMethod == PayfortFortModelMethodCc::CODE && $this->getConfig('payment/payfort_fort_cc/integration_type') == PayfortFortModelConfigSourceIntegrationtypeoptions::MERCHANT_PAGE) {
  151. return true;
  152. }
  153. return false;
  154. }
  155.  
  156. public function merchantPageNotifyFort($order, $fortParams) {
  157. //send host to host
  158. $language = $this->getLanguage();
  159. $orderId = $order->getRealOrderId();
  160.  
  161. $return_url = $this->getReturnUrl('payfortfort/payment/response');
  162.  
  163. $ip = $this->getVisitorIp();
  164. $currency = $order->getOrderCurrency()->getCurrencyCode();
  165. $amount = $this->convertFortAmount($order->getGrandTotal(), $currency);
  166. $postData = array(
  167. 'merchant_reference' => $orderId,
  168. 'access_code' => $this->getMainConfigData('access_code'),
  169. 'command' => $this->getMainConfigData('command'),
  170. 'merchant_identifier' => $this->getMainConfigData('merchant_identifier'),
  171. 'customer_ip' => $ip,
  172. 'amount' => $amount,
  173. 'currency' => strtoupper($currency),
  174. 'customer_email' => trim( $order->getCustomerEmail() ),
  175. 'token_name' => $fortParams['token_name'],
  176. 'language' => $language,
  177. 'return_url' => $return_url,
  178. );
  179. $customer_name = $this->getOrderCustomerName($order);
  180. if(!empty($customer_name)) {
  181. $postData['customer_name'] = $customer_name;
  182. }
  183. //calculate request signature
  184. $signature = $this->calculateSignature($postData, 'request');
  185. $postData['signature'] = $signature;
  186.  
  187. $debugMsg = "Fort Merchant Page Notifiaction Request Parameters n".print_r($postData, true);
  188. $this->log($debugMsg);
  189.  
  190. $gatewayUrl = $this->getGatewayUrl('notificationApi');
  191. //open connection
  192. $ch = curl_init();
  193.  
  194. //set the url, number of POST vars, POST data
  195. $useragent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:20.0) Gecko/20100101 Firefox/20.0";
  196. curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
  197. curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  198. 'Content-Type: application/json;charset=UTF-8',
  199. //'Accept: application/json, application/*+json',
  200. //'Connection:keep-alive'
  201. ));
  202. curl_setopt($ch, CURLOPT_URL, $gatewayUrl);
  203. curl_setopt($ch, CURLOPT_POST, 1);
  204. curl_setopt($ch, CURLOPT_FAILONERROR, 1);
  205. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  206. curl_setopt($ch, CURLOPT_ENCODING, "compress, gzip");
  207. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
  208. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  209. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // allow redirects
  210. //curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // return into a variable
  211. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0); // The number of seconds to wait while trying to connect
  212. //curl_setopt($ch, CURLOPT_TIMEOUT, Yii::app()->params['apiCallTimeout']); // timeout in seconds
  213. curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
  214.  
  215. $response = curl_exec($ch);
  216.  
  217. //$response_data = array();
  218.  
  219. //parse_str($response, $response_data);
  220. curl_close($ch);
  221.  
  222. $array_result = json_decode($response, true);
  223.  
  224. $debugMsg = 'Fort Merchant Page Notifiaction Response Parameters'."n".print_r($array_result, true);
  225. $this->log($debugMsg);
  226.  
  227. if(!$response || empty($array_result)) {
  228. return false;
  229. }
  230. return $array_result;
  231. }
  232.  
  233. /** @return string */
  234. function getVisitorIp() {
  235. /** @var MagentoFrameworkObjectManagerInterface $om */
  236. $om = MagentoFrameworkAppObjectManager::getInstance();
  237. /** @var MagentoFrameworkHTTPPhpEnvironmentRemoteAddress $a */
  238. $a = $om->get('MagentoFrameworkHTTPPhpEnvironmentRemoteAddress');
  239. return $a->getRemoteAddress();
  240. }
  241.  
  242. /**
  243. * calculate fort signature
  244. * @param array $arr_data
  245. * @param sting $sign_type request or response
  246. * @return string fort signature
  247. */
  248. public function calculateSignature($arr_data, $sign_type = 'request')
  249. {
  250. $sha_in_pass_phrase = $this->getMainConfigData('sha_in_pass_phrase');
  251. $sha_out_pass_phrase = $this->getMainConfigData('sha_out_pass_phrase');
  252. $sha_type = $this->getMainConfigData('sha_type');
  253. $sha_type = str_replace('-', '', $sha_type);
  254.  
  255. $shaString = '';
  256.  
  257. ksort($arr_data);
  258. foreach ($arr_data as $k => $v) {
  259. $shaString .= "$k=$v";
  260. }
  261.  
  262. if ($sign_type == 'request') {
  263. $shaString = $sha_in_pass_phrase . $shaString . $sha_in_pass_phrase;
  264. }
  265. else {
  266. $shaString = $sha_out_pass_phrase . $shaString . $sha_out_pass_phrase;
  267. }
  268. $signature = hash($sha_type, $shaString);
  269.  
  270. return $signature;
  271. }
  272.  
  273. /**
  274. * Convert Amount with dicemal points
  275. * @param decimal $amount
  276. * @param string $baseCurrencyCode
  277. * @param string $currentCurrencyCode
  278. * @return decimal
  279. */
  280. public function convertFortAmount($amount, $currencyCode)
  281. {
  282.  
  283. $new_amount = 0;
  284. $decimal_points = $this->getCurrencyDecimalPoint($currencyCode);
  285. $new_amount = round($amount, $decimal_points);
  286. $new_amount = $new_amount * (pow(10, $decimal_points));
  287. return $new_amount;
  288. }
  289.  
  290. /**
  291. *
  292. * @param string $currency
  293. * @param integer
  294. */
  295. public function getCurrencyDecimalPoint($currency)
  296. {
  297. $decimalPoint = 2;
  298. $arrCurrencies = array(
  299. 'JOD' => 3,
  300. 'KWD' => 3,
  301. 'OMR' => 3,
  302. 'TND' => 3,
  303. 'BHD' => 3,
  304. 'LYD' => 3,
  305. 'IQD' => 3,
  306. );
  307. if (isset($arrCurrencies[$currency])) {
  308. $decimalPoint = $arrCurrencies[$currency];
  309. }
  310. return $decimalPoint;
  311. }
  312.  
  313. public function getGatewayUrl($type='redirection') {
  314. $testMode = $this->getMainConfigData('sandbox_mode');
  315. if($type == 'notificationApi') {
  316. $gatewayUrl = $testMode ? $this->_gatewaySandboxHost.'FortAPI/paymentApi' : $this->_gatewayHost.'FortAPI/paymentApi';
  317. }
  318. else{
  319. $gatewayUrl = $testMode ? $this->_gatewaySandboxHost.'FortAPI/paymentPage' : $this->_gatewayHost.'FortAPI/paymentPage';
  320. }
  321.  
  322. return $gatewayUrl;
  323. }
  324.  
  325. public function getReturnUrl($path) {
  326. return $this->_storeManager->getStore()->getBaseUrl().$path;
  327. //return $this->getUrl($path);
  328. }
  329.  
  330. public function getLanguage() {
  331. $language = $this->getMainConfigData('language');
  332. if ($language == PayfortFortModelConfigSourceLanguageoptions::STORE) {
  333. $language = $this->_localeResolver->getLocale();
  334. }
  335. if(substr($language, 0, 2) == 'ar') {
  336. $language = 'ar';
  337. }
  338. else{
  339. $language = 'en';
  340. }
  341. return $language;
  342. }
  343.  
  344. /**
  345. * Restores quote
  346. *
  347. * @return bool
  348. */
  349. public function restoreQuote()
  350. {
  351. return $this->session->restoreQuote();
  352. }
  353.  
  354. /**
  355. * Cancel last placed order with specified comment message
  356. *
  357. * @param string $comment Comment appended to order history
  358. * @return bool True if order cancelled, false otherwise
  359. */
  360. public function cancelCurrentOrder($comment)
  361. {
  362. $order = $this->session->getLastRealOrder();
  363. if(!empty($comment)) {
  364. $comment = 'Payfort_Fort :: ' . $comment;
  365. }
  366. if ($order->getId() && $order->getState() != Order::STATE_CANCELED) {
  367. $order->registerCancellation($comment)->save();
  368. return true;
  369. }
  370. return false;
  371. }
  372.  
  373. /**
  374. * Cancel order with specified comment message
  375. *
  376. * @return Mixed
  377. */
  378. public function cancelOrder($order, $comment)
  379. {
  380. $gotoSection = false;
  381. if(!empty($comment)) {
  382. $comment = 'Payfort_Fort :: ' . $comment;
  383. }
  384. if ($order->getState() != Order::STATE_CANCELED) {
  385. $order->registerCancellation($comment)->save();
  386. /*if ($this->restoreQuote()) {
  387. //Redirect to payment step
  388. $gotoSection = 'paymentMethod';
  389. }*/
  390. $gotoSection = true;
  391. }
  392. return $gotoSection;
  393. }
  394.  
  395. public function orderFailed($order) {
  396. if ($order->getState() != $this->getMainConfigData('order_status_on_fail')) {
  397. $order->setStatus($this->getMainConfigData('order_status_on_fail'));
  398. $order->setState($this->getMainConfigData('order_status_on_fail'));
  399. $order->save();
  400. $customerNotified = $this->sendOrderEmail($order);
  401. $order->addStatusToHistory( $this->getMainConfigData('order_status_on_fail') , 'Payfort_Fort :: payment has failed.', $customerNotified );
  402. $order->save();
  403. return true;
  404. }
  405. return false;
  406. }
  407.  
  408. public function processOrder($order) {
  409.  
  410. if ($order->getState() != $order::STATE_PROCESSING) {
  411. $order->setStatus($order::STATE_PROCESSING);
  412. $order->setState($order::STATE_PROCESSING);
  413. //$order->setExtOrderId($orderNumber);
  414. $order->save();
  415. $customerNotified = $this->sendOrderEmail($order);
  416. $order->addStatusToHistory( $order::STATE_PROCESSING , 'Payfort_Fort :: Order has been paid.', $customerNotified );
  417. $order->save();
  418. return true;
  419. }
  420. return false;
  421. }
  422.  
  423. public function sendOrderEmail($order) {
  424. $result = true;
  425. try{
  426. if($order->getState() != $order::STATE_PROCESSING) {
  427. $orderCommentSender = $this->_objectManager
  428. ->create('MagentoSalesModelOrderEmailSenderOrderCommentSender');
  429. $orderCommentSender->send($order, true, '');
  430. }
  431. else{
  432. $this->orderManagement->notify($order->getEntityId());
  433. }
  434. } catch (Exception $e) {
  435. $result = false;
  436. $this->_logger->critical($e);
  437. }
  438.  
  439. return $result;
  440. }
  441.  
  442. public function getUrl($route, $params = [])
  443. {
  444. return $this->_getUrl($route, $params);
  445. }
  446.  
  447. public function validateResponse($responseData)
  448. {
  449. $debugMsg = "Response Parameters n".print_r($responseData, 1);
  450. $this->log($debugMsg);
  451. if(empty($responseData)) {
  452. $this->log('Invalid Response Parameters');
  453. return PayfortFortModelPayment::PAYMENT_STATUS_FAILED;
  454. }
  455.  
  456. $responseSignature = $responseData['signature'];
  457. $responseGatewayParams = $responseData;
  458. unset($responseGatewayParams['signature']);
  459. $calculatedSignature = $this->calculateSignature($responseGatewayParams, 'response');
  460. if($responseSignature != $calculatedSignature) {
  461. $this->log(sprintf('Invalid Signature. Calculated Signature: %1s, Response Signature: %2s', $responseSignature, $calculatedSignature));
  462. return PayfortFortModelPayment::PAYMENT_STATUS_FAILED;
  463. }
  464. $response_code = $responseData['response_code'];
  465. $response_msg = $responseData['response_message'];
  466. if (substr($response_code, 2) != '000') {
  467. if($response_code == PayfortFortModelPayment::PAYMENT_STATUS_CANCELED) {
  468. $this->log(sprintf('User has cancle the payment, Response Code (%1s), Response Message (%2s)', $response_code, $response_msg));
  469. return PayfortFortModelPayment::PAYMENT_STATUS_CANCELED;
  470. }
  471. elseif($response_code == PayfortFortModelPayment::PAYMENT_STATUS_3DS_CHECK) {
  472. return PayfortFortModelPayment::PAYMENT_STATUS_3DS_CHECK;
  473. }
  474. else {
  475. $this->log(sprintf('Gateway error: Response Code (%1s), Response Message (%2s)', $response_code, $response_msg));
  476. return PayfortFortModelPayment::PAYMENT_STATUS_FAILED;
  477. }
  478.  
  479. }
  480. return PayfortFortModelPayment::PAYMENT_STATUS_SUCCESS;
  481. }
  482.  
  483. /**
  484. * Log the error on the disk
  485. */
  486. public function log($messages, $forceLog = false) {
  487. $debugMode = $this->getMainConfigData('debug');
  488. if(!$debugMode && !$forceLog) {
  489. return;
  490. }
  491. $debugMsg = "=============== Payfort_Fort Module =============== n".$messages."n";
  492. $this->_logger->debug($debugMsg);
  493. }
  494.  
  495. public function sendOrderEmail($order) {
  496. $result = true;
  497. try{
  498. if($order->getState() != $order::STATE_PROCESSING) {
  499. $orderCommentSender = $this->_objectManager
  500. ->create('MagentoSalesModelOrderEmailSenderOrderCommentSender');
  501. $orderCommentSender->send($order, true, '');
  502. }
  503. else{
  504. $this->orderManagement->notify($order->getEntityId());
  505. }
  506. } catch (Exception $e) {
  507. $result = false;
  508. $this->_logger->critical($e);
  509. }
  510.  
  511. return $result;
  512. }
Add Comment
Please, Sign In to add comment