Skip to content

Get Downloadable Link with Hash

I’m trying to get the downloadable link with hash (like the one present in the email sent to the customer) from my block.

My idea was to call the getPurchasedLinkUrl method of the MagentoDownloadableBlockSalesOrderEmailItemsOrderDownloadable class.

So, I tried this way:

<?php
namespace VendorModuleBlock;

use MagentoFrameworkViewElementTemplate;
use MagentoSalesModelOrder;
use MagentoCheckoutModelSession as CheckoutSession;


class Success extends Template
{
    protected $order;
    protected $checkoutSession;
    protected $downloadable;

    public function __construct(
        TemplateContext $context,
        Order $order,
        CheckoutSession $checkoutSession,
        MagentoCatalogApiProductRepositoryInterface $productRepository,
        array $data = [],
        MagentoDownloadableBlockSalesOrderEmailItemsOrderDownloadable $downloadable
    ) {
        $this->order = $order;
        $this->checkoutSession = $checkoutSession;
        $this->productRepository = $productRepository;
        $this->downloadable = $downloadable;
        parent::__construct($context, $data);
    }

    public function getDownloadableLinks()
    {
        $incrementId = $this->checkoutSession->getLastRealOrder()->getIncrementId();

        $order = $this->order->loadByIncrementId($incrementId);

        $items = $order->getAllItems();
        $downloadableLinks = [];

        foreach ($items as $item) {
            if ($item->getProductType() == 'downloadable') {
                $productId = $item->getProductId();
                $product = $this->productRepository->getById($productId);

                // Get the downloadable links associated with the product
                $extensionAttributes = $product->getExtensionAttributes();
                $links = $extensionAttributes->getDownloadableProductLinks();
            
                foreach ($links as $item) {
                    $downloadableLinks[] = $this->downloadable->getPurchasedLinkUrl($item);
                }
            }
        
            return $downloadableLinks;
        }
    }
}

but it says: Error: Call to a member function getOrder() on null in /var/www/magento/vendor/magento/module-sales/Block/Order/Email/Items/Order/DefaultOrder.php:26