调用Amazon Advertising API创建关键词返回错误码422如何解决
问题根因排查
- 请求体未转为JSON格式,与声明的Content-Type不匹配
你设置了Content-Type: application/json请求头,但直接将PHP数组传入CURLOPT_POSTFIELDS,此时cURL会自动将数据编码为application/x-www-form-urlencoded格式,同时会覆盖你设置的Content-Type头,API无法正确解析请求体返回422错误。 - 参数类型不符合接口要求
Amazon Advertising API要求campaignId、adGroupId为数字类型,bid为浮点类型,你代码中三个参数都用了字符串包裹,触发字段类型校验失败。 - 请求体结构不符合接口规范
/v2/sp/keywords接口为批量创建接口,请求体需要是包含关键词对象的数组,哪怕仅创建单个关键词也需要包裹在数组层级中。
修复方案
修改后的完整代码如下:
curl_setopt($ch, CURLOPT_URL, $std_url . "/v2/sp/keywords"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, true); // 修正参数类型,外层包裹数组符合批量接口要求 $keywords = [ [ "campaignId" => 111111111111, // 改为数字类型 "adGroupId" => 2222222222222, // 改为数字类型 "state" => "enabled", "keywordText" => "YetAnotherKeyword", "matchType" => "broad", "bid" => 0.05 // 改为浮点类型 ] ]; // 把数组序列化为JSON字符串 $data_string = json_encode($keywords); curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); $headers = array(); $headers[] = "Content-Type:application/json"; $headers[] = ("Authorization: Bearer " . $accesstoken); $headers[] = ("Amazon-Advertising-API-ClientId: ". $client); $headers[] = ("Amazon-Advertising-API-Scope: " . $API_Scope); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); $result = curl_exec($ch); if (curl_errno($ch)) { echo 'Error:' . curl_error($ch); } curl_close ($ch); echo $result;
如果修改后仍然返回422,可以打印解析返回的错误响应体,Amazon Advertising API的422返回结果会标注具体的字段校验失败原因,比如出价低于站点最低要求、关键词属于禁售品类等,可以根据提示进一步调整参数。
内容的提问来源于stack exchange,提问作者henankoko
相关产品推荐
相关产品推荐

