addtocart – Adding product with textfield customisable option programatically via route not showing option value in admin

I’ve got a magento store with some products which have a text field customisable option, and there’s a module to add these products to the cart via a URL – where the product ID and option value are passed in the URL.

This was working fine on an old module under 2.1, but since changing to 2.4.3 it’s stopped working, so I followed the guide here: https://store.magenest.com/blog/how-to-add-products-to-cart/ which I customised the addProductWithOptions() function to accept the option value.

However when the order is placed the value is lost and doesn’t show on clients order summary or in the admin area.

If I visit the product page manually and enter the text into the field, I’ve noticed the format for the options of the window.checkoutConfig.quoteItemData object in the browser console is different. I’ve tried to replicate this format for window.checkoutConfig.quoteItemData.options but this breaks the checkout.

   public function execute () {
       $p = $this->_request->getParam('id');
       if (strpos($p, '-') !== FALSE){
               $aq = explode('-', $p);
               $p = $aq(0);
               $q = $aq(1);
       }

       if ($p < 21) {
          $this->addProductWithOptions($p, $q);
       } else {
           $session = $this->checkoutSession->create();
           $quote = $session->getQuote();
           $product = $this->productRepository->getById($p);
           $quote->addProduct($product, $qty);
           $this->cartRepository->save($quote);
           $session->replaceQuote($quote)->unsLastRealOrderId();
       }
       $this->getResponse()->setRedirect('/checkout/');
   }

   public function addProductWithOptions ($p, $opt_value) {
      $product = $this->productRepository->getById($p);
      $product->addCustomOption('additional_options', $this->json->serialize((
          'option_name' => (
              'label' => __('Option Name'),
              'value' => $opt_value
          )
      )));
      $buyRequest = new MagentoFrameworkDataObject((
          'qty' => 1,
          'related_product' => '',
          'custom_option' => '?'
      ));
      $session = $this->checkoutSession->create();
      $quote = $session->getQuote();
      $quote->addProduct($product, $buyRequest);
      $this->cartRepository->save($quote);
      $session->replaceQuote($quote)->unsLastRealOrderId();
   }

Any advice you could offer would be appreciated. I’m sure it’s down to the $product->addCustomOption() line as mentioned quoteItemData.options is slightly different when manually adding the value via product page.

Thanks in advance

Edit: Just to add I’ve modified the addProductWithOptions function so the quoteItemData object at checkout matches when you fill in the field on the product page itself but value still not pulling through to admin.