TRAI DLT-compliant routes on Jio, Airtel, Vi and BSNL
CRM integration

Salesforce SMS Gateway Integration: Apex, Triggers and Flow

Send SMS from Salesforce when a case closes, an opportunity moves or a lead arrives. This guide gives you an Apex service class, an async trigger, a Flow action and a test class that call our SMS API through a named credential. You deploy the code yourself; there is no package to install.

Updated · 20 min read · OnlineSMSService team, Coimbatore

Quick answer

Salesforce sends SMS through OnlineSMSService with an Apex callout to https://whitelabled.securesmsc.com/api/v2/sms/send. Set this URL up as a named credential so the API key stays out of your code. Triggers can't make callouts, so they hand the work to a Queueable job. Flows use an invocable action on a "Run Asynchronously" path. Before the first call, create a separate API key for Salesforce and add Salesforce's IP ranges to it. Otherwise the key locks to the first Salesforce server that uses it, and other servers get 403. There is no AppExchange package: you deploy the classes on this page.

What you can automate

Apex service class

One reusable class builds the request, calls the API through the named credential and reads every success and error reply.

Trigger-based SMS

Send automatically when a record is created or changes, such as a case closing. The trigger queues an async job.

Flow action

Admins add "Send SMS (OnlineSMSService)" to any flow and map the fields without writing code.

Typical uses: a welcome SMS for new leads, opportunity stage updates, appointment reminders, order status updates from custom objects, and a follow-up after a case closes. Each message must match a DLT template that is approved in the right category. Service and transactional templates can go out at any time. Promotional messages go out only between 9 AM and 9 PM. See what the -P, -S, -T and -G header suffixes mean.

Prerequisites

SalesforceOnlineSMSService
Enterprise, Performance, Unlimited or Developer Edition. Professional Edition can't run your own Apex.An account and an API key for Salesforce only. Create it under API & Integrations → API Management.
A user who can deploy Apex (a sandbox or Developer org first).An approved DLT header (sender ID, e.g. ACMEIN) mapped to your account.
A named credential for the API. The steps are in Using a named credential below; set it up before you run any code.An approved DLT template for every message you send.
A permission set giving the sending users access to the credential.Salesforce's IP ranges in the key's IP whitelist (next section).

We file DLT registration for you: a new registration costs ₹5,900 (₹5,000 + 18% GST) and is valid for one year and renewed every year. Renewal is separate, and we remind you before it lapses. Linking an entity you already have is free. Approval usually takes 2–7 business days.

Get a free API key + 100 test SMS. Create your account and API key now. Verified businesses also get 100 free test SMS once KYC and DLT mapping are done.

Allow Salesforce's IP ranges before the first call

This is the most common reason CRM integrations fail. Each API key has its own list of allowed IP addresses. If the list is empty, the first IP that calls with the correct key is added to it automatically. After that, every other IP gets 403 "IP address not allowed. Please whitelist your IP address to access the API." Salesforce makes callouts from many servers, so the first SMS works and later ones fail.

  1. Create a separate API key for SalesforceUse one key per org, and keep sandbox and production apart. A change for Salesforce then never breaks your website or app.
  2. Add Salesforce's ranges before the first callOpen API & Integrations → API Management → IP Whitelisting for that key. Add the IPv4 ranges in CIDR form. Once the list has at least one entry, nothing is added automatically.
  3. Already locked to one IP?Add the full list first, then remove the wrong IP. If you remove it first, the list is empty for a moment and locks again to the next caller. You can also ask our support team to reset the key's list.

Where to get Salesforce's ranges. Salesforce lists them in its help article Salesforce Core Services – IP Addresses and Domains to Allow (last changed 15 September 2026). The Hyperforce ranges are also published as JSON at ip-ranges.salesforce.com/ip-ranges.json. The file dated 16 October 2026 has 50 IPv4 ranges across 25 regions. Add the ranges for your org's region. If you aren't sure of the region, add all of them. Orgs not yet on Hyperforce should also add the ranges from the help article. If a call is still refused, our support team can see the refused IP in the key's log.

Method 1: Apex SMS service class

This class sends one SMS and returns a result object. It builds the JSON body the API expects, cleans Indian mobile numbers and reads every reply. It uses callout:OnlineSMS_API, so it needs no Remote Site Setting and holds no API key.

