twilio = new Client(config('services.twilio.sid'), config('services.twilio.auth_token')); } /** * Purchase a Twilio phone number and set up a webhook for incoming calls. * * @param string $phoneNumber - The phone number to purchase * @param string $companyName - The name of the company for setting the friendly name * @param string $type - The type ('revenue_code' or 'operational_user') * @param string $value - The user full name or revenue code based on type * @return array - Information about the purchased number * @throws Exception */ public function purchasePhoneNumberAndSetWebhook(string $phoneNumber, string $companyName, string $type, string $value) { try { $purchasedNumber = $this->twilio->incomingPhoneNumbers->create([ 'phoneNumber' => $phoneNumber, ]); $webhookUrl = url('/twilio/incoming-call'); $statusCallbackUrl = url('/twilio/call-status'); // URL for status callback $friendlyName = "{$companyName} - {$type} - {$value}"; $this->twilio->incomingPhoneNumbers($purchasedNumber->sid)->update([ 'voiceUrl' => $webhookUrl, 'voiceMethod' => 'POST', 'friendlyName' => $friendlyName, 'statusCallback' => $statusCallbackUrl, // Status callback webhook 'statusCallbackMethod' => 'POST', ]); return [ 'phone_number' => $purchasedNumber->phoneNumber, 'sid' => $purchasedNumber->sid, 'webhook_url' => $webhookUrl, 'status_callback_url' => $statusCallbackUrl, ]; } catch (Exception $e) { throw new Exception("Failed to purchase the phone number or set up the webhook: " . $e->getMessage()); } } /** * Get available phone numbers based on area code. * * @param string $areaCode - The area code to search for available numbers * @return array - List of available phone numbers */ public function getAvailablePhoneNumbers(string $areaCode): array { $availableNumbers = $this->twilio->availablePhoneNumbers('US')->local->read([ 'areaCode' => $areaCode, ]); return collect($availableNumbers)->mapWithKeys(function ($number) { return [$number->phoneNumber => $number->friendlyName]; })->toArray(); } }