load(); $this->client = new Client(); $this->clientId = env('ZOHO_CLIENT_ID'); $this->clientSecret = env('ZOHO_CLIENT_SECRET'); $this->refreshToken = env('ZOHO_REFRESH_TOKEN'); $this->apiDomain = 'https://www.zohoapis.com'; } /** * Generate access token using the self-client flow. */ protected function getAccessToken() { if (Cache::has('zoho_access_token')) { return Cache::get('zoho_access_token'); } try { $response = $this->client->post('https://accounts.zoho.com/oauth/v2/token', [ 'form_params' => [ 'refresh_token' => $this->refreshToken, 'client_id' => $this->clientId, 'client_secret' => $this->clientSecret, 'grant_type' => 'refresh_token', ], ]); $data = json_decode($response->getBody(), true); if (isset($data['access_token'])) { $this->accessToken = $data['access_token']; Cache::put('zoho_access_token', $this->accessToken, 3600); // Cache for 1 hour return $this->accessToken; } else { throw new \Exception('Failed to generate access token: ' . json_encode($data)); } } catch (\Exception $e) { throw new \Exception('Zoho API Error: ' . $e->getMessage()); } } /** * Make a COQL query to Zoho CRM. */ public function makeCoqlQuery($query) { $accessToken = $this->getAccessToken(); try { $response = $this->client->post($this->apiDomain . '/crm/v7/coql', [ 'headers' => [ 'Authorization' => 'Bearer ' . $accessToken, 'Content-Type' => 'application/json', ], 'json' => [ 'select_query' => $query, ], ]); return json_decode($response->getBody(), true); } catch (\Exception $e) { throw new \Exception('Zoho CRM API Error: ' . $e->getMessage()); } } public function getContactsByPhone($phone) { $query = "select Last_Name, First_Name, Full_Name, Lead_Source from Contacts where (Phone = '".$phone."') limit 1"; return $this->makeCoqlQuery($query); } // Generate refresh token using the self-client flow public function generateRefreshToken($selfClientCode) { try { $response = $this->client->post('https://accounts.zoho.com/oauth/v2/token', [ 'form_params' => [ 'code' => $selfClientCode, 'client_id' => $this->clientId, 'client_secret' => $this->clientSecret, 'grant_type' => 'authorization_code', ], ]); $data = json_decode($response->getBody(), true); if (isset($data['refresh_token'])) { $this->refreshToken = $data['refresh_token']; // Save the refresh token to storage, for further save to .env file \Storage::disk('local')->put('zoho_refresh_token.txt', $data['refresh_token']); return $this->refreshToken; } else { throw new \Exception('Failed to generate refresh token: ' . json_encode($data)); } } catch (\Exception $e) { throw new \Exception('Zoho API Error: ' . $e->getMessage()); } } }