Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 52 additions & 0 deletions app/Http/Controllers/TwilioProxyController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
<?php

namespace App\Http\Controllers;

use Exception;
use Illuminate\Auth\AuthenticationException;
use Twilio\Rest\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class TwilioProxyController extends Controller
{
public function __invoke(Request $request)
{
$validated = (object) $request->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.');
}
}
}
1 change: 1 addition & 0 deletions config/services.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
*/

'twilio' => [
'sid' => env('TWILIO_SID', ''),
'auth_tokens' => explode(',', env('TWILIO_AUTH_TOKENS', env('TWILIO_AUTH_TOKEN', ''))),
],

Expand Down
7 changes: 5 additions & 2 deletions routes/api.php
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
<?php

use App\Http\Controllers\Webhooks\TwilioWebhookController;
use App\Http\Middleware\TwilioSignatureMiddleware;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\TwilioProxyController;
use App\Http\Controllers\Webhooks\TwilioWebhookController;

Route::post('/proxy/twilio', TwilioProxyController::class);

Route::post('/webhooks/twilio', TwilioWebhookController::class)
// ->middleware(TwilioSignatureMiddleware::class)
->name('webhooks.twilio');