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 \Magento\Downloadable\Block\Sales\Order\Email\Items\Order\Downloadable
class.
So, I tried this way:
<?php
namespace Vendor\Module\Block;
use Magento\Framework\View\Element\Template;
use Magento\Sales\Model\Order;
use Magento\Checkout\Model\Session as CheckoutSession;
class Success extends Template
{
protected $order;
protected $checkoutSession;
protected $downloadable;
public function __construct(
Template\Context $context,
Order $order,
CheckoutSession $checkoutSession,
\Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
array $data = [],
\Magento\Downloadable\Block\Sales\Order\Email\Items\Order\Downloadable $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