以编程方式将产品添加到 Magento 2 中的购物车
Programmatically add product to cart in Magento 2
我尝试访问此文件 www.example.com/add.php 但我收到一条错误消息:HTTP ERROR 500
这是一个新的 Linux 服务器,运行 MySQL 5,PHP 7 和 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();
}
}
可能的解决方案:
1. 使用
授予 file/folder 权限
chmod -R 777 foldername
确保服务器(如果是 Apache)的 000-default.conf 文件指向相关文件夹。它应该已经授予访问权限。
要求全部授予
希望对您有所帮助。
我尝试访问此文件 www.example.com/add.php 但我收到一条错误消息:HTTP ERROR 500
这是一个新的 Linux 服务器,运行 MySQL 5,PHP 7 和 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();
}
}
可能的解决方案:
1. 使用
chmod -R 777 foldername
确保服务器(如果是 Apache)的 000-default.conf 文件指向相关文件夹。它应该已经授予访问权限。
要求全部授予
希望对您有所帮助。