【发布时间】:2020-07-14 16:18:03
【问题描述】:
我有一个简单的注册表单,用户可以在我的应用中注册,现在我想将提交的数据发送到另一个服务。
首先,我使用邮递员面板中的原始选项测试我的请求,如下所示。
API 网址:app3.salesmanago.pl/api/contact/upsert
JSON DATA:
{
"clientId":"w2ncrw06k7ny45umsssc",
"apiKey":"ssssj2q8qp4fbp9qf2b8p49fz",
"requestTime":1327056031488,
"sha":"ba0ddddddb543dcaf5ca82b09e33264fedb509cfb4806c",
"async" : true,
"owner" : "adam@rce.com",
"contact" : {
"email" : "test-1@konri.com",
"name" : "Test",
"address":{
"streetAddress":"Brzyczynska 123",
}
}
}
UPDATE 我得到以下成功结果
{
"success": true,
"message": [],
"contactId": "b52910be-9d22-4830-82d5-c9dc788888ba",
"externalId": null
}
现在在 laravel 中使用 guuzle htpp 请求
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
$client = new client();
$current_timestamp = Carbon::now()->timestamp;
try {
$request = $client->post('app3.salesmanago.pl/api/contact/upsert', [
\GuzzleHttp\RequestOptions::HEADERS => array(
'debug' => true,
'Accept' => 'application/json',
'Content-Type' => 'application/json',
'clientId' => 's255hncrw06k7ny45umc',
'apiKey' => 'sj2q8rt5qp4fbp9qf2b8p49fz',
'sha' => 'ba0br45543dcaf5ca82b09e33264fedb509cfb4806c',
'requestTime' => $current_timestamp,
'owner' => 'adwamtrw@fere.com',
'http_error' => true
),
\GuzzleHttp\RequestOptions::JSON => [
'form_params' => [
'name' => $data['name'],
'email' => $data['email'],
],
],
]);
}
catch (GuzzleHttp\Exception\ClientException $e) {
$response = $e->getResponse();
$responseBodyAsString = $response->getBody()->getContents();
}
$status = $request->getStatusCode();
$response = $request->getBody();
$r = json_decode($response);
dd($r);
dd($status, $r );
return $user;
}
当我运行我的应用程序并发送表单数据时,我使用与邮递员相同的数据得到这个
{#306 ▼
+"success": false
+"message": array:1 [▼
0 => "Not authenticated"
]
+"contactId": null
+"externalId": null
}
好像我的API key和其他header数据没有按要求传递给header,
谁能告诉我我在这里做错了什么?
【问题讨论】:
-
为什么
headers在\GuzzleHttp\RequestOptions::JSON里面? -
@FelippeDuarte 你能提供正确的方法吗?
-
您作为json数据发布的第一个sn-p属于传递给api的标头还是POST请求的主体?因为如果它是有效负载而不是标头,那么您应该修改下面的代码以将身份验证值作为正文的一部分发送,而不是像您现在在 Guzzle 中所做的那样发送标头。
-
@DraQ 上面的 sn-ps 来自 API 文档,我只是更改并添加了我的 API 密钥、sha 等,并将其发布在邮递员中,运行 post 给我成功,但在 guzzle 中,我有错误,你能以代码的形式显示你在说什么吗?
-
header 和 body 是有区别的。你如何在邮递员中填写这些信息?作为标题还是作为正文?如果是标题,则需要将
headers键移到\GuzzleHttp\RequestOptions::JSON之外。
标签: php laravel laravel-5 guzzle guzzle6