I use Laravel 5.3 with GuzzleHttp 7 and want to make an API-Call to another Server in order to authorize and get a JSON Web Token in return.
The curl command runs perfectly fine and returns a JSON Web Token with status code 200:
curl -X POST "https://example.com/api/auth" -H "accept: application/json"
-H "Content-Type: application/json" -d "{ "password": "passwd", "username": "foo"}"
In PHP:
<?php
namespace App\Policies;
use GuzzleHttp\Client;
class ApiToken
{
// curl -X POST "https://example.com/api/auth" -H "accept: application/json" -H "Content-Type: application/json" -d "{ "password": "passwd", "username": "foo"}"
public function getToken()
{
$username = 'foo';
$password = 'passwd';
$url ='https://example.com/api/auth';
$client = new Client();
try {
$result = $client->request('POST', $url, [
'headers' => [
'Accept' => 'application/json',
'Content-Type' => 'application/json'
],
'json' => [
'username' => $username,
'password' => $password,
]
]);
Log::info(print_r($result)); // 1
}
catch (exception $e) { // no exception
if ($e->hasResponse()) {
Log::info(print_r($e->getResponse())); // empty
die();
}
}
}
return $result;
}
$apiToken = new ApiToken;
$apiToken->getToken(); // => GuzzleHttp\Psr7\Response {#3619}