From 2cb1a1865f53162297d0ca5847e9b0114d908d4e Mon Sep 17 00:00:00 2001 From: Aleksandar Todic Date: Thu, 23 Mar 2017 16:22:31 +0100 Subject: [PATCH 01/13] Generate Cart Magento v2 Implementation --- Bread/BreadCheckout/Block/Payment/Form.php | 20 ++ .../Adminhtml/Bread/GenerateCart.php | 105 +++++++++ .../Controller/Adminhtml/Bread/SendMail.php | 61 +++++ .../Controller/Checkout/LandingPage.php | 213 ++++++++++++++++++ .../Controller/Checkout/ValidateOrder.php | 2 +- Bread/BreadCheckout/Helper/Catalog.php | 17 +- Bread/BreadCheckout/Helper/Customer.php | 94 +++++++- Bread/BreadCheckout/Helper/Data.php | 38 ++++ Bread/BreadCheckout/Helper/Quote.php | 35 ++- Bread/BreadCheckout/Helper/Url.php | 43 ++++ .../Model/Payment/Api/Client.php | 21 +- .../Model/Payment/Method/Bread.php | 8 + Bread/BreadCheckout/etc/email_templates.xml | 5 + .../layout/sales_order_create_index.xml | 3 +- .../templates/breadcheckout/css.phtml | 20 ++ .../templates/breadcheckout/info.phtml | 107 ++++++++- .../view/frontend/email/error_report.phtml | 25 ++ .../frontend/email/payment_confirmation.phtml | 24 ++ .../breadcheckout/checkout_items.phtml | 14 ++ 19 files changed, 843 insertions(+), 12 deletions(-) create mode 100644 Bread/BreadCheckout/Controller/Adminhtml/Bread/GenerateCart.php create mode 100644 Bread/BreadCheckout/Controller/Adminhtml/Bread/SendMail.php create mode 100644 Bread/BreadCheckout/Controller/Checkout/LandingPage.php create mode 100644 Bread/BreadCheckout/Helper/Url.php create mode 100644 Bread/BreadCheckout/etc/email_templates.xml create mode 100644 Bread/BreadCheckout/view/frontend/email/error_report.phtml create mode 100644 Bread/BreadCheckout/view/frontend/email/payment_confirmation.phtml create mode 100644 Bread/BreadCheckout/view/frontend/templates/breadcheckout/checkout_items.phtml diff --git a/Bread/BreadCheckout/Block/Payment/Form.php b/Bread/BreadCheckout/Block/Payment/Form.php index 15b5a700..93f4b6d2 100644 --- a/Bread/BreadCheckout/Block/Payment/Form.php +++ b/Bread/BreadCheckout/Block/Payment/Form.php @@ -30,6 +30,26 @@ public function getQuoteDataUrl() return $this->helper->getQuoteDataUrl(); } + /** + * Get controller URL for cart generation + * + * @return string + */ + public function getGenerateCartUrl() + { + return $this->helper->getGenerateCartUrl(); + } + + /** + * Get controller URL for email sending + * + * @return string + */ + public function getSendMailUrl() + { + return $this->helper->getSendMailUrl(); + } + /** * Get button size config setting * diff --git a/Bread/BreadCheckout/Controller/Adminhtml/Bread/GenerateCart.php b/Bread/BreadCheckout/Controller/Adminhtml/Bread/GenerateCart.php new file mode 100644 index 00000000..73f813ed --- /dev/null +++ b/Bread/BreadCheckout/Controller/Adminhtml/Bread/GenerateCart.php @@ -0,0 +1,105 @@ +resultFactory = $context->getResultFactory(); + $this->helper = $helper; + $this->cart = $cart; + $this->config = $scopeConfig; + $this->paymentApiClient = $paymentApiClient; + $this->customerHelper = $customerHelper; + $this->breadMethod = $breadMethod; + $this->urlHelper = $urlHelper; + parent::__construct($context); + } + + /** + * Generate cart from backend + * + * @return \Magento\Framework\Controller\Result\Json + */ + public function execute() + { + try { + $quote = $this->helper->getSessionQuote(); + + $ret = [ "error" => false, + "successRows" => [], + "errorRows" => [], + "cartUrl" => "" + ]; + + if (!$quote || ($quote && $quote->getItemsQty() == 0)) { + throw new Exception(__("Cart is empty")); + } + + if ($quote->getPayment()->getMethodInstance()->getCode() != $this->breadMethod->getMethodCode()) { + throw new Exception(__("In order to checkout with bread you must choose bread as payment option.")); + } + + if (!$this->helper->getShippingOptions()) { + throw new Exception(__("Please specify a shipping method.")); + } + + $arr = []; + + $arr["expiration"] = date('Y-m-d', strtotime("+" . $this->config->getValue('checkout/cart/delete_quote_after', \Magento\Store\Model\ScopeInterface::SCOPE_STORE) . "days")); + $arr["options"] = []; + $arr["options"]["orderRef"] = $quote->getId(); + + $arr["options"]["completeUrl"] = $this->urlHelper->getLandingPageURL(); + $arr["options"]["errorUrl"] = $this->urlHelper->getLandingPageURL(true); + + $arr["options"]["shippingOptions"] = [ $this->helper->getShippingOptions() ]; + + $arr["options"]["shippingContact"] = $this->helper->getShippingAddressData(); + $arr["options"]["billingContact"] = $this->helper->getBillingAddressData(); + + $arr["options"]["items"] = $this->helper->getQuoteItemsData(); + + $arr["options"]["discounts"] = $this->helper->getDiscountData() ? $this->helper->getDiscountData() : []; + + $arr["options"]["tax"] = $this->helper->getTaxValue(); + + $result = $this->paymentApiClient->submitCartData($arr); + + $ret["successRows"] = [ + __("Cart with Financing was successfully created."), + __('Following link can be used by your customer to complete purchase.'), + sprintf('%1$s', $result["url"]) + ]; + + $ret["cartUrl"] = $result["url"]; + + }catch (\Exception $e){ + $ret["error"] = true; + $ret["errorRows"][] = __("There was an error in cart creation:"); + $ret["errorRows"][] = $e->getMessage(); + } + return $this->resultFactory->create(\Magento\Framework\Controller\ResultFactory::TYPE_JSON)->setData($ret); + } +} \ No newline at end of file diff --git a/Bread/BreadCheckout/Controller/Adminhtml/Bread/SendMail.php b/Bread/BreadCheckout/Controller/Adminhtml/Bread/SendMail.php new file mode 100644 index 00000000..4e002a0b --- /dev/null +++ b/Bread/BreadCheckout/Controller/Adminhtml/Bread/SendMail.php @@ -0,0 +1,61 @@ +request = $request; + $this->resultFactory = $context->getResultFactory(); + $this->helper = $helper; + $this->cart = $cart; + $this->config = $scopeConfig; + $this->paymentApiClient = $paymentApiClient; + $this->customerHelper = $customerHelper; + parent::__construct($context); + } + + /** + * Send confirmation email to customer + * + * @return \Magento\Framework\Controller\Result\Json + */ + public function execute(){ + $quote = $this->helper->getSessionQuote(); + + $url = $this->request->getParam("url"); + + $items = $this->helper->getQuoteItemsData(); + $ret = ["error"=>false, + "successRows"=> [], + "errorRows" => [], + ]; + try{ + $this->customerHelper->sendCartActivationEmailToCustomer($quote->getCustomer(), $url, $items); + $ret["successRows"][] = __("Email was successfully sent to your customer."); + + }catch (\Exception $e){ + $ret["error"] = true; + $ret["errorRows"][] = __("An error occurred while sending email:"); + $ret["errorRows"][] = $e->getMessage(); + } + return $this->resultFactory->create(\Magento\Framework\Controller\ResultFactory::TYPE_JSON)->setData($ret); + } + +} \ No newline at end of file diff --git a/Bread/BreadCheckout/Controller/Checkout/LandingPage.php b/Bread/BreadCheckout/Controller/Checkout/LandingPage.php new file mode 100644 index 00000000..323bcf69 --- /dev/null +++ b/Bread/BreadCheckout/Controller/Checkout/LandingPage.php @@ -0,0 +1,213 @@ +request = $request; + $this->paymentApiClient = $paymentApiClient; + $this->customer = $customer; + $this->customerSession = $customerSession; + $this->checkoutSession = $checkoutSession; + $this->quoteRepository = $quoteRepository; + $this->quoteManagement = $quoteManagement; + $this->helper = $helper; + $this->logger = $logger; + $this->customerFactory = $customerFactory; + $this->storeManager = $storeManager; + $this->quoteFactory = $quoteFactory; + $this->cartHelper = $cartHelper; + $this->orderSender = $orderSender; + $this->resultFactory = $context->getResultFactory(); + $this->quoteHelper = $quoteHelper; + $this->customerHelper = $customerHelper; + parent::__construct($context); + } + + /** + * Convert cart to order + * + * @return \Magento\Framework\Controller\Result\Json + */ + public function execute() { + $transactionId = $this->request->getParam("transactionId"); + $orderRef = $this->request->getParam("orderRef"); + + if($transactionId && $orderRef && !$this->request->getParam("error")){ + $this->validateBackendOrder($transactionId,$orderRef); + }else{ + $this->messageManager->addErrorMessage($this->__('There was an error with your financing program')); + $this->_redirect("/"); + } + } + + /** + * Create Magento Order From Backend Quote + * + */ + public function validateBackendOrder($transactionId, $orderRef){ + try { + if ($transactionId) { + + $data = $this->paymentApiClient->getInfo($transactionId); + + $customer = $this->customerFactory->create(); + + $customer->setWebsiteId($this->storeManager->getWebsite()->getId()); + $customer->loadByEmail($data["billingContact"]["email"]); + + $this->customerSession->setCustomerAsLoggedIn($customer); + + $this->processBackendOrder($orderRef, $transactionId, $data); + + $this->_redirect('checkout/onepage/success'); + } + } catch (\Exception $e) { + $this->helper->log($e); + $this->customerHelper->sendCustomerErrorReportToMerchant($e, "", $orderRef, $transactionId); + $this->messageManager->addErrorMessage(__('There was an error with your financing program. Notification was sent to merchant.')); + $this->_redirect("/"); + } + } + + + /** + * Process Order Placed From Bread Pop Up + * + * @param $data + * @throws \Exception + */ + protected function processBackendOrder($orderRef, $transactionId, $data) + { + $quote = $this->quoteFactory->create()->loadByIdWithoutStore($orderRef); + + $this->checkoutSession->setBreadTransactionId($data['breadTransactionId']); + + if (!$quote->getPayment()->getQuote()) { + $quote->getPayment()->setQuote($quote); + } + $quote->getPayment()->setMethod('breadcheckout'); + + $customer = $this->customerFactory->create(); + + $customer->setWebsiteId($this->storeManager->getWebsite()->getId()); + + $customer = $customer->loadByEmail($data["billingContact"]["email"]); + + if (!$customer) { + $quote->setCustomerIsGuest(true); + } + + $quote->setTotalsCollectedFlag(false)->collectTotals()->save(); + + $quote->getPayment()->importData(['method' => 'breadcheckout']); + $quote->getPayment()->setTransactionId($data['breadTransactionId']); + $quote->getPayment()->setAdditionalData("BREAD CHECKOUT DATA", json_encode($data)); + + try { + $order = $this->quoteManagement->submit($quote); + } catch (\Exception $e) { + $this->helper->log(["ERROR SUBMITTING QUOTE IN PROCESS ORDER" => $e->getMessage()]); + $this->logger->critical($e); + throw $e; + } + + $this->checkoutSession + ->setLastQuoteId($quote->getId()) + ->setLastSuccessQuoteId($quote->getId()) + ->clearHelperData(); + + try { + $this->orderSender->send($order); + } catch (\Exception $e) { + $this->logger->critical($e); + $this->checkoutSession->setBreadItemAddedToQuote(false); + } + + if ($customer) { + $this->customerSession->setCustomerAsLoggedIn($customer); + } + + $this->checkoutSession->setLastOrderId($order->getId()) + ->setLastRealOrderId($order->getIncrementId()) + ->setLastOrderStatus($order->getStatus()) + ->setBreadItemAddedToQuote(false); + + $cart = $this->cartHelper->getCart(); + $cart->truncate()->save(); + $cartItems = $cart->getItems(); + foreach ($cartItems as $item) { + $quote->removeItem($item->getId())->save(); + } + + $this->_redirect('checkout/onepage/success'); + } +} \ No newline at end of file diff --git a/Bread/BreadCheckout/Controller/Checkout/ValidateOrder.php b/Bread/BreadCheckout/Controller/Checkout/ValidateOrder.php index 8f3419d0..b13ebb14 100644 --- a/Bread/BreadCheckout/Controller/Checkout/ValidateOrder.php +++ b/Bread/BreadCheckout/Controller/Checkout/ValidateOrder.php @@ -119,7 +119,7 @@ public function execute() } } catch (\Exception $e) { $this->logger->critical($e); - $this->messageManager->addError(__("Checkout With Financing On Product Page Error, Please Contact Store Owner. You may checkout by adding to cart and providing a payment in the checkout process.")); + $this->messageManager->addErrorMessage(__("Checkout With Financing On Product Page Error, Please Contact Store Owner. You may checkout by adding to cart and providing a payment in the checkout process.")); $resultRedirect = $this->resultRedirectFactory ->create() diff --git a/Bread/BreadCheckout/Helper/Catalog.php b/Bread/BreadCheckout/Helper/Catalog.php index 13bb226b..6bb32e9d 100644 --- a/Bread/BreadCheckout/Helper/Catalog.php +++ b/Bread/BreadCheckout/Helper/Catalog.php @@ -12,6 +12,7 @@ class Catalog extends Data { /** @var \Magento\Catalog\Block\Product\View */ protected $productViewBlock; + protected $storeManager; public function __construct( \Magento\Framework\App\Helper\Context $helperContext, @@ -19,9 +20,13 @@ public function __construct( \Magento\Catalog\Block\Product\View $productViewBlock, \Magento\Framework\App\Request\Http $request, \Magento\Framework\Encryption\Encryptor $encryptor, - \Magento\Framework\UrlInterfaceFactory $urlInterfaceFactory + \Magento\Framework\UrlInterfaceFactory $urlInterfaceFactory, + \Magento\Catalog\Api\ProductRepositoryInterfaceFactory $productRepositoryFactory, + \Magento\Store\Model\StoreManagerInterface $storeManager ) { $this->productViewBlock = $productViewBlock; + $this->_productRepositoryFactory = $productRepositoryFactory; + $this->storeManager = $storeManager; parent::__construct($helperContext, $context, $request, $encryptor, $urlInterfaceFactory); } @@ -57,13 +62,13 @@ public function getProductDataArray(\Magento\Catalog\Model\Product $product, $skuString = $this->getSkuString($product, $theProduct); $price = ($lineItemPrice !== null) ? $lineItemPrice * 100 : ( ( $baseProduct == null ) ? $product->getFinalPrice() : $baseProduct->getFinalPrice() ) * 100; - $productData = array( + $productData = [ 'name' => ( $baseProduct == null ) ? $product->getName() : $baseProduct->getName(), 'price' => $price, 'sku' => ( $baseProduct == null ) ? $skuString : ($baseProduct['sku'].'///'.$skuString), 'detailUrl' => ( $baseProduct == null ) ? $product->getProductUrl() : $baseProduct->getProductUrl(), 'quantity' => $qty, - ); + ]; $imgSrc = $this->getImgSrc($product); if( $imgSrc != null ) { @@ -94,7 +99,7 @@ protected function getSkuString(\Magento\Catalog\Model\Product $product, if ($value['option_type'] == 'multiple') { $selectedOptionValues = explode(',', $value['option_value']); } else { - $selectedOptionValues = array($value['option_value']); + $selectedOptionValues = [$value['option_value']]; } foreach ($selectedOptionValues as $selectedOptionValue) { $found = false; @@ -132,7 +137,9 @@ protected function getSkuString(\Magento\Catalog\Model\Product $product, protected function getImgSrc(\Magento\Catalog\Model\Product $product) { if( $this->isInAdmin() ) { - return null; + $product = $this->_productRepositoryFactory->create()->getById($product->getId()); + $imageUrl = $this->storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA) . 'catalog/product' . $product->getImage(); + return $imageUrl; } try { diff --git a/Bread/BreadCheckout/Helper/Customer.php b/Bread/BreadCheckout/Helper/Customer.php index 408aa882..42198f1b 100644 --- a/Bread/BreadCheckout/Helper/Customer.php +++ b/Bread/BreadCheckout/Helper/Customer.php @@ -28,6 +28,12 @@ class Customer extends Data /** @var \Magento\Framework\Math\Random */ protected $random; + /** @var \Magento\Framework\Mail\Template\TransportBuilder */ + protected $_transportBuilder; + + /** @var \Magento\Framework\Translate\Inline\StateInterface */ + protected $inlineTranslation; + public function __construct( \Magento\Framework\App\Helper\Context $helperContext, \Magento\Framework\Model\Context $context, @@ -39,7 +45,9 @@ public function __construct( \Magento\Customer\Model\CustomerFactory $customerFactory, \Magento\Customer\Model\AddressFactory $customerAddressFactory, \Magento\Framework\Json\Helper\Data $jsonHelper, - \Magento\Framework\Math\Random $random + \Magento\Framework\Math\Random $random, + \Magento\Framework\Mail\Template\TransportBuilder $_transportBuilder, + \Magento\Framework\Translate\Inline\StateInterface $inlineTranslation ) { $this->storeManager = $storeManager; $this->customerSession = $customerSession; @@ -47,6 +55,8 @@ public function __construct( $this->customerAddressFactory = $customerAddressFactory; $this->jsonHelper = $jsonHelper; $this->random = $random; + $this->_transportBuilder = $_transportBuilder; + $this->inlineTranslation = $inlineTranslation; parent::__construct($helperContext, $context, $request, $encryptor, $urlInterfaceFactory); } /** @@ -262,4 +272,86 @@ protected function generatePassword($length) return $this->encryptor->getHash($this->random->getRandomString($length), true); } + /** + * Send activation link to customer + * @param \Magento\Customer\Model\Customer customer + * @param url + * @param Array items + */ + public function sendCartActivationEmailToCustomer($customer, $url, $items) + { + $templateOptions = ['area' => \Magento\Framework\App\Area::AREA_FRONTEND, 'store' => $this->storeManager->getStore()->getId()]; + + $templateVars = [ + 'subject' => __("Financing Confirmation"), + 'url' => $url, + 'email' => $customer->getEmail(), + 'firstName' => $customer->getFirstname(), + 'lastName' => $customer->getLastname(), + 'items' => $items, + ]; + + $from = [ + 'email' => $this->scopeConfig->getValue('trans_email/ident_general/email', \Magento\Store\Model\ScopeInterface::SCOPE_STORE), + 'name' => $this->scopeConfig->getValue('trans_email/ident_general/name', \Magento\Store\Model\ScopeInterface::SCOPE_STORE) + ]; + + $this->inlineTranslation->suspend(); + + $to = [$customer->getEmail()]; + + $transport = $this->_transportBuilder->setTemplateIdentifier('payment_confirmation_template') + ->setTemplateOptions($templateOptions) + ->setTemplateVars($templateVars) + ->setFrom($from) + ->addTo($to) + ->getTransport(); + $transport->sendMessage(); + $this->inlineTranslation->resume(); + } + + /** + * Send error report to merchant + * @param Exception exception + * @param response + * @param quoteId + * @param customer + * @param transactionId + */ + public function sendCustomerErrorReportToMerchant($exception, $response="", $quoteId="", $transactionId=null) + { + $templateOptions = ['area' => \Magento\Framework\App\Area::AREA_FRONTEND, 'store' => $this->storeManager->getStore()->getId()]; + + $from = [ + 'name' => $this->scopeConfig->getValue('trans_email/ident_general/name', \Magento\Store\Model\ScopeInterface::SCOPE_STORE), + 'email' => $this->scopeConfig->getValue('trans_email/ident_general/email', \Magento\Store\Model\ScopeInterface::SCOPE_STORE) + ]; + + $templateVars = [ + 'exception_message' => $exception->getMessage(), + 'quote' => $quoteId, + 'token' => $transactionId, + 'response' => $response + ]; + + + $subject = __("Error report"); + + $emailData['subject'] = $subject; + + $this->inlineTranslation->suspend(); + + $recipients = $this->scopeConfig->getValue('sales_email/order/copy_to', \Magento\Store\Model\ScopeInterface::SCOPE_STORE); + if($recipients){ + $transport = $this->_transportBuilder->setTemplateIdentifier('error_report_template') + ->setTemplateOptions($templateOptions) + ->setTemplateVars($templateVars) + ->setFrom($from) + ->addTo(explode(",", $recipients)) + ->getTransport(); + $transport->sendMessage(); + $this->inlineTranslation->resume(); + } + + } } \ No newline at end of file diff --git a/Bread/BreadCheckout/Helper/Data.php b/Bread/BreadCheckout/Helper/Data.php index 5fcad818..0245fba2 100644 --- a/Bread/BreadCheckout/Helper/Data.php +++ b/Bread/BreadCheckout/Helper/Data.php @@ -22,8 +22,11 @@ class Data extends \Magento\Framework\App\Helper\AbstractHelper const URL_SHIPPING_ESTIMATE = "bread/checkout/estimateshipping"; const URL_TAX_ESTIMATE = "bread/checkout/estimatetax"; const URL_CONFIG_DATA = "bread/checkout/configdata"; + const URL_LANDING_PAGE = "bread/checkout/landingpage"; const URL_ADMIN_QUOTE_DATA = "breadadmin/bread/quotedata"; const URL_ADMIN_VALIDATE_PAYMENT = "breadadmin/bread/validatepaymentmethod"; + const URL_ADMIN_GENERATE_CART = "breadadmin/bread/generatecart"; + const URL_ADMIN_SEND_MAIL = "breadadmin/bread/sendmail"; const XML_CONFIG_MODULE_ACTIVE = 'payment/breadcheckout/active'; const XML_CONFIG_LOG_ENABLED = 'payment/breadcheckout/log_enabled'; @@ -49,6 +52,8 @@ class Data extends \Magento\Framework\App\Helper\AbstractHelper const BLOCK_CODE_PRODUCT_VIEW = 'product_view'; const BLOCK_CODE_CHECKOUT_OVERVIEW = 'checkout_overview'; + const API_CART_EXTENSION = 'carts/'; + /** @var \Magento\Framework\Model\Context */ protected $context; @@ -237,6 +242,28 @@ public function getQuoteDataUrl() return $this->urlInterfaceFactory->create()->getUrl(self::URL_ADMIN_QUOTE_DATA, ['_secure'=>$isSecure]); } + /** + * Get controller URL for cart generation + * + * @return string + */ + public function getGenerateCartUrl() + { + $isSecure = $this->request->isSecure(); + return $this->urlInterfaceFactory->create()->getUrl(self::URL_ADMIN_GENERATE_CART, ['_secure'=>$isSecure]); + } + + /** + * Get controller URL for email sending + * + * @return string + */ + public function getSendMailUrl() + { + $isSecure = $this->request->isSecure(); + return $this->urlInterfaceFactory->create()->getUrl(self::URL_ADMIN_SEND_MAIL, ['_secure'=>$isSecure]); + } + /** * Get Admin URL Path for Block Context Url Call * @@ -446,4 +473,15 @@ public function log($data, $context = 'Bread\BreadCheckout'){ $this->logger->debug($data, [$context]); } } + + /** + * Get cart API Url + * + * @param null $store + * @return mixed + */ + public function getCartCreateApiUrl($store = null) + { + return $this->getTransactionApiUrl($store).self::API_CART_EXTENSION; + } } diff --git a/Bread/BreadCheckout/Helper/Quote.php b/Bread/BreadCheckout/Helper/Quote.php index f9ca6110..935ddce2 100644 --- a/Bread/BreadCheckout/Helper/Quote.php +++ b/Bread/BreadCheckout/Helper/Quote.php @@ -235,6 +235,37 @@ public function getShippingAddressData() 'address' => $shippingAddress->getStreetLine(1) . ($shippingAddress->getStreetLine(2) == '' ? '' : (' ' . $shippingAddress->getStreetLine(2))), 'address2' => $shippingAddress->getStreetLine(3) . ($shippingAddress->getStreetLine(4) == '' ? '' : (' ' . $shippingAddress->getStreetLine(4))), 'city' => $shippingAddress->getCity(), + 'email' => $shippingAddress->getEmail(), + 'state' => $shippingAddress->getRegionCode(), + 'zip' => $shippingAddress->getPostcode(), + 'phone' => substr(preg_replace('/[^0-9]+/', '', $shippingAddress->getTelephone()), -10) + ]; + } + + + /** + * Get Bread Formatted Shipping Address Data From Address Model For API + * + * @return array + */ + public function getShippingAddressAPIData() + { + if ($this->isInAdmin()) { + $shippingAddress = $this->orderCreateModel->getShippingAddress(); + } else { + $shippingAddress = $this->getSessionQuote()->getShippingAddress(); + } + + if(!$shippingAddress->getStreetLine(1)){ + return false; + } + + return [ + 'firstName' => $shippingAddress->getFirstname(), + 'lastName' => $shippingAddress->getLastname(), + 'address' => $shippingAddress->getStreetLine(1) . ($shippingAddress->getStreetLine(2) == '' ? '' : (' ' . $shippingAddress->getStreetLine(2))), + 'address2' => $shippingAddress->getStreetLine(3) . ($shippingAddress->getStreetLine(4) == '' ? '' : (' ' . $shippingAddress->getStreetLine(4))), + 'city' => $shippingAddress->getCity(), 'state' => $shippingAddress->getRegionCode(), 'zip' => $shippingAddress->getPostcode(), 'phone' => substr(preg_replace('/[^0-9]+/', '', $shippingAddress->getTelephone()), -10) @@ -284,9 +315,9 @@ public function getSessionQuote() if ($this->isInAdmin()) { $this->quote = $this->orderCreateModel->getQuote(); + }else{ + $this->quote = $this->checkoutSession->getQuote(); } - - $this->quote = $this->checkoutSession->getQuote(); } return $this->quote; diff --git a/Bread/BreadCheckout/Helper/Url.php b/Bread/BreadCheckout/Helper/Url.php new file mode 100644 index 00000000..68a9b2ad --- /dev/null +++ b/Bread/BreadCheckout/Helper/Url.php @@ -0,0 +1,43 @@ +urlHelper = $urlHelper; + parent::__construct($helperContext, $context, $request, $encryptor, $urlInterfaceFactory); + } + + /** + * Get frontend url + * + * @param string $routePath + * @param array $routeParams + * @return string + */ + public function getFrontendUrl($routePath, $routeParams){ + return $this->urlHelper->getUrl($routePath, $routeParams); + } + + /** + * Get The Validate Order URL + * + * @return string + */ + public function getLandingPageURL($error=false) + { + $url = $this->getFrontendUrl(parent::URL_LANDING_PAGE,$error?["error"=>"1"]:[]); + + return preg_replace('/' . preg_quote("?") . '.*?' . '/', '', $url); + } +} \ No newline at end of file diff --git a/Bread/BreadCheckout/Model/Payment/Api/Client.php b/Bread/BreadCheckout/Model/Payment/Api/Client.php index e094aef8..a4e7cd46 100644 --- a/Bread/BreadCheckout/Model/Payment/Api/Client.php +++ b/Bread/BreadCheckout/Model/Payment/Api/Client.php @@ -55,7 +55,7 @@ public function setOrder(\Magento\Sales\Model\Order $order) * @param array $lineItems * @throws \Exception */ - public function cancel($breadTransactionId, $amount = 0, $lineItems = array()) + public function cancel($breadTransactionId, $amount = 0, $lineItems = []) { $data = array('type' => 'cancel'); @@ -192,6 +192,21 @@ public function getInfo($breadTransactionId) \Zend_Http_Client::GET); } + /** + * Submit cart data + * + * @param $data + * @return string + * @throws Exception + */ + public function submitCartData($data) + { + return $this->call( + $this->helper->getCartCreateApiUrl(), + $data, + \Zend_Http_Client::POST); + } + /** * Interact with the API * @@ -217,6 +232,10 @@ protected function call($url, array $data, $method = \Zend_Http_Client::POST) if ($method == \Zend_Http_Client::POST) { curl_setopt($curl, CURLOPT_POST, 1); + curl_setopt($curl, CURLOPT_HTTPHEADER, [ + 'Content-Type: application/json', + 'Content-Length: ' . strlen($this->jsonHelper->jsonEncode($data))] + ); curl_setopt($curl, CURLOPT_POSTFIELDS, $this->jsonHelper->jsonEncode($data)); } diff --git a/Bread/BreadCheckout/Model/Payment/Method/Bread.php b/Bread/BreadCheckout/Model/Payment/Method/Bread.php index c0f26190..a241bf6a 100644 --- a/Bread/BreadCheckout/Model/Payment/Method/Bread.php +++ b/Bread/BreadCheckout/Model/Payment/Method/Bread.php @@ -457,4 +457,12 @@ protected function getValidatedTxId(\Magento\Payment\Model\InfoInterface $paymen throw new \Magento\Framework\Exception\LocalizedException(__('Unable to process request because an invalid transaction ID was provided.')); } } + + /** + * Returns payment method code + * @return string + */ + public function getMethodCode(){ + return $this->_code; + } } \ No newline at end of file diff --git a/Bread/BreadCheckout/etc/email_templates.xml b/Bread/BreadCheckout/etc/email_templates.xml new file mode 100644 index 00000000..6bc7ff25 --- /dev/null +++ b/Bread/BreadCheckout/etc/email_templates.xml @@ -0,0 +1,5 @@ + + +