session token not generate


  • Re: Failed to generate session token how to generate

    <?php

    namespace App\Services;

    use GuzzleHttp\Client;
    use Illuminate\Support\Facades\Http;
    use Exception;
    use OTPHP\TOTP;
    use Base32\Base32;
    use Illuminate\Support\Facades\Log;

    class AngelOneService
    {
    protected $apiToken;
    protected $apiKey;
    protected $clientCode;
    protected $password;
    protected $totp;

    public function __construct()
    {
        $this->apiKey = env('ANGEL_BROKING_API_KEY');
        $this->clientCode = env('ANGEL_BROKING_CLIENT_CODE');
        $this->password = env('ANGEL_BROKING_PASSWORD');
        $this->totp = env('ANGEL_BROKING_TOTP'); // Optional, if 2FA is enabled
        $this->totpSecret = env('ANGEL_BROKING_TOTP_SECRET'); 
        $this->apiToken = $this->getAccessToken();
    }
    
    public function generateTOTPCode()
    {
    
        $secret = $this->totpSecret;  // Example, if not Base32 encoded
        $base32Secret = Base32::encode($secret);
    
        if (!$base32Secret) {
            throw new Exception('TOTP Secret is not set in the environment file.');
        }
    
        $totp = TOTP::create($base32Secret);
    
    
        return  $totp->now(); // This will generate the current 6-digit TOTP code
        
        
    }
    
    
    public function getSymbolToken($symbol)
    {  
        if (!$this->apiToken) {
            throw new Exception('API token is not set. Check your configuration.');
        }
    
        Log::info('Using API token: ' . $this->apiToken);
    
        $response = Http::withToken($this->apiToken)->get('https://margincalculator.angelbroking.com/OpenAPI_File/files/OpenAPIScripMaster.json', [
            'symbol' => $symbol,
        ]);
        
        Log::info('Response: ' . $response->body());
    
        if ($response->successful()) {  
            $data = $response->json();
    
            if (is_array($data) && isset($data['symboltoken'])) {
                return $data['symboltoken'];
            } else {
                throw new Exception('Invalid response format or symboltoken not found in response.');
            }
        }else {
            throw new Exception('Failed to fetch symbol token: ' . $responseBody);
        }
    }
    
    public function placeOrder(array $orderData)
    {      
        $headers = [
            'Authorization' => 'Bearer ' . $this->apiToken,
            'Content-Type' => 'application/json',
            'Accept' => 'application/json',
            'X-ClientCode' => env('ANGEL_BROKING_CLIENT_CODE'),
            'X-API-Key' => env('ANGEL_BROKING_API_KEY'),
        ];
    
        Log::info('Headers: ' . json_encode($headers));
    
        $response = Http::withHeaders($headers)->post('https://apiconnect.angelbroking.com/rest/secure/angelbroking/order/v1/placeOrder', $orderData);
        
        if ($response->successful()) {
            return $response->json();
        } else {
            throw new Exception('Failed to place order: ' . $response->body());
        }
    }
    
    protected function generateSessionToken()
    {
        $client = new Client();
    
        try 
        {   
            $totpCode = $this->generateTOTPCode();
    
            $response = $client->post('https://apiconnect.angelbroking.com/rest/auth/angelbroking/user/v1/loginByPassword', [
                            'json' => [
                                'clientcode' => env('ANGEL_BROKING_CLIENT_CODE'),
                                'password' => env('ANGEL_BROKING_PASSWORD'),
                                'totp' => $totpCode,
                            ],
                            'headers' => [
                                'X-API-Key' => $this->apiKey,
                                'Content-Type' => 'application/json',
                                'Accept' => 'application/json',
                                'X-UserType' => 'USER',
                                'X-SourceID' => 'WEB',
                                'X-ClientLocalIP' => $_SERVER['SERVER_ADDR'],
                                'X-ClientPublicIP' => file_get_contents('https://api.ipify.org'),
                                'X-MACAddress' => 'f8:32:e4:9c:27:0d',
                            ],
                        ]);
    
    
            $statusCode = $response->getStatusCode();
            $responseBody = $response->getBody()->getContents();
    
            dd($responseBody);
            $responseData = json_decode($responseBody, true);
           
            Log::info('API Response:', ['status' => $statusCode, 'body' => $responseBody]);
    
            if ($statusCode == 200) {
                if (isset($responseData['data']['jwtToken'])) {
                    return $responseData['data']['jwtToken'];
                } elseif (isset($responseData['success']) && !$responseData['success']) {
                    $errorMessage = isset($responseData['message']) ? $responseData['message'] : 'Unknown error occurred';
                    throw new Exception('Failed to generate session token: ' . $errorMessage);
                }
                throw new Exception('Failed to generate session token: Unexpected response');
            } else {
                throw new Exception('Failed to generate session token: Status Code ' . $statusCode);
            }
        } catch (Exception $e) {
            dd($e);
            Log::error('Error generating session token: ' . $e->getMessage());
            throw $e;
        }
    } 
    
    protected function generateAccessToken($sessionToken)
    {    
        $client = new Client();
    
        $response = $client->post('https://api.angelbroking.com/rest/auth/angelbroking/user/v1/token', [
            'json' => [
                'refreshToken' => $sessionToken,
            ],
            'headers' => [
                'X-API-Key' => $this->apiKey,
                'Content-Type' => 'application/json',
            ],
        ]);
    
        if ($response->getStatusCode() == 200) {
            $data = json_decode($response->getBody(), true);
            return $data['data']['accessToken'];
        } else {
            throw new Exception('Failed to generate access token: ' . $response->getBody());
        }
    }
    
    protected function getAccessToken()
    {
        try {
            $sessionToken = $this->generateSessionToken();
            $accessToken = $this->generateAccessToken($sessionToken);
            return $accessToken;
        } catch (Exception $e) {
            Log::error('Error generating access token: ' . $e->getMessage());
            throw $e;
        }
    }
    

    }

    ANGEL_BROKING_CLIENT_CODE=H56857442
    ANGEL_BROKING_PASSWORD=5285
    ANGEL_BROKING_TOTP=BDODBV4DALNVJGAPS4R7YS3J7A

    does not generate session token how to solve