首先,这里有一些测试代码,您应该能够根据自己的目的进行调整(另请参阅form_params
GuzzleHttp 的文档):
public function validateRecaptcha()
{
$client = new Client;
$response = $client->request('POST', 'https://www.google.com/recaptcha/api/siteverify', [
'form_params' => [
'secret' => env('RECAPTCHA_SECRET'),
'response' => Request::input('g-recaptcha-response'),
'remoteip' => Request::ip()
]
]);
return $response;
}
我刚刚遇到了同样的问题,发现尝试在 Laravel 中返回响应对象给了我ERR_INVALID_CHUNKED_ENCODING
. 鉴于,dd()
对响应本身进行操作向我展示了我真正想看到的内容:
public function validateRecaptcha()
{
$client = new Client;
$response = $client->request('POST', 'https://www.google.com/recaptcha/api/siteverify', [
'form_params' => [
'secret' => env('RECAPTCHA_SECRET'),
'response' => Request::input('g-recaptcha-response'),
'remoteip' => Request::ip()
]
]);
dd($response);
}
不幸的是,没有做进一步的研究,我无法解释为什么ERR_INVALID_CHUNKED_ENCODING
当我尝试将客户端库的对象返回给浏览器时不断出现,但我最初的倾向是这是一个数据类型问题。
就您的问题而言,您实际上并没有试图取回“请求”,而是回复。根据http://docs.guzzlephp.org/en/latest/quickstart.html#using-responses,如果您想获取响应对象中包含的 API 响应(或者至少在我的情况下,我做到了),您'会想要使用的getBody()
方法:
public function validateRecaptcha()
{
$client = new Client;
$response = $client->request('POST', 'https://www.google.com/recaptcha/api/siteverify', [
'form_params' => [
'secret' => env('RECAPTCHA_SECRET'),
'response' => Request::input('g-recaptcha-response'),
'remoteip' => Request::ip()
]
]);
return $response->getBody();
}
当然,如果您希望它是 JSON 响应(即 REST),那么只需将其传递json_decode()
给您的关联数组即可。
public function validateRecaptcha()
{
$client = new Client;
$response = $client->request('POST', 'https://www.google.com/recaptcha/api/siteverify', [
'form_params' => [
'secret' => env('RECAPTCHA_SECRET'),
'response' => Request::input('g-recaptcha-response'),
'remoteip' => Request::ip()
]
]);
return json_decode($response->getBody(), true); // true = assoc. array
}
希望有帮助!