Created
July 12, 2021 12:55
-
-
Save blisssan/0fd144d9bd6a2f526924a30eaa3b24e4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Services; | |
use Illuminate\Support\Facades\Log; | |
use Twilio\Rest\Client; | |
class SmsService | |
{ | |
// send sms using this function Ex: | |
// SmsService::prepareAndSend(919003300303, 'You order is ready to be collected') | |
public static function prepareAndSend($to, $message) | |
{ | |
// optionally you can use any sanitizing or adding signature in this function before sending | |
// to twillio | |
self::sendNotification($to, $message); | |
} | |
public static function sendNotification($to, $message) | |
{ | |
// instead of config('') you can use your own constants | |
// config('services.twillio.enabled') is used to globally enable or disable SMS from being sent | |
if (!config('services.twillio.enabled')) { | |
// skip all the Log::info instead use your own logging function or logging package's function | |
// Log is specific to laravel/Symfony | |
Log::info('Twillio Not Enabled -' . $to . ':' . $message); | |
return; | |
} | |
// constant for twillio's sid | |
// constant for twillio's project token | |
$sid = config('services.twillio.sid'); | |
$token = config('services.twillio.token'); | |
// composer require twilio/sdk needs to be run & include the autoload.php file wherever required | |
// the Client class is from twilio sdk | |
$client = new Client($sid, $token); | |
try { | |
$result = $client->messages->create( | |
'+' . $to, | |
[ | |
'messagingServiceSid' => config('services.twillio.msg_sid'), | |
'from' => config('services.twillio.from'), | |
'body' => $message | |
] | |
); | |
Log::info($result ?? 'No Response in SMS'); | |
return $result; | |
} catch (\Exception $exception) { | |
Log::error('Unable to send SMS'); | |
Log::error($exception->getMessage()); | |
return; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment