當我嘗試發送 Guzzle-POST 時,總是回傳錯誤:
{"errors":[{"code":"0","status":"400","title":"Bad Request","detail":"JSON 負載格式錯誤。"}]}
因為我沒有看到任何錯誤,在資料陣列本身內部,也許它可能是錯誤的標題資訊?這是對我嘗試添加新文章的 shopware 6 API 的簡單 POST 請求。
$payload= [
'headers' => [
'Content-Type' => 'application/json',
'Accept' => 'application/json',
],
'form_params' =>[
"name" => "productname",
"productNumber" => "101003",
"stock" => 2,
"taxId" => "50ee15989533451095c9d7e03d9ce479",
"price" => [
[
"currencyId" => "b7d2554b0ce847cd82f3ac9bd1c0dfca",
"gross" => 15,
"net" => 10,
"linked" => false
]
]
]
];
$response = $client->request('POST', 'http://shopware6.shop.de/api/product',
$data
);
如果我使用 Postman 或 RESTer 或類似工具,我會得到一個肯定的結果,它有效。所以我想我錯過了某事。在我的 guzzle-request 中(這是來自https://shopware.stoplight.io/docs/admin-api/ZG9jOjEyMzA4NTUy-product-data的原始檔案的副本)
我正在使用 guzzle 和 kamermans oauth2 中間件
一個簡單的 GET 請求也可以作業:
$response = $client->request('GET', 'http://shopware6.shop.de/api/product/{productid}',
[
'headers' => [
'Content-Type' => 'application/json',
'Accept' => 'application/json',
]
]
);
uj5u.com熱心網友回復:
您在請求中遺漏了整個身份驗證,您可能故意省略了它,但我認為為了完成起見,我應該在以下示例中添加它。
除此之外,錯誤請求的原因是使用了密鑰'form_params',它只用于Content-Type: multipart/form-data,而不是'json'用于負載。
$response = $client->request('POST', 'http://localhost/api/oauth/token', [
'headers' => [
'Content-Type' => 'application/json',
'Accept' => 'application/json',
],
'json' => [
'grant_type' => 'client_credentials',
'client_id' => '...',
'client_secret' => '...',
],
]);
$token = json_decode($response->getBody()->getContents(), true)['access_token'];
$payload = [
'headers' => [
'Content-Type' => 'application/json',
'Accept' => 'application/json',
'Authorization' => 'Bearer ' . $token,
],
'json' => [
'name' => 'productname',
'productNumber' => '101003',
'stock' => 2,
'taxId' => '...',
'price' => [
[
'currencyId' => '...',
'gross' => 15,
'net' => 10,
'linked' => false,
],
],
],
];
$response = $client->request('POST', 'http://localhost/api/product', $payload);
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/535572.html
標籤:邮政要求狂饮商店用品6
