简体   繁体   English

以编程方式将产品添加到Magento 2中的购物车

[英]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 我尝试访问此文件www.example.com/add.php,但收到错误消息: HTTP ERROR 500

This is for a new Linux server, running MySQL 5, PHP 7 and Apache 这是用于运行Linux 5,PHP 7和Apache的新Linux服务器

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();
     }
}

Possible Solutions : 可能的解决方案 :
1. give file/folder permission using 1.使用

chmod -R 777 foldername
  1. Make sure your 000-default.conf file of server(if Apache) is pointing to respected folder . 确保服务器(如果为Apache)的000-default.conf文件指向受尊重的folder。 and it should have granted access . 并且它应该已经授予访问权限。

    Require all granted 要求所有授予

hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM