Skip to content

Magento2 Get Shipping Address Before Placing Order

I’m trying to check the shipping address of an order being placed using an event observer. I need to get the shipping address before the order is placed so I can cross reference it to places I do not wish to ship to, and either proceed with the order or throw an exception.

app/code/ob7/RestrictedRegions/etc/events.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
  <event name="sales_order_place_before">
    <observer name="ob7_RestrictedRegions_sales_order_place_before" instance="ob7RestrictedRegionsObserverOrderPlaceBefore"/>
  </event>
</config>

app/code/ob7/RestrictedRegions/Observer/OrderPlaceBefore.php:

<?php namespace ob7RestrictedRegionsObserver;

use MagentoFrameworkEventObserverInterface;
use MagentoFrameworkEventObserver;
use MagentoFrameworkExceptionPaymentException;

class OrderPlaceBefore implements ObserverInterface
{

   public function execute(Observer $observer)
   {   

       $order = $observer->getEvent()->getOrder();
       $shippingAddress = $order->getShippingAddress();
       throw new PaymentException(__('Error will appear here'));            
   }
}

This results in an error. Can someone advise me on the proper way to collect the shipping address here?

Removing $shippingAddress = $order->getShippingAddress(); stops the error. But then how do I get the shipping address?