0

I am attempting to set up a custom trigger so that when Shipstation writes back it sends out a text message via Twilio. I have it working when adding a tracking number from the admin side but does not appear to work when adding tracking number through Shipstation (I am assuming it is using Magentos API). Is there a different event I should be listening to for this?

etc/events.xml

    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="sales_order_shipment_track_save_after">
    <observer name="mywebsite_model_observer_textshipment"
        instance="MyWebsite\Customizations\Model\Observer\TextShipment" />
</event>

namespace MyWebsite\Customizations\Model\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Sales\Api\Data\ShipmentInterface;
use Magento\Sales\Api\Data\ShipmentTrackInterface;
use Magento\Framework\Exception\CouldNotSaveException;
use Magento\Framework\Exception\NoSuchEntityException;
use Twilio\Rest\Client;

/**
 * Class Shipment
 */
class TextShipment implements ObserverInterface
{
    protected $_logger;

    public function __construct(\Psr\Log\LoggerInterface $logger) {
        $this->_logger = $logger;
    }

    /**
     *
     * @param Observer $observer
     * @return void
     */
    public function execute(Observer $observer)
    {
        $track = $observer->getTrack();
        $shipment = $track->getShipment();
        $order = $shipment->getOrder();
        $shippingAddress = $order->getShippingAddress();
        $telephone = $this->makePhoneNumberValid($shippingAddress->getTelephone());
        $trackUrl = $this->getTrackingUrl($track);
        $countryId = $shippingAddress->getCountryId();
        $firstName = $shippingAddress->getFirstname();

        $initialGreeting = '';

        if($firstName == '' || $firstName == null){
            $initialGreeting = 'Hello <MyWebsite> Customer of the Year! ';
        }else{
            $initialGreeting = 'Hi '. $firstName .'! ';
        }

        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        //$notifier = $objectManager->create('Magento\Shipping\Model\ShipmentNotifier');
        //$notifier->notify($shipment);


        if($countryId == "US" && $telephone != null && $trackUrl != ''){
            // Your Account SID and Auth Token from https://www.twilio.com/console
            $accountSid = "<AccountSID>";
            $authToken = "<Auth>";

            $serviceSid = "<ServiceSID>";

            // Initialize the client
            $client = new Client($accountSid, $authToken);

            //$this->_logger->debug($telephone . ' telenumber'); 


            // Create a notification
            $client->messages->create(
                // the number you'd like to send the message to
                '+1'.$telephone,
                array(
                    // A Twilio phone number you purchased at twilio.com/console
                    'from' => '+<Twilio Number>',
                    // the body of the text message you'd like to send
                    'body' => $initialGreeting . ' Your MyWebsite order has shipped!! You can track it through the following link, ' . $trackUrl . '. It has been a pleasure serving you and look forward to your return. With Love, MyWebsite'
                )
            );
        }

    }

    public function getTrackingUrl($track){

        $trackurl = '';
        if($track->getCarrierCode() === 'fedex'){
            $trackurl = 'https://www.fedex.com/apps/fedextrack/?action=track&trackingnumber='.$track->getNumber();
        }elseif ($track->getCarrierCode() === 'usps') {
            $trackurl = 'https://tools.usps.com/go/TrackConfirmAction_input?qtc_tLabels1='.$track->getNumber();
        }elseif ($track->getCarrierCode() === 'ups') {
            $trackurl = 'https://wwwapps.ups.com/WebTracking/returnToDetails?tracknum='.$track->getNumber();
        }
        return $trackurl;
    }

    public function makePhoneNumberValid($number){
        if($number == null){
            return $number;
        }


        $patterns = array();
        $replacements = array();

        $patterns[] = '/-/';
        $patterns[] = '/\(/';
        $patterns[] = '/\)/';
        $patterns[] = '/\+01/';
        $patterns[] = '/\+1/';
        $patterns[] = '/^$/';

        for ($i = 0; $i < 6; $i++) {
            $replacements[] = ' ';
        }

        $number = preg_replace($patterns, $replacements, $number);

        if($number == "0000000000"){
            return null;
        }

        return $number;
    }
}
......

0

Ran into a similar issue using ShipStation -- doesn't seem to trigger the event sales_order_shipment_track_save_after, instead try using: sales_order_shipment_save_after

And then in your observer, you can get tracking info using the following:

$shipment = $observer->getEvent()->getShipment();
foreach ($shipment->getAllTracks() as $track) {
    var_dump($track->getData()); // get tracking info
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.