下面的代码用于使用REST API添加产品。我想要实现的是通过webservice添加产品后,我需要调用一个观察者来执行数据插入到另一个表。
在网站上通过admin如果我保存了产品,我可以调用观察者,但在REST API中它不会触发。
// Post Data of Products
$sku = uniqid();
$productData = array(
'sku' => $sku,
'name' => 'Simple Product ' . uniqid(),
'visibility' => 4, /*'catalog',*/
'type_id' => 'simple',
'price' => 0.00,
'status' => 1,
'attribute_set_id' => 9,
'weight' => 1,
"extension_attributes"=> [
"stock_item"=> [
"manage_stock"=> 0,
"is_in_stock"=> 1,
"qty"=> "0"
]],
'custom_attributes' => array(
array( 'attribute_code' => 'category_ids', 'value' => ["3"] ),
array( 'attribute_code' => 'description', 'value' => 'Simple Description' ),
array( 'attribute_code' => 'short_description', 'value' => 'Simple Short Description' ),
array( 'attribute_code' => 'chef_name', 'value' => 'Rafsan Chef' ),
array( 'attribute_code' => 'servings', 'value' => '2 people' ),
array( 'attribute_code' => 'cooking_time', 'value' => '20 minutes' ),
array( 'attribute_code' => 'pdf_upload', 'value' => '123.pdf' ),
array( 'attribute_code' => 'steps', 'value' => 'step 1 content###Step 2 content###Step3 Content' ),
)
);
// creating Product using Magento 2 Rest API
$productData = json_encode(array('product' => $productData));
$ch = curl_init("http://127.0.0.1/magento/index.php/rest/V1/products");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch,CURLOPT_POSTFIELDS, $productData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Authorization: Bearer " . json_decode($token)));
$result = curl_exec($ch);
// the Product is Created using the Above Code
// i have created an observer in magento for product save after, that observer is working if it is saved from website admin End. but not working while saving through Rest Api.
// events.xml file created in app/code/[NAMESPACE]/MODULE_NAME/etc/adminhtml/events.xml
<event name="catalog_product_save_after">
<observer name="cus_recipe_saveafter" instance="Freshbox\Recipes\Observer\Productsaveafter" />
</event>
答案 0 :(得分:3)
您在 app / code / [NAMESPACE] / MODULE_NAME / etc / adminhtml / 文件夹中创建了events.xml文件,因此仅适用于管理区域。
使用REST API也可以从前端区域工作,而不是将events.xml文件放在 app / code / [NAMESPACE] / MODULE_NAME / etc / 文件夹中而不是 app / code / [NAMESPACE] / MODULE_NAME / etc / adminhtml / 文件夹。
答案 1 :(得分:-1)
这是您可以听到的使用rest api添加产品的事件列表
sales_quote_item_set_product
sales_quote_item_qty_set_after
sales_quote_product_add_after
sales_quote_item_save_before
sales_quote_item_save_after
这只是添加产品,而不是更新数量 sales_quote_add_item