user4817258
user4817258

Reputation: 135

Programmatically add product to cart in Magento 2

I've tried access this file www.example.com/add.php but i got an error message: HTTP ERROR 500

This is for a new Linux server, running MySQL 5, PHP 7 and Apache

namespace Magento\Checkout\Model;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Data\Form\FormKey;
use Magento\Checkout\Model\Cart;
use Magento\Catalog\Model\Product;
class Post extends Action
{
    protected $formKey;   
    protected $cart;
    protected $product;
    public function __construct(
        Context $context,
        FormKey $formKey,
        Cart $cart,
        Product $product) {
            $this->formKey = $formKey;
            $this->cart = $cart;
            $this->product = $product;      
            parent::__construct($context);
    }
    public function execute()
     { 
        $productId =10;
        $params = array(
                    'form_key' => $this->formKey->getFormKey(),
                    'product' => $productId, 
                    'qty'   =>1
                );              
        $product = $this->product->load($productId);       
        $this->cart->addProduct($product, $params);
        $this->cart->save();
     }
}

Upvotes: 0

Views: 860

Answers (1)

Naveen Jain
Naveen Jain

Reputation: 1072

Possible Solutions :
1. give file/folder permission using

chmod -R 777 foldername
  1. Make sure your 000-default.conf file of server(if Apache) is pointing to respected folder . and it should have granted access .

    Require all granted

hope it helps.

Upvotes: 1

Related Questions