diff --git a/app/Http/Controllers/TwilioProxyController.php b/app/Http/Controllers/TwilioProxyController.php new file mode 100644 index 0000000..b28b9de --- /dev/null +++ b/app/Http/Controllers/TwilioProxyController.php @@ -0,0 +1,52 @@ +validate([ + 'key' => 'required|string', + 'to' => 'required|string|phone:US', + 'from' => 'required|string|phone:US', + 'message' => 'required|string|max:160', + ]); + + $this->validateSenderKey($validated->key, $validated->from); + + $twilioClient = new Client( + config('services.twilio.sid'), + config('services.twilio.token') + ); + + try { + $message = $twilioClient->messages->create( + $validated->to, + [ + 'from' => $validated->from, + 'body' => $validated->message, + ] + ); + + return response()->json(['success' => true, 'message_sid' => $message->sid]); + } catch (\Exception $e) { + return response()->json(['error' => $e->getMessage()], 500); + } + } + + protected function validateSenderKey(string $key, string $from): void + { + if ( + ! Hash::check($from, $key) + ) { + throw new AuthenticationException('Key is invalid for this sending number.'); + } + } +} diff --git a/config/services.php b/config/services.php index 329b543..e3bf514 100644 --- a/config/services.php +++ b/config/services.php @@ -15,6 +15,7 @@ */ 'twilio' => [ + 'sid' => env('TWILIO_SID', ''), 'auth_tokens' => explode(',', env('TWILIO_AUTH_TOKENS', env('TWILIO_AUTH_TOKEN', ''))), ], diff --git a/routes/api.php b/routes/api.php index e386094..512edf8 100644 --- a/routes/api.php +++ b/routes/api.php @@ -1,9 +1,12 @@ middleware(TwilioSignatureMiddleware::class) ->name('webhooks.twilio'); +