Integrating Sinch SMS in Symfony Application

Aghar Saifeddine
3 min readMar 13, 2024

--

Are you looking to enhance your Symfony application with SMS functionality using Sinch? SMS services are a powerful tool for user verification, notifications, and communication. In this guide, we will walk you through integrating Sinch SMS into your Symfony application step by step.

Prerequisites

Before we begin, ensure you have the following:

  1. Symfony application set up and running.
  2. Sinch account with access to the SMS API.
  3. Sinch API credentials including SINCH_NUMBER, BEARER_TOKEN, SERVICE_PLAN_ID, and REGION

Step 1: Create SinchSMSService Class

Create a new service class SinchSMSService.php under src/Service directory with the following content:

<?php

namespace App\Service;

use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\HttpClient\Exception\TransportException;
use Symfony\Component\HttpClient\HttpClient;
use Symfony\Contracts\HttpClient\Exception\ExceptionInterface;

class SinchSMSService
{
private $httpClient;
private $parameters;

public function __construct(ParameterBagInterface $parameters)
{
$this->httpClient = HttpClient::create();
$this->parameters = $parameters;
}

public function sendSMS($smsData)
{
$response = null;
$errorMessage = null;

try {
$response = $this->httpClient->request('POST', "https://{$this->parameters->get('app.region')}.sms.api.sinch.com/xms/v1/{$this->parameters->get('app.servicePlanId')}/batches", [
'headers' => [
'Authorization' => "Bearer ". $this->parameters->get('app.bearerToken'),
'Content-Type' => 'application/json',
'Accept' => 'application/json',
],
'json' => [
'from' => $this->parameters->get('app.sinchNumber'),
'to' => array($smsData['to']),
'body' => $smsData['body'],
'type' => 'mt_text',
],
]);
$statusCode = $response->getStatusCode();
$content = $response->getContent();

if ($statusCode != 200 && $statusCode != 201) {
$errorMessage = 'API error: HTTP ' . $statusCode . ', Response: ' . $content;
}
} catch (TransportException | ExceptionInterface $e) {
$errorMessage = 'HTTP request failed: ' . $e->getMessage();
}

if ($errorMessage !== null) {
return $errorMessage;
} else {
return $response->getContent();
}
}
}

Step 2: Configure Sinch API Credentials

Update your services.yaml file to configure Sinch API credentials as parameters:

parameters:
app.sinchNumber: '%env(SINCH_NUMBER)%'
app.servicePlanId: '%env(SERVICE_PLAN_ID)%'
app.region: '%env(REGION)%'
app.bearerToken: '%env(BEARER_TOKEN)%'

services:
# default configuration for services in *this* file
_defaults:
autowire: true # Automatically injects dependencies in your services.
autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.

# makes classes in src/ available to be used as services
# this creates a service per class whose id is the fully-qualified class name
App\:
resource: '../src/'
exclude:
- '../src/DependencyInjection/'
- '../src/Entity/'
- '../src/Kernel.php'

Update your .env file with the Sinch API credentials:

###> SMS SINCH ###
SINCH_NUMBER=your_sinch_number
BEARER_TOKEN=your_bearer_token
SERVICE_PLAN_ID=your_service_plan_id
REGION=your_region
###< SMS SINCH ###

Step 3: Create an Endpoint to Send SMS

In your controller or wherever you handle SMS sending logic, inject the SinchSMSService and create a method to send SMS. For example:

#[Route('/send_sms_test', name: 'send_sms_test')]
public function sendSmsTest()
{
// cal the function sendSMS from sinchSMSSender service
$smsData = array(
"to" => 'XXXXXXXXX',
"body" => "Hello Thailand");

$result = $this->sinchSMSSender->sendSMS($smsData);
// Check if the result indicates success or failure
$responseData = [];
if (strpos($result, 'API error') !== false || strpos($result, 'HTTP request failed') !== false) {
// Handle error case
$responseData['status'] = 500;
$responseData['success'] = false;
$responseData['message'] = $result;
} else {
// SMS was sent successfully
$responseData['status'] = 200;
$responseData['success'] = true;
$responseData['message'] = 'OTP SMS sent successfully';
$responseData['api_response'] = $result;
}

// Return the response as JSON
return $this->json($responseData);
}

Replace XXXXXXXXX with the actual phone number you want to send the SMS to.

Step 4: Test and Verify

Run your Symfony application and test the SMS sending functionality. Ensure you handle response codes and errors appropriately in your application logic.

That’s it! You have successfully integrated Sinch SMS into your Symfony application. Feel free to customize the SMS content, recipient numbers, and error handling as per your application requirements.

Happy coding! 🚀

--

--