/** * @throws \Magento\Framework\Exception\LocalizedException */ public function execute() { // if version is in the notification string show the module version $response = $this->getRequest()->getParams(); if (isset($response['version'])) { $this->getResponse()->clearHeader('Content-Type')->setHeader('Content-Type', 'text/html')->setBody($this->_adyenHelper->getModuleVersion()); return; } try { $notificationItems = json_decode(file_get_contents('php://input'), true); // log the notification $this->_adyenLogger->addAdyenNotification("The content of the notification is: " . print_r($notificationItems, 1)); $notificationMode = isset($notificationItems['live']) ? $notificationItems['live'] : ""; if ($notificationMode != "" && $this->_validateNotificationMode($notificationMode)) { foreach ($notificationItems['notificationItems'] as $notificationItem) { $status = $this->_processNotification($notificationItem['NotificationRequestItem'], $notificationMode); if ($status != true) { $this->_return401(); return; } } $this->_adyenLogger->addAdyenNotification("The result is accepted"); $this->getResponse()->clearHeader('Content-Type')->setHeader('Content-Type', 'text/html')->setBody("[accepted]"); return; } else { if ($notificationMode == "") { $this->_return401(); return; } throw new \Magento\Framework\Exception\LocalizedException(__('Mismatch between Live/Test modes of Magento store and the Adyen platform')); } } catch (Exception $e) { throw new \Magento\Framework\Exception\LocalizedException(__($e->getMessage())); } }
/** * @param array $validationSubject * @throws \Magento\Framework\Exception\LocalizedException */ public function validate(array $validationSubject) { $response = \Magento\Payment\Gateway\Helper\SubjectReader::readResponse($validationSubject); $isValid = true; $errorMessages = []; if ($response['response'] != '[capture-received]') { $errorMsg = __('Error with capture'); $this->adyenLogger->error($errorMsg); $errorMessages[] = $errorMsg; } return $this->createResult($isValid, $errorMessages); }
public function execute() { $response = $this->getRequest()->getParams(); $this->_adyenLogger->info(print_r($response, true)); $result = $this->validateResponse($response); if ($result) { $session = $this->_session; $session->getQuote()->setIsActive(false)->save(); $this->_redirect('checkout/onepage/success'); } else { $this->_cancel($response); $this->_redirect('checkout/cart'); } }
/** * @param $requestParams * @param $store * @return array * @throws \Adyen\AdyenException */ protected function _getDirectoryLookupResponse($requestParams, $store) { $cacheKey = $this->_getCacheKeyForRequest($requestParams, $store); // initialize the adyen client $client = new \Adyen\Client(); if ($this->_adyenHelper->isDemoMode()) { $client->setEnvironment(\Adyen\Environment::TEST); } else { $client->setEnvironment(\Adyen\Environment::LIVE); } // connect to magento log $client->setLogger($this->_adyenLogger); $hmacKey = $this->_adyenHelper->getHmac(); // create and add signature try { $requestParams["merchantSig"] = \Adyen\Util\Util::calculateSha256Signature($hmacKey, $requestParams); } catch (\Adyen\AdyenException $e) { $this->_adyenLogger->error($e->getMessage()); // return empty result return []; } // initialize service $service = new \Adyen\Service\DirectoryLookup($client); try { $responseData = $service->directoryLookup($requestParams); } catch (\Adyen\AdyenException $e) { $this->_adyenLogger->error("The Directory Lookup response is empty check your Adyen configuration in Magento."); // return empty result return []; } return $responseData; }
protected function _apiRequest($request) { // log the request $this->_adyenLogger->info('The request to adyen: ' . print_r($request, true)); $webserviceUsername = $this->_adyenHelper->getWsUsername(); $webservicePassword = $this->_adyenHelper->getWsPassword(); $url = $this->_adyenHelper->getWsUrl(); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); curl_setopt($ch, CURLOPT_USERPWD, $webserviceUsername . ":" . $webservicePassword); curl_setopt($ch, CURLOPT_POST, count($request)); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($request)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $results = curl_exec($ch); $httpStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE); if ($httpStatus != 200) { throw new \Magento\Framework\Exception\LocalizedException(__('HTTP Status code' . $httpStatus . " " . $webserviceUsername . ":" . $webservicePassword)); } if ($results === false) { throw new \Magento\Framework\Exception\LocalizedException(__('HTTP Status code' . $results)); } parse_str($results, $resultArr); curl_close($ch); // log the result $this->_adyenLogger->info('The response to adyen: ' . print_r($resultArr, true)); return $resultArr; }
public function getFormFields() { $paymentInfo = $this->getInfoInstance(); $order = $paymentInfo->getOrder(); $realOrderId = $order->getRealOrderId(); $orderCurrencyCode = $order->getOrderCurrencyCode(); $skinCode = trim($this->getConfigData('skin_code')); $amount = $this->_adyenHelper->formatAmount($order->getGrandTotal(), $orderCurrencyCode); $merchantAccount = trim($this->_adyenHelper->getAdyenAbstractConfigData('merchant_account')); $shopperEmail = $order->getCustomerEmail(); $customerId = $order->getCustomerId(); $shopperIP = $order->getRemoteIp(); $browserInfo = $_SERVER['HTTP_USER_AGENT']; $deliveryDays = $this->getConfigData('delivery_days'); $shopperLocale = trim($this->getConfigData('shopper_locale')); $shopperLocale = !empty($shopperLocale) ? $shopperLocale : $this->resolver->getLocale(); $countryCode = trim($this->getConfigData('country_code')); $countryCode = !empty($countryCode) ? $countryCode : false; // if directory lookup is enabled use the billingadress as countrycode if ($countryCode == false) { if ($order->getBillingAddress() && $order->getBillingAddress()->getCountryId() != "") { $countryCode = $order->getBillingAddress()->getCountryId(); } } $formFields = array(); $formFields['merchantAccount'] = $merchantAccount; $formFields['merchantReference'] = $realOrderId; $formFields['paymentAmount'] = (int) $amount; $formFields['currencyCode'] = $orderCurrencyCode; $formFields['shipBeforeDate'] = date("Y-m-d", mktime(date("H"), date("i"), date("s"), date("m"), date("j") + $deliveryDays, date("Y"))); $formFields['skinCode'] = $skinCode; $formFields['shopperLocale'] = $shopperLocale; $formFields['countryCode'] = $countryCode; $formFields['shopperIP'] = $shopperIP; $formFields['browserInfo'] = $browserInfo; $formFields['sessionValidity'] = date(DATE_ATOM, mktime(date("H") + 1, date("i"), date("s"), date("m"), date("j"), date("Y"))); $formFields['shopperEmail'] = $shopperEmail; // recurring $recurringType = trim($this->_adyenHelper->getAdyenAbstractConfigData('recurring_type')); $formFields['recurringContract'] = $recurringType; $formFields['shopperReference'] = !empty($customerId) ? $customerId : self::GUEST_ID . $realOrderId; //blocked methods $formFields['blockedMethods'] = ""; $baseUrl = $this->storeManager->getStore($this->getStore())->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_LINK); $formFields['resURL'] = $baseUrl . 'adyen/process/result'; $hmacKey = $this->_adyenHelper->getHmac(); $brandCode = $this->getInfoInstance()->getCcType(); if ($brandCode) { $formFields['brandCode'] = $brandCode; } // Sort the array by key using SORT_STRING order ksort($formFields, SORT_STRING); // Generate the signing data string $signData = implode(":", array_map(array($this, 'escapeString'), array_merge(array_keys($formFields), array_values($formFields)))); $merchantSig = base64_encode(hash_hmac('sha256', $signData, pack("H*", $hmacKey), true)); $formFields['merchantSig'] = $merchantSig; $this->_adyenLogger->info(print_r($formFields, true)); return $formFields; }
public function execute() { $active = null; // check if 3d is active $order = $this->_getOrder(); if ($order->getPayment()) { $active = $order->getPayment()->getAdditionalInformation('3dActive'); } // check if 3D secure is active. If not just go to success page if ($active) { $this->_adyenLogger->addAdyenResult("3D secure is active"); // check if it is already processed if ($this->getRequest()->isPost()) { $this->_adyenLogger->addAdyenResult("Process 3D secure payment"); $requestMD = $this->getRequest()->getPost('MD'); $requestPaRes = $this->getRequest()->getPost('PaRes'); $md = $order->getPayment()->getAdditionalInformation('md'); if ($requestMD == $md) { $order->getPayment()->setAdditionalInformation('paResponse', $requestPaRes); try { $result = $order->getPayment()->getMethodInstance()->authorise3d($order->getPayment()); } catch (Exception $e) { $result = 'Refused'; } // check if authorise3d was successful if ($result == 'Authorised') { $order->addStatusHistoryComment(__('3D-secure validation was successful'))->save(); $this->_redirect('checkout/onepage/success'); } else { $order->addStatusHistoryComment(__('3D-secure validation was unsuccessful.'))->save(); $this->_adyenHelper->cancelOrder($order); } } } else { $this->_adyenLogger->addAdyenResult("Customer was redirected to bank for 3D-secure validation."); $order->addStatusHistoryComment(__('Customer was redirected to bank for 3D-secure validation.'))->save(); $this->_view->loadLayout(); $this->_view->getLayout()->initMessages(); $this->_view->renderLayout(); } } else { $this->_redirect('checkout/onepage/success/'); } }
/** * Disable a recurring contract * * @param $recurringDetailReference * @param $shopperReference * @param $storeId * @return bool * @throws \Magento\Framework\Exception\LocalizedException */ public function disableRecurringContract($recurringDetailReference, $shopperReference, $storeId) { $merchantAccount = $this->_adyenHelper->getAdyenAbstractConfigData("merchant_account", $storeId); $request = ["merchantAccount" => $merchantAccount, "shopperReference" => $shopperReference, "recurringDetailReference" => $recurringDetailReference]; // call lib $service = new \Adyen\Service\Recurring($this->_client); try { $result = $service->disable($request); } catch (\Exception $e) { $this->_adyenLogger->info($e->getMessage()); } if (isset($result['response']) && $result['response'] == '[detail-successfully-disabled]') { return true; } else { throw new \Magento\Framework\Exception\LocalizedException(__('Failed to disable this contract')); } }
/** * Validate checksum from result parameters * * @param $response * @return bool */ protected function _validateChecksum($response) { $checksum = $response['cs']; $result = $response['result']; $amount = $response['originalCustomAmount']; $currency = $response['originalCustomCurrency']; $sessionId = $response['sessionId']; // for android sessionis is with low i if ($sessionId == "") { $sessionId = $response['sessionid']; } // calculate amount checksum $amountChecksum = 0; $amountLength = strlen($amount); for ($i = 0; $i < $amountLength; $i++) { // ASCII value use ord $checksumCalc = ord($amount[$i]) - 48; $amountChecksum += $checksumCalc; } $currencyChecksum = 0; $currencyLength = strlen($currency); for ($i = 0; $i < $currencyLength; $i++) { $checksumCalc = ord($currency[$i]) - 64; $currencyChecksum += $checksumCalc; } $resultChecksum = 0; $resultLength = strlen($result); for ($i = 0; $i < $resultLength; $i++) { $checksumCalc = ord($result[$i]) - 64; $resultChecksum += $checksumCalc; } $sessionIdChecksum = 0; $sessionIdLength = strlen($sessionId); for ($i = 0; $i < $sessionIdLength; $i++) { $checksumCalc = $this->_getAscii2Int($sessionId[$i]); $sessionIdChecksum += $checksumCalc; } $totalResultChecksum = ($amountChecksum + $currencyChecksum + $resultChecksum) * $sessionIdChecksum % 100; // check if request is valid if ($totalResultChecksum == $checksum) { $this->_adyenLogger->addAdyenResult('Checksum is valid'); return true; } $this->_adyenLogger->addAdyenResult('Checksum is invalid!'); return false; }
/** * @param $order * @param $params */ protected function _validateUpdateOrder($order, $response) { $result = false; $this->_adyenLogger->addAdyenResult('Updating the order'); $authResult = $response['authResult']; $paymentMethod = isset($response['paymentMethod']) ? trim($response['paymentMethod']) : ''; $pspReference = isset($response['pspReference']) ? trim($response['pspReference']) : ''; $type = 'Adyen Result URL response:'; $comment = __('%1 <br /> authResult: %2 <br /> pspReference: %3 <br /> paymentMethod: %4', $type, $authResult, $pspReference, $paymentMethod); $history = $this->_orderHistoryFactory->create()->setComment($comment)->setEntityName('order')->setOrder($order); $history->save(); // needed becuase then we need to save $order objects $order->setAdyenResulturlEventCode($authResult); switch ($authResult) { case \Adyen\Payment\Model\Notification::AUTHORISED: case \Adyen\Payment\Model\Notification::PENDING: // do nothing wait for the notification $result = true; $this->_adyenLogger->addAdyenResult('Do nothing wait for the notification'); break; case \Adyen\Payment\Model\Notification::CANCELLED: $this->_adyenLogger->addAdyenResult('Cancel or Hold the order'); $result = false; break; case \Adyen\Payment\Model\Notification::REFUSED: // if refused there will be a AUTHORIZATION : FALSE notification send only exception is idea $this->_adyenLogger->addAdyenResult('Cancel or Hold the order'); $result = false; break; case \Adyen\Payment\Model\Notification::ERROR: //attempt to hold/cancel $this->_adyenLogger->addAdyenResult('Cancel or Hold the order'); $result = false; break; default: $this->_adyenLogger->addAdyenResult('This event is not supported: ' . $authResult); $result = false; break; } return $result; }
/** * @return string */ public function getLaunchLink() { $launchlink = ""; try { if ($this->_order->getPayment()) { $realOrderId = $this->_order->getRealOrderId(); $orderCurrencyCode = $this->_order->getOrderCurrencyCode(); $amount = $this->_adyenHelper->formatAmount($this->_order->getGrandTotal(), $orderCurrencyCode); $shopperEmail = $this->_order->getCustomerEmail(); $customerId = $this->_order->getCustomerId(); $callbackUrl = $this->_urlBuilder->getUrl('adyen/process/resultpos', ['_secure' => $this->_getRequest()->isSecure()]); $addReceiptOrderLines = $this->_adyenHelper->getAdyenPosConfigData("add_receipt_order_lines"); $recurringContract = $this->_adyenHelper->getAdyenPosConfigData('recurring_type'); $currencyCode = $orderCurrencyCode; $paymentAmount = $amount; $merchantReference = $realOrderId; $shopperReference = !empty($customerId) ? $customerId : self::GUEST_ID . $realOrderId; $shopperEmail = $shopperEmail; $recurringParams = ""; if ($this->_order->getPayment()->getAdditionalInformation("store_cc") != "") { $recurringParams = "&recurringContract=" . urlencode($recurringContract) . "&shopperReference=" . urlencode($shopperReference) . "&shopperEmail=" . urlencode($shopperEmail); } $receiptOrderLines = ""; if ($addReceiptOrderLines) { $orderLines = base64_encode($this->_getReceiptOrderLines($this->_order)); $receiptOrderLines = "&receiptOrderLines=" . urlencode($orderLines); } // extra parameters so that you alway's return these paramters from the application $extraParamaters = urlencode("/?originalCustomCurrency=" . $currencyCode . "&originalCustomAmount=" . $paymentAmount . "&originalCustomMerchantReference=" . $merchantReference . "&originalCustomSessionId=" . session_id()); $launchlink = "adyen://payment?sessionId=" . session_id() . "&amount=" . $paymentAmount . "¤cy=" . $currencyCode . "&merchantReference=" . $merchantReference . $recurringParams . $receiptOrderLines . "&callback=" . $callbackUrl . $extraParamaters; // cash not working see ticket // https://youtrack.is.adyen.com/issue/IOS-130#comment=102-20285 // . "&transactionType=CASH"; $this->_adyenLogger->addAdyenDebug(print_r($launchlink, true)); } } catch (Exception $e) { // do nothing for now throw $e; } return $launchlink; }
/** * @param array $validationSubject * @return \Magento\Payment\Gateway\Validator\ResultInterface */ public function validate(array $validationSubject) { $response = \Magento\Payment\Gateway\Helper\SubjectReader::readResponse($validationSubject); $paymentDataObjectInterface = \Magento\Payment\Gateway\Helper\SubjectReader::readPayment($validationSubject); $payment = $paymentDataObjectInterface->getPayment(); $payment->setAdditionalInformation('3dActive', false); $isValid = true; $errorMessages = []; // validate result if ($response && isset($response['resultCode'])) { switch ($response['resultCode']) { case "Authorised": $payment->setAdditionalInformation('pspReference', $response['pspReference']); break; case "Received": $payment->setAdditionalInformation('pspReference', $response['pspReference']); // set additionalData if (isset($response['additionalData']) && is_array($response['additionalData'])) { $additionalData = $response['additionalData']; if (isset($additionalData['boletobancario.dueDate'])) { $payment->setAdditionalInformation('dueDate', $additionalData['boletobancario.dueDate']); } if (isset($additionalData['boletobancario.expirationDate'])) { $payment->setAdditionalInformation('expirationDate', $additionalData['boletobancario.expirationDate']); } if (isset($additionalData['boletobancario.url'])) { $payment->setAdditionalInformation('url', $additionalData['boletobancario.url']); } } break; case "RedirectShopper": $payment->setAdditionalInformation('3dActive', true); $payment->setAdditionalInformation('pspReference', $response['pspReference']); $issuerUrl = $response['issuerUrl']; $paReq = $response['paRequest']; $md = $response['md']; if (!empty($paReq) && !empty($md) && !empty($issuerUrl)) { $payment->setAdditionalInformation('issuerUrl', $response['issuerUrl']); $payment->setAdditionalInformation('paRequest', $response['paRequest']); $payment->setAdditionalInformation('md', $response['md']); } else { $isValid = false; $errorMsg = __('3D secure is not valid.'); $this->adyenLogger->error($errorMsg); $errorMessages[] = $errorMsg; } break; case "Refused": if ($response['refusalReason']) { $refusalReason = $response['refusalReason']; switch ($refusalReason) { case "Transaction Not Permitted": $errorMsg = __('The transaction is not permitted.'); break; case "CVC Declined": $errorMsg = __('Declined due to the Card Security Code(CVC) being incorrect. Please check your CVC code!'); break; case "Restricted Card": $errorMsg = __('The card is restricted.'); break; case "803 PaymentDetail not found": $errorMsg = __('The payment is REFUSED because the saved card is removed. Please try an other payment method.'); break; case "Expiry month not set": $errorMsg = __('The expiry month is not set. Please check your expiry month!'); break; default: $errorMsg = __('The payment is REFUSED.'); break; } } else { $errorMsg = __('The payment is REFUSED.'); } // this will result the specific error throw new \Magento\Framework\Exception\LocalizedException(__($errorMsg)); break; default: $errorMsg = __('Error with payment method please select different payment method.'); throw new \Magento\Framework\Exception\LocalizedException(__($errorMsg)); break; } } else { $errorMsg = __('Error with payment method please select different payment method.'); throw new \Magento\Framework\Exception\LocalizedException(__($errorMsg)); } return $this->createResult($isValid, $errorMessages); }
/** * @param $payment * @return array */ protected function getFormFields($payment) { $order = $payment->getOrder(); $realOrderId = $order->getRealOrderId(); $orderCurrencyCode = $order->getOrderCurrencyCode(); // check if paybymail has it's own skin $skinCode = trim($this->_adyenHelper->getAdyenPayByMailConfigData('skin_code')); if ($skinCode == "") { // use HPP skin and HMAC $skinCode = $this->_adyenHelper->getAdyenHppConfigData('skin_code'); $hmacKey = $this->_adyenHelper->getHmac(); } else { // use pay_by_mail skin and hmac $hmacKey = $this->_adyenHelper->getHmacPayByMail(); } $amount = $this->_adyenHelper->formatAmount($order->getGrandTotal(), $orderCurrencyCode); $merchantAccount = trim($this->_adyenHelper->getAdyenAbstractConfigData('merchant_account')); $shopperEmail = $order->getCustomerEmail(); $customerId = $order->getCustomerId(); $shopperLocale = trim($this->_adyenHelper->getAdyenHppConfigData('shopper_locale')); $shopperLocale = !empty($shopperLocale) ? $shopperLocale : $this->_resolver->getLocale(); $countryCode = trim($this->_adyenHelper->getAdyenHppConfigData('country_code')); $countryCode = !empty($countryCode) ? $countryCode : false; // if directory lookup is enabled use the billingadress as countrycode if ($countryCode == false) { if (is_object($order->getBillingAddress()) && $order->getBillingAddress()->getCountry() != "") { $countryCode = $order->getBillingAddress()->getCountry(); } else { $countryCode = ""; } } $deliveryDays = $this->_adyenHelper->getAdyenHppConfigData('delivery_days'); $deliveryDays = !empty($deliveryDays) ? $deliveryDays : 5; $formFields = []; $formFields['merchantAccount'] = $merchantAccount; $formFields['merchantReference'] = $realOrderId; $formFields['paymentAmount'] = (int) $amount; $formFields['currencyCode'] = $orderCurrencyCode; $formFields['shipBeforeDate'] = date("Y-m-d", mktime(date("H"), date("i"), date("s"), date("m"), date("j") + $deliveryDays, date("Y"))); $formFields['skinCode'] = $skinCode; $formFields['shopperLocale'] = $shopperLocale; if ($countryCode != "") { $formFields['countryCode'] = $countryCode; } $formFields['shopperEmail'] = $shopperEmail; // recurring $recurringType = trim($this->_adyenHelper->getAdyenAbstractConfigData('recurring_type')); $formFields['recurringContract'] = $recurringType; $sessionValidity = $this->_adyenHelper->getAdyenPayByMailConfigData('session_validity'); if ($sessionValidity == "") { $sessionValidity = 3; } $formFields['sessionValidity'] = date("c", strtotime("+" . $sessionValidity . " days")); $formFields['shopperReference'] = !empty($customerId) ? $customerId : self::GUEST_ID . $realOrderId; // Sort the array by key using SORT_STRING order ksort($formFields, SORT_STRING); // Generate the signing data string $signData = implode(":", array_map([$this, 'escapeString'], array_merge(array_keys($formFields), array_values($formFields)))); $merchantSig = base64_encode(hash_hmac('sha256', $signData, pack("H*", $hmacKey), true)); $formFields['merchantSig'] = $merchantSig; $this->_adyenLogger->addAdyenDebug(print_r($formFields, true)); return $formFields; }
/** * Validate 3D secure payment */ public function execute() { $active = null; // check if 3d is active $order = $this->_getOrder(); if ($order->getPayment()) { $active = $order->getPayment()->getAdditionalInformation('3dActive'); } // check if 3D secure is active. If not just go to success page if ($active) { $this->_adyenLogger->addAdyenResult("3D secure is active"); // check if it is already processed if ($this->getRequest()->isPost()) { $this->_adyenLogger->addAdyenResult("Process 3D secure payment"); $requestMD = $this->getRequest()->getPost('MD'); $requestPaRes = $this->getRequest()->getPost('PaRes'); $md = $order->getPayment()->getAdditionalInformation('md'); if ($requestMD == $md) { $order->getPayment()->setAdditionalInformation('paResponse', $requestPaRes); try { /** * Magento should allow this. * https://github.com/magento/magento2/issues/5819 */ // $result = $order->getPayment()->getMethodInstance()->executeCommand( // 'authorise_3d', // ['payment' => $order->getPayment(), 'amount' => $order->getGrandTotal()] // ); // old fashion way: $result = $this->_authorise3d($order->getPayment()); } catch (\Exception $e) { $this->_adyenLogger->addAdyenResult("Process 3D secure payment was refused"); $result = 'Refused'; } $this->_adyenLogger->addAdyenResult("Process 3D secure payment result is: " . $result); // check if authorise3d was successful if ($result == 'Authorised') { $order->addStatusHistoryComment(__('3D-secure validation was successful'))->save(); $this->_redirect('checkout/onepage/success'); } else { $order->addStatusHistoryComment(__('3D-secure validation was unsuccessful.'))->save(); $this->_adyenHelper->cancelOrder($order); $this->messageManager->addErrorMessage("3D-secure validation was unsuccessful"); // reactivate the quote $session = $this->_getCheckout(); // restore the quote $session->restoreQuote(); $this->_redirect('checkout/cart'); } } } else { $this->_adyenLogger->addAdyenResult("Customer was redirected to bank for 3D-secure validation."); $order->addStatusHistoryComment(__('Customer was redirected to bank for 3D-secure validation.'))->save(); $this->_view->loadLayout(); $this->_view->getLayout()->initMessages(); $this->_view->renderLayout(); } } else { $this->_redirect('checkout/onepage/success/'); } }
public function processNotification() { $this->_order = null; $this->_logger->info("START OF THE CRONJOB"); //fixme somehow the created_at is saved in my timzone $dateStart = new \DateTime(); // loop over notifications that are not processed and from 1 minute ago $dateStart = new \DateTime(); $dateStart->modify('-1 day'); // excecute notifications from 2 minute or earlier because order could not yet been created by mangento $dateEnd = new \DateTime(); $dateEnd->modify('-2 minute'); $dateRange = ['from' => $dateStart, 'to' => $dateEnd, 'datetime' => true]; $notifications = $this->_notificationFactory->create(); $notifications->addFieldToFilter('done', 0); $notifications->addFieldToFilter('created_at', $dateRange); foreach ($notifications as $notification) { // get order $incrementId = $notification->getMerchantReference(); $this->_order = $this->_orderFactory->create()->loadByIncrementId($incrementId); if (!$this->_order->getId()) { throw new Exception(sprintf('Wrong order ID: "%1".', $incrementId)); } // declare all variables that are needed $this->_declareVariables($notification); // add notification to comment history status is current status $this->_addStatusHistoryComment(); // $previousAdyenEventCode = $this->order->getAdyenNotificationEventCode(); $previousAdyenEventCode = $this->_order->getData('adyen_notification_event_code'); // set pspReference on payment object $this->_order->getPayment()->setAdditionalInformation('pspReference', $this->_pspReference); // check if success is true of false if (strcmp($this->_success, 'false') == 0 || strcmp($this->_success, '0') == 0) { // Only cancel the order when it is in state pending, payment review or if the ORDER_CLOSED is failed (means split payment has not be successful) if ($this->_order->getState() === \Magento\Sales\Model\Order::STATE_PENDING_PAYMENT || $this->_order->getState() === \Magento\Sales\Model\Order::STATE_PAYMENT_REVIEW || $this->_eventCode == \Magento\Sales\Model\Order::ADYEN_EVENT_ORDER_CLOSED) { $this->_debugData['_updateOrder info'] = 'Going to cancel the order'; // if payment is API check, check if API result pspreference is the same as reference if ($this->_eventCode == Adyen_Payment_Model_Event::ADYEN_EVENT_AUTHORISATION && $this->_getPaymentMethodType() == 'api') { if ($this->_pspReference == $this->_order->getPayment()->getAdditionalInformation('pspReference')) { // don't cancel the order if previous state is authorisation with success=true if ($previousAdyenEventCode != "AUTHORISATION : TRUE") { $this->_holdCancelOrder(false); } else { //$this->_order->setAdyenEventCode($previousAdyenEventCode); // do not update the adyenEventCode $this->_order->setData('adyen_notification_event_code', $previousAdyenEventCode); $this->_debugData['_updateOrder warning'] = 'order is not cancelled because previous notification was a authorisation that succeeded'; } } else { $this->_debugData['_updateOrder warning'] = 'order is not cancelled because pspReference does not match with the order'; } } else { // don't cancel the order if previous state is authorisation with success=true if ($previousAdyenEventCode != "AUTHORISATION : TRUE") { $this->_holdCancelOrder(false); } else { // $this->_order->setAdyenEventCode($previousAdyenEventCode); // do not update the adyenEventCode $this->_order->setData('adyen_notification_event_code', $previousAdyenEventCode); $this->_debugData['_updateOrder warning'] = 'order is not cancelled because previous notification was a authorisation that succeeded'; } } } else { $this->_debugData['_updateOrder info'] = 'Order is already processed so ignore this notification state is:' . $this->_order->getState(); } } else { // Notification is successful $this->_processNotification(); } $this->_order->save(); foreach ($this->_debugData as $debug) { $this->_logger->info($debug); } // set done to true $dateEnd = new \DateTime(); $notification->setDone(true); $notification->setUpdatedAt($dateEnd); $notification->save(); } $this->_logger->info("END OF THE CRONJOB"); }
/** * @return array */ public function getFormFields() { $formFields = []; try { if ($this->_order->getPayment()) { $realOrderId = $this->_order->getRealOrderId(); $orderCurrencyCode = $this->_order->getOrderCurrencyCode(); $skinCode = trim($this->_adyenHelper->getAdyenHppConfigData('skin_code')); $amount = $this->_adyenHelper->formatAmount($this->_order->getGrandTotal(), $orderCurrencyCode); $merchantAccount = trim($this->_adyenHelper->getAdyenAbstractConfigData('merchant_account')); $shopperEmail = $this->_order->getCustomerEmail(); $customerId = $this->_order->getCustomerId(); $shopperIP = $this->_order->getRemoteIp(); $browserInfo = $_SERVER['HTTP_USER_AGENT']; $deliveryDays = $this->_adyenHelper->getAdyenHppConfigData('delivery_days'); $shopperLocale = trim($this->_adyenHelper->getAdyenHppConfigData('shopper_locale')); $shopperLocale = !empty($shopperLocale) ? $shopperLocale : $this->_resolver->getLocale(); $countryCode = trim($this->_adyenHelper->getAdyenHppConfigData('country_code')); $countryCode = !empty($countryCode) ? $countryCode : false; // if directory lookup is enabled use the billingadress as countrycode if ($countryCode == false) { if ($this->_order->getBillingAddress() && $this->_order->getBillingAddress()->getCountryId() != "") { $countryCode = $this->_order->getBillingAddress()->getCountryId(); } } $formFields = []; $formFields['merchantAccount'] = $merchantAccount; $formFields['merchantReference'] = $realOrderId; $formFields['paymentAmount'] = (int) $amount; $formFields['currencyCode'] = $orderCurrencyCode; $formFields['shipBeforeDate'] = date("Y-m-d", mktime(date("H"), date("i"), date("s"), date("m"), date("j") + $deliveryDays, date("Y"))); $formFields['skinCode'] = $skinCode; $formFields['shopperLocale'] = $shopperLocale; $formFields['countryCode'] = $countryCode; $formFields['shopperIP'] = $shopperIP; $formFields['browserInfo'] = $browserInfo; $formFields['sessionValidity'] = date(DATE_ATOM, mktime(date("H") + 1, date("i"), date("s"), date("m"), date("j"), date("Y"))); $formFields['shopperEmail'] = $shopperEmail; // recurring $recurringType = trim($this->_adyenHelper->getAdyenAbstractConfigData('recurring_type')); $brandCode = $this->_order->getPayment()->getAdditionalInformation("brand_code"); // Paypal does not allow ONECLICK,RECURRING only RECURRING if ($brandCode == "paypal" && $recurringType == 'ONECLICK,RECURRING') { $recurringType = "RECURRING"; } $formFields['recurringContract'] = $recurringType; $formFields['shopperReference'] = !empty($customerId) ? $customerId : self::GUEST_ID . $realOrderId; //blocked methods $formFields['blockedMethods'] = ""; $baseUrl = $this->_storeManager->getStore($this->getStore())->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_LINK); $formFields['resURL'] = $baseUrl . 'adyen/process/result'; $hmacKey = $this->_adyenHelper->getHmac(); if ($brandCode) { $formFields['brandCode'] = $brandCode; } $issuerId = $this->_order->getPayment()->getAdditionalInformation("issuer_id"); if ($issuerId) { $formFields['issuerId'] = $issuerId; } $formFields = $this->setBillingAddressData($formFields); $formFields = $this->setShippingAddressData($formFields); $formFields = $this->setOpenInvoiceData($formFields); $formFields['shopper.gender'] = $this->getGenderText($this->_order->getCustomerGender()); $dob = $this->_order->getCustomerDob(); if ($dob) { $formFields['shopper.dateOfBirthDayOfMonth'] = trim($this->_getDate($dob, 'd')); $formFields['shopper.dateOfBirthMonth'] = trim($this->_getDate($dob, 'm')); $formFields['shopper.dateOfBirthYear'] = trim($this->_getDate($dob, 'Y')); } if ($this->_order->getPayment()->getAdditionalInformation(\Adyen\Payment\Observer\AdyenHppDataAssignObserver::BRAND_CODE) == "klarna") { // // needed for DE and AT $formFields['klarna.acceptPrivacyPolicy'] = 'true'; // don't allow editable shipping/delivery address $formFields['billingAddressType'] = "1"; $formFields['deliveryAddressType'] = "1"; // make setting to make this optional $adyFields['shopperType'] = "1"; } // Sort the array by key using SORT_STRING order ksort($formFields, SORT_STRING); // Generate the signing data string $signData = implode(":", array_map([$this, 'escapeString'], array_merge(array_keys($formFields), array_values($formFields)))); $merchantSig = base64_encode(hash_hmac('sha256', $signData, pack("H*", $hmacKey), true)); $formFields['merchantSig'] = $merchantSig; $this->_adyenLogger->addAdyenDebug(print_r($formFields, true)); } } catch (Exception $e) { // do nothing for now } return $formFields; }