Create a Drush alias to connect private Remote IP via ssh

What is Drush ?

Drush is a very cool command line utility to perform actions to your Drupal Application.

Drush is a very good friend of Developer. We can do perform below tasks using Drush:

  • Drush helps to manage Drupal website remotely
  • You can Install/enable module(s) using drush. You don’t need to an FTP client to do this
  • You can clear cache using Drush.
  • Check installed modules/themes, you can disable modules using this
  • Drush Provides easier way to code review and Diffs.
  • Maintaining patches using drush is very easy
  • A drush alias is a shortcut to a remote Drupal application, which can be accessible via tunnel or VPN.

    It’s great, that you found it interesting. To use drush from local machine to your private IP like your private EC2 instance.

    Here i am assuming that Drush is already installed to remote machine (If not follow the same step to configure to remote as well). I am going to explain installation, configuration and uses of drush on your local machine to remote machine.

    Install Drush via composer

    Open terminal and run below command

    curl -sS | php 
    mv composer.phar /usr/local/bin/composer
    cd ~/
    touch .bash_profile
    nano .bash_profile
    export PATH="$HOME/.composer/vendor/bin:$PATH"
    composer global require drush/drush:dev-master
    composer global require drush/drush:8.*

    Now Drush is installed on your machine. Now accessing private ip from your Drush alias. Now we are going to create a drush alias that will connect to your remote IP(via VPN) Assuming you already have VPN access to your remote IP.

    To write a drush alias, Open terminal by default your path will be /Users/username/. Now go to the drush folder. Tupe below command for that.

     cd /Users/kundan/.drush 

    Now you are in your Drush directory. create a new drush alais file. file naming convention will be filename.aliases.drushrc.php. To create a file run below command on terminal

    vim filename.aliases.drushrc.php 
    #Alias for
    $aliases['aliasname'] = array(
      'root' => '/var/www/html/drupal',  //path to remote drupal site
      'uri' => '',          // URL 
      'remote-user' => 'username',      // ssh username
      'remote-host'=> 'XX.XXX.XX.XXX,   // Your private IP 
      'ssh-options' => '-o PasswordAuthentication=yes'

    To run this alias, First connect to VPN with your credentials and go to terminal.

    and run

    drush @aliasname status

    It will ask your ssh password and display detail information about your Drupal site.

    In the same way you can run all drush commands. Some are listed below:

    drush @aliasname status
    drush @aliasname cc all
    drush @aliasname pm-list
    drush @aliasname update

    So all this command is getting execute from local to your remote private Server. You can create multiple drush alias in a single file E.g.

    #Alias for
    $aliases['aliasname'] = array(
      'root' => '/var/www/html/drupal',  //path to remote drupal site
      'uri' => '',          // URL 
      'remote-user' => 'username',      // ssh username
      'remote-host'=> 'XX.XXX.XX.XXX,   // Your private IP 
      'ssh-options' => '-o PasswordAuthentication=yes'
    #Alias for
    $aliases['aliasname1'] = array(
      'root' => '/var/www/html/drupal1',  //path to remote drupal site
      'uri' => '',          // URL 
      'remote-user' => 'username',      // ssh username
      'remote-host'=> 'XX.YYY.XX.XXX,   // Your private IP 
      'ssh-options' => '-o PasswordAuthentication=yes'
    #Alias for
    $aliases['aliasname2'] = array(
      'root' => '/var/www/html/drupal2',  //path to remote drupal site
      'uri' => '',          // URL 
      'remote-user' => 'username',      // ssh username
      'remote-host'=> 'XX.XXX.XX.XXX,   // Your private IP 
      'ssh-options' => '-o PasswordAuthentication=yes'

    Magento 2 Guide To Create Custom Api

    As we have already seen how to create a basic module in Magento 2, now lets learn how to create you own custom api. So start creation of your new module by creating module.xml and registration.php. I have created my module ‘CustomApi’ under ‘W3solver’ namespace so below is the code of my module.xml and registration.php


    <?xml version="1.0" encoding="UTF-8"?>
     * @category       W3solver
     * @package        W3solver_CustomApi
     * @Description    module
    <config xmlns:xsi="" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
       <module name="W3solver_CustomApi" setup_version="2.0.1"></module>


     * @category    W3solver
     * @package     W3solver_CustomApi
     * @Description Module registration file
     * @author      W3solver

    Now to create any custom API we need to add ‘webapi.xml’ file under ‘etc’ folder. In below code you can see we have a rest api with method as GET and url as /V1/customapi/shipping/:name, the class to which it refers is W3solver\CustomApi\Api\ShippingInterface

    <?xml version="1.0"?>
    <routes xmlns:xsi="" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Webapi:etc/webapi.xsd">
        <route url="/V1/customapi/shipping/:name" method="GET">
            <service class="W3solver\CustomApi\Api\ShippingInterface" method="exist"/>
                <resource ref="anonymous"/>

    Now we will create the interface(ShippingInterface) file under ‘Api’ folder

    namespace W3solver\CustomApi\Api;
    interface ShippingInterface
         * check if shipping method exists
         * @api
         * @param string $name shipping method name
         * @return bool
        public function exist($name);

    The interface is implemented in its respective model, in our case we are implementing it in Shipping.php file placed directly under ‘Model’ Folder.

    namespace W3solver\CustomApi\Model;
    use W3solver\CustomApi\Api\ShippingInterface;
    class Shipping implements ShippingInterface
        public $shipconfig;
        public $scopeConfig;
        public function __construct(
            \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
            \Magento\Shipping\Model\Config $shipconfig
        ) {
            $this->shipconfig = $shipconfig;
            $this->scopeConfig = $scopeConfig;
         * checks if shipping method is active
         * @api
         * @param string $name shipping method name
         * @return string Greeting message with users name.
        public function exist($name)
            $activeCarriers = $this->shipconfig->getActiveCarriers();
            $storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE;
            foreach ($activeCarriers as $carrierCode => $carrierModel) {
                if ($carrierMethods = $carrierModel->getAllowedMethods()) {
                    foreach ($carrierMethods as $methodCode => $method) {
                        $code = $carrierCode . '_' . $methodCode;
                        if ($code == $name) {
                            return true;
            return false;

    We are all set for your API to test, above API checks the availability of method.

    Integrate Amazon Rekongition service With PHP.

    Ahh! If you have never heard AWS Rekognition service that no need to worry. Rekognition is a service provided by Amazon in the year 2016. Your program can recognize faces, you can compare face, find a specific face, find content from the image and videos.You can moderate the uploaded images/video according to your need. It doesn’t sound excited now but it is a very important and useful in many use case.
    Suppose you have an e-commerce site, where seller uploads their product. The seller is free to upload any product seller can upload an image of Weapon, Drug and some content that you really don’t want to allow on your application. To remove them you have to moderate the products manually. Here AWS Rekognition comes in the picture, by using this service you can write your logic in code and moderate images and video. It helps you to understand the image and you can write your algorithm accordingly.

    Listed things, that you will be required to integrate AWS Recognition.

    1. AWS account. If you don’t have an account you can create.
    2. It will be better if you will create an IAM user and provide the sufficient access permission to him.(Obtain key and secret )
    3. You can get the key, login to aws console -> search IAM -> Users(from left panel)-> security Credential-> Create access key
    4. AWS PHP SDK.

    There are 33 methods exposed by AWS underrecognition service. You can use according to your need. Visit this link to get all methods.

    How to implement this: This service support almost all language. For PHP, AWS has SDK. You need to download this SDK. Follow Command to get AWS PHP SDK.

    Go to your project folder and run command.

    curl -sS | php

    Run composer command and install PHP SDK

    php composer.phar require aws/aws-sdk-php

    That’s it. Now you have PHP SDK with you. You can Use this SDK to integrate all service provided By Amazon.

    You can use aws recognition service with S3 as well as local storage. so let’s start your IDE and Write first code:

    require 'vendor/autoload.php';
    use Aws\Rekognition\RekognitionClient;
    $options = [
        'region' => 'us-west-2',
        'version' => '2016-06-27',
        'credentials' => array(
            'key' => 'Your key',
            'secret'  => 'Your Secret',
    $rekognition = new RekognitionClient($options);
    $fp_image = fopen('test.jpg', 'r');
    $image = fread($fp_image, filesize('test.jpg'));

    Custom Api Module to check if shipment and payment methods are active

    There are lots of api provided by magento but here is the module that provide you a custom api to check if shipment and payment method are active or not. Below you can find out the module zip attached. I have tested my code via postman so below are some screenshot of the same:-

    1. Check for payment method

    Api End Point:- V1/customapi/payment/:paymentmethodname


    2. Check for shipment method

    Api End Point:- V1/customapi/payment/:paymentmethodname

    Versions: I’ve tested the module with the version 2.2.2

    click link to download the extension

    Let me know if you found any issue or have any query.
    Updated on :- 01-02-2018


    Magento 2 Solid Principle

    As soon as you start working with OOPs we came to know about sevral design pattern and SOLID principle is the first thing that we can across. As per magento technical guidelines (under class design)

    Object decomposition MUST follow the SOLID principles

    If you check the Magento code than you can clearly see that Magento code is following SOLID principles. We will look into it these principle one by one:-

    SOLID stands for:

    • Single Responsibility
    • Open-Closed
    • Liskov Substitution
    • Interface Segregation
    • Dependency Inversion

    Single Responsibility Principle

    A class should have only and only one reason to change.

    As its name suggest, it states that every object should have single responsibility i.e, single role to perform and that responsibility should be entirely encapsulated by the class. It means that when we are adding some unrelated feature they should not affect same class.
    For example, In Magento 2 every controller has just one responsibility.

    namespace Magento\Cms\Controller\Page;
    class View extends \Magento\Framework\App\Action\Action {
        public function execute() {
            $pageId = $this->getRequest()->getParam('page_id', $this->getRequest()->getParam('id', false));
            $resultPage = $this->_objectManager->get(\Magento\Cms\Helper\Page::class)->prepareResultPage($this, $pageId);
            if (!$resultPage) {
                $resultForward = $this->resultForwardFactory->create();
                return $resultForward->forward('noroute');
        return $resultPage;

    Open-Closed Principle

    Objects or entities should be open for extension, but closed for modification.

    The above statement itself explains everything that it should be always easy to make behaviour change of particular implementation but we should make changes directly into the original source code. We should make changes by extending the class.

    For example, In Magento 2 if you check module-catalog/Controller/Adminhtml/Category.php it is just initiating category object and rest of the actions (such as:- move, refresh page) are using it by extending the \Magento\Catalog\Controller\Adminhtml\Category class and making behaviour changes as per the requirement.

    namespace Magento\Catalog\Controller\Adminhtml\Category;
    class Move extends \Magento\Catalog\Controller\Adminhtml\Category {
        public function execute() {
            $parentNodeId = $this->getRequest()->getPost('pid', false);
            $prevNodeId = $this->getRequest()->getPost('aid', false);

    Liskov substitution principle

    This principle states that any substitute/child class (implemented by either extension or dependency injection) should adhere the same rules as its predecessor class i.e, it should not break the functionality that is already being used by keeping method signature consistent.

    For example, in below example you can see that toOptionArray() in both class return an array

    namespace Magento\Ups\Model\Config\Source;
    use Magento\Shipping\Model\Carrier\Source\GenericInterface;
    class Generic implements GenericInterface {
        public function toOptionArray()
            $configData = $this->carrierConfig->getCode($this->_code);
            $arr = [];
            foreach ($configData as $code => $title) {
                $arr[] = ['value' => $code, 'label' => __($title)];
            return $arr;
    namespace Magento\Ups\Model\Config\Source;
    class OriginShipment extends \Magento\Ups\Model\Config\Source\Generic
        protected $_code = 'originShipment';
        public function toOptionArray()
            $orShipArr = $this->carrierConfig->getCode($this->_code);
            $returnArr = [];
            foreach ($orShipArr as $key => $val) {
                $returnArr[] = ['value' => $key, 'label' => $key];
            return $returnArr;
        return $returnArr;

    Interface Segregation

    This states that we should not use those method or properties in the interface that the client may not use. Rather than having all method which are related to responsibility it’s good to break it into multiple interfaces and let a single class extends multiple interface. For example see the below image:-

    Dependency Inversion principle

    High level module should not depend on low level moduleFirst of all keep in mind that dependency inversion is not same as dependency injection, although they go hand in hand.

    Magento 2 Design Pattern

    There are lots of design pattern used in Magento, here we will be discussing some of them. We all know design patterns are the solution of some commonly occurring problem during our development phase. They are the recommended way to write our code.

    Service Contract Design Pattern

    Magento is an extension based or modular system, which allows a third-party developer to customize and overwrite core parts of its framework. These customizations may lead to several issues, for example, it will become for developers to keep track of customization done by external extensions. Thus to overcome this Magento comes up with service contract pattern. A service contract is a set of interfaces which act as a layer between an end user and business layer. Thus rather than directly exposing business logic for customization to end user, a layer called service contract comes in between.

    • Service contracts enhances the modularity of Magento.
    • Helps merchants for easy upgrade of Magento
    • Ensure well-defined and durable API that other external and Magento module implements.
    • Provide an easy way to expose business logic via REST or SOAP interfaces.

    Object Manager

    It itself consist of various pattern such as:- Dependency injection, Singleton, Factory, Abstract Factory, Composite, strategy, CQRS, Decorator and many more. We will discussing some most used pattern among these.
    Object manager has a very big role to play, Magento prohibits the direct use of it. Object manager is responsible for implementing factory, singleton and proxy patterns. It automatically instantiates parameter in class constructors. Before moving future lets understand about injectable and non-injectable objects:-

    Injectable objects

    They does not have their own identity such as EventManager, CustomerAccountManagementService.

    Non-injectable objects

    Such as customer, product etc. These entities usually have their identities and state, since they have their identities it is important to know on which exact instance of entity we have to work.

    Dependency Injection

    It is an alternative to Mage in magento 1. It is a concept of injecting the dependent object through external environment rather than creating them internally. Thus we will be asking for resource when our object is being created instead of creating resource when needed. This helps in future modification and testing becomes very easy by mocking required objects. For example:-









    So in the first image, we have read() method in class A which has initialized database connection object but in second image we have injected database connection via a constructor. Now to test our database connection we can easily create mock object during object creation of class A, making our testing much easier. For large object injection Magento have introduced object manager. But using object manager is not a good practice so we use Factory classes and proxy.

    Factory pattern or Factory classes:-

    In Magento 2 Factory classes create a layer between the object manager and business code. Factory classes need not define explicitly as they are auto-generated. We should create factory classes for non-injectable objects.
    Let see the way to get create factory classes:-

    function __construct ( \Magento\Cms\Model\BlockFactory $blockFactory) {
    $this->blockFactory = $blockFactory;
    // calling create will give the object for block class
    $block = $this->blockFactory->create();

    Event Observer pattern

    Events are a way to hook up your functionality in between of code without overriding any core class. An event is dispatched when some actions get triggered. They are very useful when we have to just modify some value of an object rather than overriding that class we can event add an observer to do that. It also prevents someone to touch our core code, anyone can use them without deep knowledge of logic running behind. You can create your own event also by writing following line of code:-


    An observer is certain type of Magento classes that contains the logic which you want to implement in any event. Below is an example of observer class:-

    namespace MyCompany\MyModule\Observer;
    use Magento\Framework\Event\ObserverInterface;
    class MyObserver implements ObserverInterface
      public function __construct()
        //Observer initialization code...
        //You can use dependency injection to get any class this observer may need.
      public function execute(\Magento\Framework\Event\Observer $observer)
        //Observer execution code...

    Proxy Pattern

    Proxy classes are used to work in place of another class and in Magento 2 they are sometimes used in place of resource hungry classes. To understand what proxy classes do let’s see the reason which leads to the occurrence of proxy classes. As we know Magento uses constructor injection for object creation and when we instantiate an object all the classes in its constructor will also instantiate thus leading to a chain of instantiation via a constructor, this can really slow down the process and impact the performance of an application, so to stop chain instantiation Magento uses proxy classes.

    Lets see following code:-



    So in above code, we are using proxy classes for catalogProductStatus and productLink. When we run

     php bin/magento setup:di:compile 

    Magento creates proxy classes on the fly using di.xml with some fixed conventions, thus replacing the original object with a proxy class object. Now let us look at our proxy class to understand how it is working

    namespace Magento\Catalog\Model\Product\Attribute\Source\Status;
    class Proxy extends \Magento\Catalog\Model\Product\Attribute\Source\Status implements \Magento\Framework\ObjectManager\NoninterceptableInterface
    protected $_objectManager = null;
    protected $_instanceName = null;
    protected $_subject = null;
    protected $_isShared = null;
    * Proxy constructor
    * @param \Magento\Framework\ObjectManagerInterface $objectManager
    * @param string $instanceName
    * @param bool $shared
    public function __construct(\Magento\Framework\ObjectManagerInterface $objectManager, $instanceName = '\\Magento\\Catalog\\Model\\Product\\Attribute\\Source\\Status', $shared = true)
    $this->_objectManager = $objectManager;
    $this->_instanceName = $instanceName;
    $this->_isShared = $shared;
    * @return array
    public function __sleep()
    return ['_subject', '_isShared', '_instanceName'];
    * Retrieve ObjectManager from global scope
    public function __wakeup()
    $this->_objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    public function __clone()
    $this->_subject = clone $this->_getSubject();

    Some common convention Magento follow while creation of proxy:-

    • Namespace of proxy class will be same as original (Magento\Catalog\Model\Product\Attribute\Source\Status)
    • Proxy class only extends one object i.e, object manager
    • Has magic functions such as __sleep, __wake which are invoked only on certain action and function such as __clone will make an object of original class and will provide the object only when it is needed (making use of lazy loading design pattern), thus improving the performance of application

    Magento2.2 add custom product tab with custom template on product edit page

    In this blogpost we will learn how to add custom tab in product edit page in admin panel.Create a file with mentioned path and add the following code:-

     <form xmlns:xsi="" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
        <htmlContent name="qrcode" sortOrder="22">
            <argument name="data" xsi:type="array">
                <item name="wrapper" xsi:type="array">
                    <item name="label" xsi:type="string" translate="true">Qrcode</item>
                    <item name="collapsible" xsi:type="boolean">true</item>
                    <item name="opened" xsi:type="boolean">false</item>
            <block class="W3solver\Qrcode\Block\Adminhtml\Catalog\Product\Edit\Tab\Qrcode" name="qrcode">
                    <argument name="config" xsi:type="array">
                        <item name="label" xsi:type="string" translate="true">Qrcode</item>
                        <item name="collapsible" xsi:type="boolean">true</item>
                        <item name="opened" xsi:type="boolean">false</item>
                        <item name="sortOrder" xsi:type="string">11</item>
                        <item name="canShow" xsi:type="boolean">true</item>
                        <item name="componentType" xsi:type="string">fieldset</item>

    Lets understand above code. product_form is used for customization of product edit page in admin panel as per magento documentation(for more info refer the link). So above code will add some htmlcontent which will thus render a block to show your custom tab and its template.

    Now lets create our block at below path

     * @category    W3solver
     * @package     W3solver_Qrcode
     * @Description Block to add qrcode tab to product edit page
     * @author      W3solver
     * @copyright   Copyright (c) 2017 w3solver
    namespace W3solver\Qrcode\Block\Adminhtml\Catalog\Product\Edit\Tab;
    use Magento\Backend\Block\Template\Context;
    use Magento\Framework\Registry;
    use W3solver\Qrcode\Model\QrcodeListFactory;
    class Qrcode extends \Magento\Framework\View\Element\Template {
        protected $_template = 'product/edit/qrcode.phtml';
        protected $_qrcodeListFactory;
        protected $fileName;
         * Core registry
         * @var Registry
        protected $_coreRegistry = null;
         * @param Magento\Backend\Block\Template\Context
         * @param Magento\Framework\Registry
         * @param W3solver\Qrcode\Model\QrcodeListFactory
         * @param Magento\Store\Model\StoreManagerInterface
        public function __construct(
        Context $context, Registry $registry, QrcodeListFactory $qrcodeListFactory, array $data = []
        ) {
            $this->_coreRegistry = $registry;
            $this->_qrcodeListFactory = $qrcodeListFactory;
            parent::__construct($context, $data);
         * Retrieve product
         * @return \Magento\Catalog\Model\Product
        public function getProduct() {
            return $this->_coreRegistry->registry('current_product');

    We also need to create our template file to show whatever content we want at following path:-


    So above code will craete a Qrcode tab on product edit page in admin. Drop in your comments if you face any issue.

    Magento 2 some important coding practice for developers

    In my previous blogpost for code sniffer, we have come to know how we can find if our extension is following MEQP2 standards. Today let us see some most common coding practice that will help us while developing Magento extension. This will make our code more magento friendly.

    Use dependency injection not object manager

    We all love to use object manager though we know it is not a recommended practice by Magento. We should not use it for several reason:-

    a. To maintain code consistency
    b. Testing become easier(as we can pass mock object as an argument)
    c. Dependency injection make dependencies more clear – as everything can be easily found in constructor rather than hidden in middle of the code.
    d. It also prevent us from using repeated dependency as we can make use already existing dependency of parent class

    There are several exception to this scenario:-

    • in static magic methods like __wakeup, serialize, etc
    • in case you should make backward compatibility of constructor
    • in global scope, like in fixtures of integration test.
    • in class that needs only for creation of object like factory, proxy , etc

    You can go through for more details about dependency injection.

    Do not use session in dependency injection

    Whenever you will check your code with MEQP2 standard it will raise an issue if you have used session object in constructor as dependency injection. You will get below error. You can simply replace it from parent class session objects.

    “Session object MUST NOT be requested in constructor. It can only be passed as a method argument. “

    Use Magento exception library not core PHP – Do not throw exception using PHP keyword.

    You can use message manager to show error, warning or ant exception message rather than using throw keyword.
    Include \Magento\Framework\Message\ManagerInterface $messageManager in your constructor and call the respective function to show error, warning or exception.

    Use magento library function instead of core PHP function

    For example for curl request instead of using curl_init, curl_setopt, curl_exec use the function provide by curl class in magento (\Magento\Framework\HTTP\Client\Curl $curl)

    Magento 2 – Address verification using USPS API on checkout.

    This blogpost is related with address verification using USPS on one page checkout page. Address verification is a very critical part of any E-Commerce application. We have to make sure that address is deliverable, in this post we are using USPS APIs for this.

    Note: In this post we are only validating US address as USPS stands for United State Postal Services. 

    You can create a different module for this, or if you already have then add below code. If you don’t know how to create module in Magento 2 Then, Follow this.

    Let’s verify the address in onepage checkout before order place.

    Here I am using my existing module and making some changes for the same.

    I have a module /var/www/html/Project_name/app/code/W3solver/TwilioIntegration/. I am using Ubuntu so my path is like this if anyone is using Mac or window path till project name will vary. Create a di.xml file on below path and add the given code, which will override magento core checkout module payment information model:

    <?xml version="1.0"?>
    <config xmlns:xsi="" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
        <preference for="Magento\Checkout\Model\PaymentInformationManagement" type="W3solver\TwilioIntegration\Model\PaymentInformationManagement" />

    Now create the overriden file (PaymentInformationManagement.php) at below path.


    Add the below code to your file

    namespace  W3solver\TwilioIntegration\Model;
    use Magento\Framework\Exception\CouldNotSaveException;
    class PaymentInformationManagement extends \Magento\Checkout\Model\PaymentInformationManagement {
        public function savePaymentInformationAndPlaceOrder(
            \Magento\Quote\Api\Data\PaymentInterface $paymentMethod,
            \Magento\Quote\Api\Data\AddressInterface $billingAddress = null
        ) {
        	$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
            if(Your_condition )// if you want run this in every condition if(1)
               $address_details = $billingAddress->getStreet();
               $address_detail = $address_details[0];
               $final_address = $address_detail.",".$address_details[1];
               $city = $billingAddress->getCity();
               $state = ($billingAddress->getRegionId() =='12')? 'CA' : 'navada';
               $zipcode = $billingAddress->getPostCode();
               $response =  $this->getStateName($final_address,$city,$state,$zipcode);
                  throw new CouldNotSaveException(__('Please re-check your shipping address'));
                  return false;
               $this->savePaymentInformation($cartId, $paymentMethod, $billingAddress);
               try {
                    $orderId = $this->cartManagement->placeOrder($cartId);
               } catch (\Exception $e) {
                    throw new CouldNotSaveException(
                    __('An error occurred on the server. Please try to place the order again.'), $e
                return $orderId;
                //echo $response;
        public function getStateName($final_address,$city,$state,$zipcode){
            $input_xml = <<<EOXML
                   <AddressValidateRequest USERID="Your USPS User ID will Come here">
                   <Address ID="0">
            $fields = array(
                    'API' => 'Verify',
                    'XML' => $input_xml
            $url = '' . http_build_query($fields);
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 300);
            $data = curl_exec($ch);
            // Convert the XML result into array
            $array_data = json_decode(json_encode(simplexml_load_string($data)), true);
            if (array_key_exists("Error",$array_data['Address'])){
                return  0;
                return 1;

    Go to your Magento 2 installation from terminal and run “php bin/magento setup:upgrade“.

    Try this solution and let us know your thoughts.

    Magento 2 place order without a Email address

    This blogpost guide you a hack to place order in magento 2 via Email. As we all know email is an essential component for managing data in Magento. But today i came across to one of my client who does not want email to be necessary, i told him that this is not possible in Magento but he wanted to implement such functionality. So i came across a hack, i removed validation from client side and passed a random generated email. Here are the steps that i followed:-

    To achieve this we need to override Magento_Checkout/js/action/place-order file and Magento_Checkout/template/form/element/email.html, to do that create a requirejs-config file in your module under view/frontend/requirejs-config.js

    var config = {
        map: {
            '*': {

    Place your overriden file under view/frontend/web/js/action/place-order.js and add the below code. Here we have just added an optional email(, so all order will be placed by this email.

     * Copyright © 2013-2017 Magento, Inc. All rights reserved.
     * See COPYING.txt for license details.
        function (quote, urlBuilder, customer, placeOrderService) {
            'use strict';
            return function (paymentData, messageContainer) {
                var serviceUrl, payload, email;
                payload = {
                    cartId: quote.getQuoteId(),
                    billingAddress: quote.billingAddress(),
                    paymentMethod: paymentData
                if (customer.isLoggedIn()) {
                    serviceUrl = urlBuilder.createUrl('/carts/mine/payment-information', {});
                } else {
                    serviceUrl = urlBuilder.createUrl('/guest-carts/:quoteId/payment-information', {
                        quoteId: quote.getQuoteId()
                    /* added email optional*/
                    if(quote.guestEmail == null) {
                        email = '';
           = email;
                return placeOrderService(serviceUrl, payload, messageContainer);

    Now we will look how to make email as non-required field, for that we have overridden core email.html file, place your overriden file under view/frontend/web/template/form/element/email.phtml and remove the required from email input as seen in below code:-

    <div class="field">
                <label class="label" for="customer-email">
                    <span data-bind="i18n: 'Email Address (Optional)'"></span>
                <div class="control _with-tooltip">
                    <input class="input-text"
                                textInput: email,
                                hasFocus: emailFocused"
                           id="customer-email" />
                    <!-- ko template: 'ui/form/element/helper/tooltip' --><!-- /ko -->
                    <span class="note" data-bind="fadeVisible: isPasswordVisible() == false"><!-- ko i18n: 'You can create an account after checkout.'--><!-- /ko --></span>