使用Magento REST API创建销售规则时遇必填字段错误求助
Hey there, I see exactly what's going on here! The error message is telling you that the API expects a top-level rule key in your request body, but your current payload doesn't wrap the sales rule data inside it. Magento's /V1/salesRules endpoint requires all the rule parameters to be nested under this rule key.
Let's walk through the fixes step by step:
1. Wrap Your Rule Data in a rule Key
Modify your $data array to nest all the rule parameters inside a rule key—this is the core fix for your current error:
$data = [ 'rule' => [ 'name' => '40% Off on Large Orders', 'store_labels'=> [], 'description' => 'Test sales rule', 'website_ids' => [1,3], 'customer_group_ids' => [0, 1, 2, 3], "from_date" => "2018-01-03", 'uses_per_customer' => 0, 'is_active' => true, // Add your remaining rule parameters (like conditions/actions) here ] ];
2. Fix a Typo in Your HTTP Header
I also spotted a small typo in your token request header that could cause unexpected issues later: Content-Lenght should be Content-Length. Let's correct that:
curl_setopt($ch, CURLOPT_HTTPHEADER, array( "Content-Type: application/json", "Content-Length: " . strlen(json_encode($userData)) ));
3. Full Modified Code Snippet
Here's the updated version of your code with both fixes applied:
$userData = array("username" => "admin", "password" => "admin123"); $ch = curl_init("http://test.local/index.php/rest/V1/integration/admin/token"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($userData)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Fixed the Content-Length typo here curl_setopt($ch, CURLOPT_HTTPHEADER, array( "Content-Type: application/json", "Content-Length: " . strlen(json_encode($userData)) )); $token = curl_exec($ch); // Wrapped all rule data inside the required 'rule' key $data = [ 'rule' => [ 'name' => '40% Off on Large Orders', 'store_labels'=> [], 'description' => 'Test sales rule', 'website_ids' => [1,3], 'customer_group_ids' => [0, 1, 2, 3], "from_date" => "2018-01-03", 'uses_per_customer' => 0, 'is_active' => true, // Include any other mandatory rule fields here (e.g., condition/action settings) ] ]; $ch = curl_init("http://test.local/index.php/rest/V1/salesRules"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); 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); var_dump($result);
Just a quick reminder: Make sure you fill in any remaining required fields (like conditions or actions) inside the rule array. The Magento API specifies all mandatory fields, but wrapping your data in the rule key will resolve the exact error you're facing right now.
内容的提问来源于stack exchange,提问作者Kashif

