DEV Community

Debajyoti Das
Debajyoti Das

Posted on • Updated on

Guzzle Https Requests Laravel

Generating token with from Shiprocket using Laravel 9 and Guzzle Http, however GuzzleHttp\Psr7\Request has not been used.

public static function generateShipRocketToken()
    {
        if(config()->get('shiprocket_email') == null)
            dd('Shiprocket email not et in DB');
        $shiprocketEmailId = config()->get('shiprocket_email'); 
        $shiprocketPassword = config()->get('shiprocket_password'); 
        // Some test code here. Some more test here 
        $last_rec = Setting::all()->last();
        try
        {
            $client = new \GuzzleHttp\Client();
            $headers = [
                "headers" => 
                [
                    'Content-Type' => 'application/json',
                ],
                'body' => json_encode(['email'=>$shiprocketEmailId, 'password'=>$shiprocketPassword]),
                'verify' => false,
            ];

            if($last_rec->shiprocket_token == null)
            { //If token null
                $g_request = $client->requestAsync('POST', 'https://apiv2.shiprocket.in/v1/external/auth/login',$headers)
                ->wait();   
                $response = json_decode($g_request->getBody());
                $token = $response->token;
                $last_rec->update([
                    'shiprocket_token' => $token,
                    'shiprocket_updated_at' => Carbon::now()->format('Y-m-d h:i:s'),
                ]);

            } 
            else
            { 
                // $timeNow = Carbon::now(new \DateTimeZone('Asia/Kolkata')); //If token expired
                $timeNow = Carbon::now(); 
                $lastTokenTime = Carbon::parse($last_rec->shiprocket_updated_at)->format('Y-m-d h:i:s');  
                $hoursDifference = $timeNow->diffInHours($lastTokenTime);  
                $token = null;

                if($hoursDifference > 240)
                {  //if token difference greater than 10 days
                    // Create new token if token more than a day old 
                    $g_request = $client->requestAsync('POST', 'https://apiv2.shiprocket.in/v1/external/auth/login',$headers)
                    ->wait();
                    $response = json_decode($g_request->getBody());
                    $token = $response->token;
                    // Save record into the table 
                    $last_rec->update([
                        'shiprocket_token' => $token,
                        'shiprocket_updated_at' => Carbon::now()->format('Y-m-d h:i:s'),
                    ]);
                }
                else
                {
                    // Get current token //If token not expired
                    $token = $last_rec->shiprocket_token;
                }
            }
        }catch(GuzzleException $e1)
        {
            dd($e1->getMessage());
        }
        return $token;
    } 
Enter fullscreen mode Exit fullscreen mode

General trait function for sending Guzzle Async POST/GET request:

use GuzzleHttp\Exception\GuzzleException;

public static function send_guzzle_aysnc_req($type=null, $url=null, $header=null, $body=null)
    {
        try{
            $client = new \GuzzleHttp\Client();
            if($type == 'POST')
                $g_request = $client->requestAsync($type, $url,['headers'=>[$header], 'body'=>json_encode($body), 'verify' => false,])->wait();
            elseif($type == 'GET')
                $g_request = $client->requestAsync($type, $url,['headers'=>[$header], 'verify' => false,])->wait();

            if($g_request->getStatusCode() == 200)
                $shiprocketResponse = json_decode($g_request->getBody());

            return $shiprocketResponse;
        }
        catch(GuzzleException $e1)
        {
            return response()->json([
                'status'=> $e1->getMessage(),
            ],400);
        }
    }
Enter fullscreen mode Exit fullscreen mode

Top comments (0)