Skip to content

Cannot redirect to custom page from Observer “sales_order_place_after”

I have this event

“sales_order_place_after”

I need to redirect the customers to a custom page and connect them to an external payment gateway, this page is done, however I can’t figure out how I can redirect the customer to that page from this order observer, I tried it with many solutions but the observer is redirecting to checkout/cart and the order is not executed (completed) and if I remove the redirect code, the order is executed normally, I have nothing in the log files.

    <?php

namespace CybersourceGatewayObserver;

use MagentoFrameworkEventObserverInterface;

class SalesOrderAfterSaveObserver implements ObserverInterface {

    /**
     * @var MagentoFrameworkMessageManagerInterface
     */
    protected $messageManager;

    /**
     * @var PsrLogLoggerInterface 
     */
    protected $logger;

    /**
     * @var MagentoFrameworkAppResponseRedirectInterface
     */
    protected $redirect;

    /**
     * @var MagentoFrameworkAppResponseInterface
     */
    protected $response;
    /**
     * @var MagentoFrameworkAppActionFlag
     */
    protected $_actionFlag;
    
    /**
     * @var MagentoFrameworkAppResponseFactory
     */
    protected $responseFactory;
    
     /**
     * @var MagentoFrameworkUrlInterface
     */
    protected $url;

    public function __construct(
            MagentoFrameworkAppResponseRedirectInterface $redirect,
            MagentoFrameworkMessageManagerInterface $messageManager,
            PsrLogLoggerInterface $logger,
            MagentoFrameworkAppActionFlag $actionFlag,
            MagentoFrameworkAppResponseInterface $response,
            MagentoFrameworkAppResponseFactory $responseFactory,
            MagentoFrameworkUrlInterface $url
    ) {
        $this->redirect = $redirect;
        $this->messageManager = $messageManager;
        $this->logger = $logger;
        $this->response = $response;
        $this->_actionFlag = $actionFlag;
        $this->responseFactory = $responseFactory;
        $this->url = $url;
    }

    public function execute(MagentoFrameworkEventObserver $observer) {
        try {
            $customRedirectionUrl = $this->url->getUrl('customer/account');
            $this->responseFactory->create()->setRedirect($customRedirectionUrl)->sendResponse(); //Redirect to cms page
            $this->logger->debug('paso', [$customRedirectionUrl]);
            // kill the process and redirect to the cms page.
            die();
        } catch (Exception $ex) {
            throw $ex;
        }
    }

}

I literally don’t know why this observer is redirecting to checkout/cart when I tried to redirect to another page.