Skip to content
Advertisement

PHP get JSON Web Token with Guzzle

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 AppPolicies;

use GuzzleHttpClient;
    
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(); // => GuzzleHttpPsr7Response {#3619}

Advertisement

Answer

I have made small changes to your code to make it more better,

<?php

namespace AppPolicies;

use GuzzleHttpClient;
    
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 {
            $guzzleResponse = $client->request('POST', $url, [
                'headers' => [
                    'Accept'     => 'application/json',
                    'Content-Type' => 'application/json'
                ],
                'json' => [
                    'username' => $username,
                    'password' => $password,
                ]
            ]);
            if ($guzzleResponse->getStatusCode() == 200) {
                 $response = json_decode($guzzleResponse->getBody()->getContents(), true);
                 return $response; // or perform your action with $response
                 // see this answer to know why use getContents() https://stackoverflow.com/a/30549372/9471283
                  
            }
        } catch(GuzzleHttpExceptionRequestException $e){
               // you can catch here 400 response errors and 500 response errors
               // You can either use logs here 
               $error['error'] = $e->getMessage();
               $error['request'] = $e->getRequest();
               if($e->hasResponse()){
                   if ($e->getResponse()->getStatusCode() == '400'){
                       $error['response'] = $e->getResponse(); 
                   }
               }
               Log::info('Error occurred in request.', ['error' => $error]);
        } catch(Exception $e){
               //other errors 
        }
    }
   
}

$apiToken = new ApiToken;
$apiToken->getToken();
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement