Skip to content

Facing issue in creating the magento downloadable product with downloadable link and sample link

I am using below code to create downloadable product with downloadablelink and sample link, this script create the product but without links.

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

use MagentoCatalogApiProductRepositoryInterface;
use MagentoCatalogModelProduct;
use MagentoCatalogModelProductAttributeSourceStatus;
use MagentoDownloadableModelProductType;
use MagentoCatalogModelProductVisibility;
use MagentoCatalogModelProductFactory;
use MagentoFrameworkObjectManagerInterface;
use MagentoTestFrameworkHelperBootstrap;

use function PHPUnitFrameworkthrowException;

/** @var ObjectManagerInterface $objectManager */
$objectManager = Bootstrap::getObjectManager();
/** @var ProductFactory $productFactory */
$productFactory = $objectManager->get(ProductFactory::class);
/** @var ProductRepositoryInterface $productRepository */
$productRepository = $objectManager->get(ProductRepositoryInterface::class);

try {
    /** @var Product $product */
    $product = $productFactory->create();
    $product->setTypeId(Type::TYPE_DOWNLOADABLE)
        ->setAttributeSetId($product->getDefaultAttributeSetId())
        ->setName('New downloadable Product')
        ->setSku('downloadable')
        ->setPrice(10)
        ->setVisibility(Visibility::VISIBILITY_BOTH)
        ->setStatus(Status::STATUS_ENABLED)
        ->setWebsiteIds([1])
        ->setStockData(['qty' => 100, 'is_in_stock' => 1, 'manage_stock' => 1])
        ->setNewsFromDate(date('Y-m-d H:i:s', strtotime('-2 day')))
        ->setNewsToDate(date('Y-m-d H:i:s', strtotime('+2 day')))
        ->setDescription('description')
        ->setShortDescription('short desc');


                
        /**
         * @var MagentoDownloadableApiDataLinkInterfaceFactory $linkFactory
         */
        $linkFactory = $objectManager->get(MagentoDownloadableApiDataLinkInterfaceFactory::class);
        $links = [];
        $linkData = [
            'title' => 'Downloadable Product Link',
            'type' => MagentoDownloadableHelperDownload::LINK_TYPE_URL,
            'is_shareable' => MagentoDownloadableModelLink::LINK_SHAREABLE_CONFIG,
            'link_url' => 'http://example.com/downloadable.txt',
            'link_id' => 0,
            'is_delete' => null,
        ];
        $link = $linkFactory->create(['data' => $linkData]);
        $link->setId(null);
        $link->setLinkType($linkData['type']);
        $link->setStoreId($product->getStoreId());
        $link->setWebsiteId($product->getStore()->getWebsiteId());
        $link->setProductWebsiteIds($product->getWebsiteIds());
        $link->setSortOrder(1);
        $link->setPrice(0);
        $link->setNumberOfDownloads(0);
        $links[] = $link;

        $linkData = [
            'title' => 'Downloadable Product Link',
            'sample' => [
                'type' => MagentoDownloadableHelperDownload::LINK_TYPE_URL,
                'url' => 'http://sampleUrl.com',
            ],
            'type' => MagentoDownloadableHelperDownload::LINK_TYPE_FILE,
            'is_shareable' => MagentoDownloadableModelLink::LINK_SHAREABLE_CONFIG,
            'link_url' => 'http://example.com/downloadable.txt',
            'is_delete' => null,
            'number_of_downloads' => 0,
            'price' => 0,
        ];
        /**
         * @var MagentoDownloadableApiDataFileContentInterface $sampleContent
         */
        $sampleContent = $objectManager->create(MagentoDownloadableApiDataFileContentInterfaceFactory::class)->create();
        $sampleContent->setFileData(
            // @codingStandardsIgnoreLine
            base64_encode(file_get_contents(__DIR__ . DIRECTORY_SEPARATOR . DIRECTORY_SEPARATOR . 'test_image.jpg'))
        );
        $sampleContent->setName('jellyfish_1_3.jpg');
        $sampleLink = $linkFactory->create(['data' => $linkData]);
        $sampleLink->setId(null);
        $sampleLink->setSampleType($linkData['sample']['type']);
        $sampleLink->setSampleFileContent($sampleContent);
        $sampleLink->setSampleUrl($linkData['sample']['url']);
        $sampleLink->setLinkType($linkData['type']);
        $sampleLink->setStoreId($product->getStoreId());
        $sampleLink->setWebsiteId($product->getStore()->getWebsiteId());
        $sampleLink->setProductWebsiteIds($product->getWebsiteIds());
        $sampleLink->setSortOrder(2);
        /**
         * @var MagentoDownloadableApiDataFileContentInterface $content
         */
        $content = $objectManager->create(MagentoDownloadableApiDataFileContentInterfaceFactory::class)->create();
        $content->setFileData(
            // @codingStandardsIgnoreLine
            base64_encode(file_get_contents(__DIR__ . DIRECTORY_SEPARATOR . DIRECTORY_SEPARATOR . 'test_image.jpg'))
        );
        $content->setName('jellyfish_2_4.jpg');
        $sampleLink->setLinkFileContent($content);
        $links[] = $sampleLink;

        $downloadableData = [
            'sample' => [
                [
                    'is_delete' => 0,
                    'sample_id' => 0,
                    'title' => 'Downloadable Product Sample Title',
                    'type' => MagentoDownloadableHelperDownload::LINK_TYPE_FILE,
                    'file' => json_encode(
                        [
                            [
                                'file' => '/f/u/jellyfish_1_4.jpg',
                                'name' => 'jellyfish_1_4.jpg',
                                'size' => 1024,
                                'status' => 0,
                            ],
                        ]
                    ),
                    'sample_url' => null,
                    'sort_order' => '0',
                ],
            ],
        ];

        $extension = $product->getExtensionAttributes();

        $samples = [];
        $sampleFactory = $objectManager->create(MagentoDownloadableApiDataSampleInterfaceFactory::class);
        foreach ($downloadableData['sample'] as $sampleData) {
            if (!$sampleData || (isset($sampleData['is_delete']) && (bool)$sampleData['is_delete'])) {
                continue;
            } else {
                unset($sampleData['sample_id']);
                /**
                 * @var MagentoDownloadableApiDataSampleInterface $sample
                 */
                $sample = $sampleFactory->create(['data' => $sampleData]);
                $sample->setId(null);
                $sample->setStoreId($product->getStoreId());
                $sample->setSampleType($sampleData['type']);
                $sample->setSampleUrl($sampleData['sample_url']);
                /**
                 * @var MagentoDownloadableApiDataFileContentInterface $content
                 */
                $content = $objectManager->create(
                    MagentoDownloadableApiDataFileContentInterfaceFactory::class
                )->create();
                $content->setFileData(
                    // @codingStandardsIgnoreLine
                    base64_encode(file_get_contents(__DIR__ . DIRECTORY_SEPARATOR . DIRECTORY_SEPARATOR . 'test_image.jpg'))
                );
                $content->setName('jellyfish_1_4.jpg');
                $sample->setSampleFileContent($content);
                $sample->setSortOrder($sampleData['sort_order']);
                $samples[] = $sample;
            }
        }

        $extension = $product->getExtensionAttributes();
        $extension->setDownloadableProductSamples($samples);
        $extension->setDownloadableProductLinks($links);
        $product->setExtensionAttributes($extension);

    $productRepository->save($product);
} catch(Exception $e) {
    throw new Exception(
        'Error in adding product '
         . $e
    );
}

When I am trying to fetch the links for the same product it gives an empty error

$product = $this->productRepository->get('downloadable');

            $extensionAttributes = $product->getExtensionAttributes();
            $downloadableLinks = $extensionAttributes->getDownloadableProductLinks();

Let me know what I am doing wrong/missing, any help will be much appreciated.