Apex: OnlineSmsService.cls

/**
 * Sends one SMS through the OnlineSMSService API (v2).
 * Named credential OnlineSMS_API = https://whitelabled.securesmsc.com/api/v2
 * Its external credential adds the X-API-Key header, so no key is stored in code.
 */
public with sharing class OnlineSmsService {

    public static final String ENDPOINT = 'callout:OnlineSMS_API/sms/send';
    public static final String DEFAULT_SENDER_ID = 'ACMEIN'; // your approved DLT header

    public class SmsMessage {
        public String recipient;
        public String message;        // must match an approved DLT template
        public String senderId;       // optional; DEFAULT_SENDER_ID if blank
        public String dltTemplateId;  // optional; always a string
        public String route;          // optional: 'transactional' or 'promotional'
        public Id relatedId;          // optional: record to log the result on

        public SmsMessage(String recipient, String message) {
            this.recipient = recipient;
            this.message = message;
        }
    }

    public class SmsResult {
        public Boolean success = false;
        public Integer statusCode;
        public String messageId;
        public String status;
        public String errorCode;
        public String errorMessage;
    }

    public static SmsResult send(SmsMessage sms) {
        HttpRequest req = new HttpRequest();
        req.setEndpoint(ENDPOINT);
        req.setMethod('POST');
        req.setHeader('Content-Type', 'application/json');
        req.setHeader('Accept', 'application/json');
        req.setTimeout(20000); // 20 s; all callouts in a transaction share 120 s
        req.setBody(JSON.serialize(buildBody(sms)));

        try {
            HttpResponse res = new Http().send(req);
            return parseResponse(res.getStatusCode(), res.getBody());
        } catch (CalloutException e) {
            SmsResult failed = new SmsResult();
            failed.statusCode = 0;
            failed.errorCode = 'CALLOUT_FAILED';
            failed.errorMessage = e.getMessage();
            return failed;
        }
    }

    public static Map<String, Object> buildBody(SmsMessage sms) {
        Map<String, Object> body = new Map<String, Object>{
            'sender_id' => String.isBlank(sms.senderId) ? DEFAULT_SENDER_ID : sms.senderId,
            'recipient' => toIndianMobile(sms.recipient),
            'message' => sms.message
        };
        if (String.isNotBlank(sms.dltTemplateId)) {
            body.put('dlt_template_id', sms.dltTemplateId);
        }
        if (String.isNotBlank(sms.route)) {
            body.put('route', sms.route);
        }
        return body;
    }

    // '+91 98765-43210' -> '9876543210' (the API rejects spaces and dashes)
    public static String toIndianMobile(String phone) {
        String digits = phone == null ? '' : phone.replaceAll('[^0-9]', '');
        return digits.length() > 10 ? digits.right(10) : digits;
    }

    public static SmsResult parseResponse(Integer statusCode, String responseBody) {
        SmsResult result = new SmsResult();
        result.statusCode = statusCode;

        Map<String, Object> parsed = new Map<String, Object>();
        try {
            parsed = (Map<String, Object>) JSON.deserializeUntyped(responseBody);
        } catch (Exception e) {
            // Not JSON, e.g. a proxy error page. Handled below.
        }

        Object ok = parsed.get('success');
        if (statusCode == 200 && ok instanceof Boolean && (Boolean) ok) {
            Map<String, Object> data = (Map<String, Object>) parsed.get('data');
            result.success = true;
            result.messageId = String.valueOf(data.get('message_id'));
            result.status = String.valueOf(data.get('status'));
            return result;
        }

        // Read error_code first, then error, then message
        if (parsed.containsKey('error_code')) {
            result.errorCode = String.valueOf(parsed.get('error_code'));
        } else if (parsed.containsKey('error')) {
            result.errorCode = String.valueOf(parsed.get('error'));
        } else {
            result.errorCode = 'HTTP_' + statusCode;
        }
        result.errorMessage = parsed.containsKey('message') ? String.valueOf(parsed.get('message')) : responseBody;
        if (parsed.get('errors') != null) {
            result.errorMessage += ' ' + JSON.serialize(parsed.get('errors'));
        }
        return result;
    }
}

For a case-closed message, the request body it sends looks like this:

{"sender_id":"ACMEIN","recipient":"9876543210","message":"Your Acme support case 00001026 has been closed. Thank you for contacting us. -ACME"}

A successful reply, which parseResponse turns into success = true, messageId = '123' and status = 'queued':

{"success":true,"message":"SMS queued successfully","data":{"message_id":123,"queue_id":123,"status":"queued","estimated_delivery":"2026-11-07T10:02:00.000000Z"}}

For errors, errorCode takes the reply's error_code first (for example TEMPLATE_MISMATCH), then error (for example Forbidden). errorMessage holds the message and any errors details. A network failure gives CALLOUT_FAILED instead of an exception, so one bad call never stops the rest.

Method 2: Trigger-based SMS (async Queueable)

Apex can't make a callout in the same transaction as a trigger. The trigger collects the messages and hands them to a Queueable job that implements Database.AllowsCallouts. The job makes all its callouts first, then saves one completed Task per SMS on the record, because Salesforce does not allow DML before a callout in the same transaction. It sends at most 50 SMS per job and chains a new job for the rest.

Apex: OnlineSmsQueueable.cls

/**
 * Sends SMS outside the trigger transaction (triggers can't make callouts).
 * Callouts first, DML after, then chains a new job for anything left over.
 */
public with sharing class OnlineSmsQueueable implements Queueable, Database.AllowsCallouts {

    // Well inside 100 callouts and 120 s of callout time per transaction
    public static final Integer MAX_PER_JOB = 50;

    private List<OnlineSmsService.SmsMessage> messages;

    public OnlineSmsQueueable(List<OnlineSmsService.SmsMessage> messages) {
        this.messages = messages;
    }

    public void execute(QueueableContext context) {
        List<OnlineSmsService.SmsMessage> remaining = new List<OnlineSmsService.SmsMessage>();
        List<Task> logs = new List<Task>();

        // 1. All callouts first: no DML may run before a callout in the same transaction
        for (Integer i = 0; i < messages.size(); i++) {
            OnlineSmsService.SmsMessage sms = messages[i];
            if (i >= MAX_PER_JOB) {
                remaining.add(sms);
                continue;
            }
            OnlineSmsService.SmsResult result = OnlineSmsService.send(sms);
            if (sms.relatedId != null) {
                logs.add(buildLog(sms, result));
            }
        }

        // 2. Then DML: one completed Task per SMS on the related record
        if (!logs.isEmpty()) {
            insert logs;
        }

        // 3. Chain a new job for the rest
        if (!remaining.isEmpty() && !Test.isRunningTest()) {
            System.enqueueJob(new OnlineSmsQueueable(remaining));
        }
    }

    private static Task buildLog(OnlineSmsService.SmsMessage sms, OnlineSmsService.SmsResult result) {
        Task t = new Task(
            Subject = result.success ? 'SMS queued: ' + result.messageId : 'SMS failed: ' + result.errorCode,
            Description = result.success ? sms.message : result.errorMessage,
            Status = 'Completed',
            ActivityDate = Date.today()
        );
        Schema.SObjectType objectType = sms.relatedId.getSObjectType();
        if (objectType == Lead.SObjectType || objectType == Contact.SObjectType) {
            t.WhoId = sms.relatedId;
        } else {
            t.WhatId = sms.relatedId;
        }
        return t;
    }
}

Apex trigger: CaseClosedSms.trigger

trigger CaseClosedSms on Case (after update) {
    List<Case> closedCases = new List<Case>();
    Set<Id> contactIds = new Set<Id>();

    for (Case c : Trigger.new) {
        Case prior = Trigger.oldMap.get(c.Id);
        if (c.Status == 'Closed' && prior.Status != 'Closed' && c.ContactId != null) {
            closedCases.add(c);
            contactIds.add(c.ContactId);
        }
    }

    if (!closedCases.isEmpty()) {
        Map<Id, Contact> contacts = new Map<Id, Contact>(
            [SELECT Id, MobilePhone FROM Contact WHERE Id IN :contactIds AND MobilePhone != null]
        );
        List<OnlineSmsService.SmsMessage> outbox = new List<OnlineSmsService.SmsMessage>();
        for (Case c : closedCases) {
            Contact person = contacts.get(c.ContactId);
            if (person == null) {
                continue;
            }
            // DLT template: "Your Acme support case {#numeric#} has been closed. Thank you for contacting us. -ACME"
            OnlineSmsService.SmsMessage sms = new OnlineSmsService.SmsMessage(
                person.MobilePhone,
                'Your Acme support case ' + c.CaseNumber + ' has been closed. Thank you for contacting us. -ACME'
            );
            sms.relatedId = c.Id;
            outbox.add(sms);
        }
        if (!outbox.isEmpty()) {
            System.enqueueJob(new OnlineSmsQueueable(outbox)); // one job per trigger batch
        }
    }
}

The trigger queues one job for each batch of up to 200 records. It sends only when the status changes to Closed, so editing a closed case again sends nothing. Change 'Closed' if your org uses another closed status. A @future(callout=true) method also works for a single SMS. Queueable is used here because it accepts a list of objects and can chain.

Method 3: Salesforce Flow integration

Once OnlineSmsService is deployed, add this class and admins can send SMS from Flow Builder without writing code.

Apex: OnlineSmsFlowAction.cls

/**
 * "Send SMS (OnlineSMSService)" action for Flow Builder.
 * In a record-triggered flow, put it on a "Run Asynchronously" path.
 */
public with sharing class OnlineSmsFlowAction {

    public class Request {
        @InvocableVariable(label='Mobile number' required=true)
        public String mobile;
        @InvocableVariable(label='Message (must match your DLT template)' required=true)
        public String message;
        @InvocableVariable(label='Sender ID (DLT header)')
        public String senderId;
        @InvocableVariable(label='DLT template ID')
        public String dltTemplateId;
        @InvocableVariable(label='Route: transactional or promotional')
        public String route;
    }

    public class Result {
        @InvocableVariable(label='Sent')
        public Boolean success;
        @InvocableVariable(label='Message ID')
        public String messageId;
        @InvocableVariable(label='Error code')
        public String errorCode;
        @InvocableVariable(label='Error message')
        public String errorMessage;
    }

    @InvocableMethod(label='Send SMS (OnlineSMSService)' description='Sends an SMS through the OnlineSMSService API' callout=true)
    public static List<Result> send(List<Request> requests) {
        List<Result> results = new List<Result>();
        for (Request r : requests) {
            Result out = new Result();
            if (Limits.getCallouts() >= Limits.getLimitCallouts()) {
                out.success = false;
                out.errorCode = 'CALLOUT_LIMIT';
                out.errorMessage = 'Over 100 SMS in one transaction. Use OnlineSmsQueueable for large batches.';
            } else {
                OnlineSmsService.SmsMessage sms = new OnlineSmsService.SmsMessage(r.mobile, r.message);
                sms.senderId = r.senderId;
                sms.dltTemplateId = r.dltTemplateId;
                sms.route = r.route;
                OnlineSmsService.SmsResult sent = OnlineSmsService.send(sms);
                out.success = sent.success;
                out.messageId = sent.messageId;
                out.errorCode = sent.errorCode;
                out.errorMessage = sent.errorMessage;
            }
            results.add(out);
        }
        return results;
    }
}
  1. Deploy the classesDeploy OnlineSmsService and OnlineSmsFlowAction with the test class.
  2. Add an async pathIn a record-triggered flow, tick "Include a Run Asynchronously path" on the Start element. Callouts can't run while the record is being saved. Screen flows can call the action directly.
  3. Add the actionOn the async path, add an Action and search for Send SMS (OnlineSMSService).
  4. Map the fieldsSet Mobile number (for example {!$Record.Contact.MobilePhone}) and Message. Build the message in a Text Template resource that copies your DLT template word for word.
  5. Use the outputsStore Sent, Message ID, Error code and Error message on the record, or use them in a Decision element.
  6. ActivateTest with one record that has your own mobile number, then activate the flow.

Flow Builder also has an HTTP Callout action that works with named credentials. This guide uses the Apex action because it cleans numbers and reads our error replies for you.

Using a named credential (recommended)

A named credential keeps the API key encrypted in Salesforce and adds it to every request. Your Apex then calls callout:OnlineSMS_API/sms/send, and you need no Remote Site Setting. Set it up in Setup → Named Credentials:

  1. External credentialOn the External Credentials tab, click New. Use Label OnlineSMS, Name OnlineSMS and Authentication Protocol Custom.
  2. Principal and keyUnder Principals, add a principal (for example OnlineSMSKey, identity type Named Principal). Give it an authentication parameter named ApiKey whose value is your API key.
  3. Custom headerUnder Custom Headers on the external credential, add the name X-API-Key and the value {!$Credential.OnlineSMS.ApiKey}.
  4. Named credentialOn the Named Credentials tab, click New. Use Label OnlineSMS API, Name OnlineSMS_API, URL https://whitelabled.securesmsc.com/api/v2 and External Credential OnlineSMS. Clear "Generate Authorization Header" and tick "Allow Formulas in HTTP Header".
  5. Permission setIn a permission set, enable External Credential Principal Access for OnlineSMS – OnlineSMSKey, and give access to the User External Credentials object. Assign it to every user whose actions send SMS, and to your integration user.

If a callout fails with a message about the named credential or principal, the running user is usually missing this permission set.

Field mapping and DLT template matching

API fieldSalesforce valueRules
sender_idDEFAULT_SENDER_ID, or the Flow inputRequired. An approved DLT header on your account, up to 11 characters (headers are 6).
recipientContact.MobilePhone, Lead.MobilePhoneRequired. toIndianMobile turns +91 98765-43210 into 9876543210.
messageBuilt in Apex or a Flow Text TemplateRequired. Up to 1,600 characters, and it must match an approved template.
dlt_template_idOptional inputAlways a String. A number in the JSON fails with 422.
routeOptional inputtransactional (default) or promotional.

Operators compare every SMS with your approved templates. The fixed words must be identical, and only the variables may change. The trigger above matches this template:

Your Acme support case {#numeric#} has been closed. Thank you for contacting us. -ACME
  • Copy the fixed text from your DLT portal into Apex or the Text Template. Don't retype it. Spaces, commas and full stops count.
  • Values must fit the variable type. A case number is digits only, so it fits a numeric variable. A name needs an alphanumeric variable of up to 40 characters. See DLT template variable tags.
  • No empty variables. A blank value leaves a gap, and the text no longer matches.
  • Watch for Unicode. A curly quote or ₹ sign makes the whole SMS Unicode. Each SMS then holds 70 characters, not 160. Check with the SMS character counter and the DLT template checker.

If you leave dlt_template_id out, our platform matches the text against your approved templates and rejects a mismatch at once with TEMPLATE_MISMATCH. If you send it, the platform may skip its own check, and the operator's DLT check becomes the only one. So leave it out while you test.

Test class (HttpCalloutMock)

Apex tests can't make real callouts. This test class uses HttpCalloutMock to return the API's real reply bodies. It covers success, the IP-lock 403, TEMPLATE_MISMATCH, the Flow action, and the trigger plus Queueable path. Salesforce needs 75% code coverage to deploy Apex to production.

Apex: OnlineSmsServiceTest.cls

@IsTest
private class OnlineSmsServiceTest {

    static final String OK_BODY = '{"success":true,"message":"SMS queued successfully","data":{"message_id":123,"queue_id":123,"status":"queued","estimated_delivery":"2026-11-07T10:02:00.000000Z"}}';
    static final String IP_LOCKED = '{"success":false,"error":"Forbidden","message":"IP address not allowed. Please whitelist your IP address to access the API."}';
    static final String MISMATCH = '{"success":false,"error":"Template Verification Failed","error_code":"TEMPLATE_MISMATCH","message":"Template verification failed: no matching template"}';

    private class ApiMock implements HttpCalloutMock {
        private Integer statusCode;
        private String body;

        ApiMock(Integer statusCode, String body) {
            this.statusCode = statusCode;
            this.body = body;
        }

        public HttpResponse respond(HttpRequest req) {
            System.assertEquals('POST', req.getMethod());
            System.assertEquals('callout:OnlineSMS_API/sms/send', req.getEndpoint());
            Map<String, Object> sent = (Map<String, Object>) JSON.deserializeUntyped(req.getBody());
            System.assertEquals('ACMEIN', sent.get('sender_id'));
            System.assertEquals('9876543210', sent.get('recipient'));
            HttpResponse res = new HttpResponse();
            res.setStatusCode(statusCode);
            res.setHeader('Content-Type', 'application/json');
            res.setBody(body);
            return res;
        }
    }

    @IsTest
    static void parsesSuccess() {
        Test.setMock(HttpCalloutMock.class, new ApiMock(200, OK_BODY));
        Test.startTest();
        OnlineSmsService.SmsResult r = OnlineSmsService.send(
            new OnlineSmsService.SmsMessage('+91 98765-43210', 'Test -ACME'));
        Test.stopTest();
        System.assert(r.success);
        System.assertEquals('123', r.messageId);
        System.assertEquals('queued', r.status);
    }

    @IsTest
    static void reportsIpNotWhitelisted() {
        Test.setMock(HttpCalloutMock.class, new ApiMock(403, IP_LOCKED));
        Test.startTest();
        OnlineSmsService.SmsResult r = OnlineSmsService.send(
            new OnlineSmsService.SmsMessage('9876543210', 'Test -ACME'));
        Test.stopTest();
        System.assert(!r.success);
        System.assertEquals('Forbidden', r.errorCode);
        System.assert(r.errorMessage.startsWith('IP address not allowed'));
    }

    @IsTest
    static void reportsTemplateMismatch() {
        Test.setMock(HttpCalloutMock.class, new ApiMock(422, MISMATCH));
        Test.startTest();
        OnlineSmsService.SmsResult r = OnlineSmsService.send(
            new OnlineSmsService.SmsMessage('919876543210', 'Test -ACME'));
        Test.stopTest();
        System.assert(!r.success);
        System.assertEquals('TEMPLATE_MISMATCH', r.errorCode);
    }

    @IsTest
    static void flowActionReturnsOneResultPerRequest() {
        Test.setMock(HttpCalloutMock.class, new ApiMock(200, OK_BODY));
        OnlineSmsFlowAction.Request input = new OnlineSmsFlowAction.Request();
        input.mobile = '9876543210';
        input.message = 'Test -ACME';
        Test.startTest();
        List<OnlineSmsFlowAction.Result> results =
            OnlineSmsFlowAction.send(new List<OnlineSmsFlowAction.Request>{ input });
        Test.stopTest();
        System.assertEquals(1, results.size());
        System.assertEquals('123', results[0].messageId);
    }

    @IsTest
    static void closingACaseSendsAnSmsAndLogsATask() {
        // Add any fields your org's validation rules require
        Contact person = new Contact(LastName = 'Test', MobilePhone = '+91 98765 43210');
        insert person;
        Case c = new Case(Subject = 'Test', Status = 'New', Origin = 'Phone', ContactId = person.Id);
        insert c;

        Test.setMock(HttpCalloutMock.class, new ApiMock(200, OK_BODY));
        Test.startTest();
        c.Status = 'Closed';
        update c;
        Test.stopTest(); // runs the queued job

        Task logged = [SELECT Subject FROM Task WHERE WhatId = :c.Id LIMIT 1];
        System.assertEquals('SMS queued: 123', logged.Subject);
    }
}

Then test for real in a sandbox:

  1. Use the sandbox's own keyGive it Salesforce's ranges in its IP list.
  2. Don't try the key from your laptopIf its list is still empty, that call locks the key to your laptop's IP. Use a different key in the API playground for manual tests.
  3. Close one test caseUse a contact with your own mobile number. This sends a real SMS. The Task on the case shows "SMS queued: …" or "SMS failed: …".
  4. Fix errors before you go liveIf many calls fail at once from the same IP, our security system can block that IP until our support team lifts the block, so fix any 401 or 403 errors first.

Production checklist

Security

  • Keep the key in the named credential. Never put it in Apex, custom settings or a Flow.
  • Use one API key per org, with Salesforce's IP ranges in its list.
  • Grant the permission set only to users and integration users that send SMS.
  • Keep the Task log, or a custom object, for audit.

Governor limits

  • No callouts in a trigger's own transaction. Use Queueable or @future(callout=true).
  • At most 100 callouts and 120 seconds of callout time per transaction. The job sends 50 and chains the rest.
  • Up to 50 jobs queued per transaction, and one chained job from a running Queueable.
  • No DML before a callout in the same transaction.

API limits

  • A key allows 60 requests a minute and 10,000 a day by default. Ask us to raise it for larger volumes.
  • For the same text to many numbers, /sms/send-bulk takes up to 1,000 numbers per call.
  • GET endpoints (balance, status) are off for new keys until you tick "Allow GET Method" under API & Integrations → API Management.

Troubleshooting

ResponseCauseFix
403 "IP address not allowed. Please whitelist your IP address to access the API."The key is locked to another IP, or this Salesforce server's IP is not in the key's list.Add Salesforce's ranges under IP Whitelisting, or ask support to reset the list. See above.
403 "Your IP address has been blocked due to suspicious activity…"Too many failed key checks came from that IP in a few minutes.Fix the key or IP problem, then contact support to unblock the IP.
401 "API key is required"The X-API-Key header was not added.Check the custom header formula, "Allow Formulas in HTTP Header" and the permission set.
401 "Invalid API key", "API key is disabled", "API key has expired" or "Account is not active"The key is wrong, switched off or expired, or the account is not active.Update the principal's ApiKey parameter, or create a new key.
400 "Invalid sender ID"sender_id is not an approved header on your account.Set DEFAULT_SENDER_ID to the exact header shown in your dashboard.
422 "Validation failed"A required field is empty, the number is not 10 digits, or route is not allowed.Read errorMessage, which lists the fields.
422 TEMPLATE_MISMATCHThe text differs from every approved template.Compare it word for word with the template.
400 "SMS dispatch failed" with "Insufficient credits…"Your balance is too low.Top up. There is no minimum top-up.
429 "Rate limit exceeded"More than the key's limit (60 a minute by default).Send in smaller jobs, or ask us to raise the limit.
CALLOUT_FAILED "You have uncommitted work pending"DML ran before the callout in the same transaction.Make the callouts first, as the Queueable does.
CALLOUT_FAILED about the named credentialA wrong name, or the user lacks principal access.Check OnlineSMS_API and the permission set.

Other CRMs

Zoho CRM

A workflow webhook, or a Deluge function that saves the result on the lead.

HubSpot

A "Send a webhook" action, or a Node.js 24 custom code action in workflows.

Your own code

The same API from PHP, Node.js or Python. See the API docs.

Frequently asked questions

Is there an AppExchange package for OnlineSMSService?

No. We do not have an AppExchange or managed package. You deploy the Apex classes on this page, or your Salesforce developer adapts them, and they call our API through a named credential.

Which Salesforce editions can send SMS with this guide?

Enterprise, Performance, Unlimited and Developer editions, because the guide uses Apex. Professional Edition cannot run your own Apex code.

Why did the first SMS from Salesforce work and the next ones fail with 403?

The API key locked itself to the IP address of the first Salesforce server that used it. Salesforce makes callouts from many servers, so the others were refused. Add Salesforce's IP ranges to the key under API & Integrations, API Management, IP Whitelisting, or ask our support team to reset the key's list.

Can I send an SMS directly from an Apex trigger?

Not in the same transaction. Salesforce does not allow callouts while a trigger runs, so the trigger queues a Queueable job that implements Database.AllowsCallouts, or calls a future method with callout=true.

How many SMS can one Salesforce transaction send?

Salesforce allows 100 callouts and 120 seconds of total callout time per transaction. The Queueable on this page sends 50 per job and chains the rest. Our API also limits each key to 60 requests a minute and 10,000 a day by default, and we can raise this.

Do I still need a Remote Site Setting?

No. A callout through a named credential, written as callout:OnlineSMS_API/sms/send, does not need a Remote Site Setting.

Do I need DLT registration to send SMS from Salesforce?

Yes. Every business SMS in India needs a registered entity, an approved header and approved content templates on a DLT portal. A new DLT registration filed through us costs ₹5,900 (₹5,000 + 18% GST) and is valid for one year and renewed every year. Renewal is separate, and we remind you before it lapses. Linking an entity you already have is free.

How much does it cost to send SMS from Salesforce?

SMS cost ₹0.20 each on Starter (up to 10,000 a month) and ₹0.15 on Business (up to 1,00,000 a month), plus 18% GST. Above 1,00,000 a month, Enterprise pricing is custom. You pay per delivered message, with no setup or monthly fee. Your Salesforce licence is separate.

Get a free API key + 100 test SMS

Create your account and generate an API key right away. Verified businesses also get 100 free test SMS once KYC and DLT mapping are done. No setup fee, no minimum top-up, and credits never expire.

Get 100 free SMS
Claim 100 free SMS