Summer Sale! All accounts are 50% off this week.

ssquare's avatar

Help needed to call api using guzzle http in correct way in case of expire session id

In case of authentication failure (session-id expired, which does after 15minute of inactivity), the only way to get a new session id is to reauthenticate.

And, I have created a helper function to authenticate and could be called at:

$sessionID = TPPAPIHelper::getSessionID();

and my current code: looks like this:

$sessionID = session()->get('TPP_SESSION_ID');
try{
    $response = Http::retry(3, 100)->asForm()->post(config('services.tpp.api_url').'/query.pl', [
        'SessionID' => $sessionID,
        //other params
    ])->throw();
    $body = $response->body();
    if(Str::contains($body, 'ERR: 102')){
        //need to reauthenticate and call api again
    }
}catch(\Exception $e){
    
}

So, in the above case: if I received this ERR: 102 I want to call TPPAPIHelper::getSessionID(); to get a new session id and execute this try block 1 more time, how could I do this correct way?

0 likes
3 replies
Brandon Eichhorn's avatar

Well, you are on the right track. The try {} block is used for trying purposes only. In the catch(Exception $e) you should check for what the exception is named and handle it.

This way you can check in the catch:

// If the exception is: 'not authenticated' <br>
// Create a new session id, if the user is still authenticated within your code.
ssquare's avatar

I could catch the issue but I can't figure out, how to execute the same try block again.

Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

Just have it call itself

public function getStuff($sessionId = null)
{
$sessionID = $sessionId ?? session()->get('TPP_SESSION_ID');
try{
    $response = Http::retry(3, 100)->asForm()->post(config('services.tpp.api_url').'/query.pl', [
        'SessionID' => $sessionID,
        //other params
    ])->throw();
    $body = $response->body();
    if(Str::contains($body, 'ERR: 102')){
        //need to reauthenticate and call api again
    }
}catch(\Exception $e){
    //if it fails
    $sessionId = TPPAPIHelper::getSessionID();
    return $this->getStuff($sessionId);
}
}

Please or to participate in this conversation.