0

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}
Sandra Cieseck
  • 311
  • 1
  • 10
  • 1
    you need to change = to => in here `['username' = $username, 'password' = $password, ]` – bhucho Apr 14 '21 at 07:07
  • 1
    _“ get an Server Error 50”_ - and what did the error log have to say about that? – CBroe Apr 14 '21 at 07:46
  • GuzzleHttp\Exception\ServerException with message 'Server error: `POST https://example.com/api/auth` resulted in a `500 INTERNAL SERVER ERROR` response: {"message": "Internal Server Error"} – Sandra Cieseck Apr 14 '21 at 08:25
  • 2
    use try catch then in catch block try to catch request exception, you will get $e use `$e->getMessage();` you will get the full error in 500 – bhucho Apr 14 '21 at 14:34
  • I'm getting: GuzzleHttp\Psr7\Response {#3610} – Sandra Cieseck Apr 14 '21 at 22:00
  • 1
    update the code here what all you have changed – bhucho Apr 15 '21 at 12:51
  • 1
    use this `if ($e->hasResponse()) { print_r($e->getResponse()); die();}` – bhucho Apr 15 '21 at 13:02
  • @bhucho thanks to your input I could debug further and found the solution: return $result->getBody(); Can you provide this as answer so I can accept it? – Sandra Cieseck Apr 15 '21 at 14:44
  • 1
    use `getBody()->getContents()` to get the complete output, I feel like your code needs improvement as a whole so I will post the complete – bhucho Apr 15 '21 at 16:27

1 Answers1

1

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

<?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 {
            $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(\GuzzleHttp\Exception\RequestException $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();
bhucho
  • 3,903
  • 3
  • 16
  • 34
  • Thank you very much! Maybe you can have a look on this follow-up question:L https://stackoverflow.com/questions/67125755/where-to-store-the-jwt-for-authentication-when-laravel-is-used-as-client – Sandra Cieseck Apr 16 '21 at 13:07