Guzzle Https Requests Laravel

Генерирую токен из Shiprocket с помощью Laravel 9 и Guzzle Http, однако GuzzleHttpPsr7Request не был использован.

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 GuzzleHttpClient();
            $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;
    } 
Вход в полноэкранный режим Выход из полноэкранного режима

Функция общего назначения для отправки асинхронного POST/GET-запроса Guzzle:

use GuzzleHttpExceptionGuzzleException;

public static function send_guzzle_aysnc_req($type=null, $url=null, $header=null, $body=null)
    {
        try{
            $client = new GuzzleHttpClient();
            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);
        }
    }
Войти в полноэкранный режим Выход из полноэкранного режима

Оцените статью
devanswers.ru
Добавить комментарий