Trigger SMS text messages using Server-Side JavaScript

In order to be able to programmatically trigger text messages, you will need to have MobileConnect enabled in Marketing Cloud’s Mobile Studio. You will also need to be able to create an installed package in your Marketing Cloud account to interact with Salesforce Marketing Cloud APIs. If you have both in place, we can start by creating a new SMS message.

Create a new message in MobileConnect

Go to Mobile Studio > Mobile Connect and click on Create Message. Choose Outbound and click on Next. In Message Setup, choose a Name, Short/Long Code to be used, From Name and choose API Trigger as the Send Method. Click on Next, type the Outbound Message text and choose the Next Keyword if needed. To finalize, click on Activate. Before you confirm, note the API Key displayed in the pop-up:

The message will now be visible in the Overview screen – make sure it’s status is Active/Scheduled.

Trigger the message using API

In order to trigger a text message, we will have to interact with Salesforce Marketing Cloud’s REST API using the /sms/v1/messageContact/{id}/send route, but before we do that, we will need to authenticate.

Authenticate using Server-Side JavaScript

Let’s start by installing a new, or identifying an existing installed package in your Marketing Cloud account. Note the Client Id and Client Secret as we will need them to authenticate our API request. Make sure that SMS is enabled in the scope of the package you are using:

Depending on the type of the package installed (v2 – enhanced functionality or v1 – legacy functionality), use one of the following code snippets to cover the authentication part of the script.

v1: [see code snippet on Github]

v2: [see code snippet on Github]

<script runat="server">
Platform.Load("Core","1.1.1");
var authEndpoint = 'https://mcxxxxxxxxxxxxxxxxxxxxxxxxx.auth.marketingcloudapis.com&#39;;
var payload = {
client_id: "insert Client Id",
client_secret: "insert Client Secret",
grant_type: "client_credentials"
};
var url = authEndpoint + '/v2/token';
var contentType = 'application/json';
try {
var accessTokenRequest = HTTP.Post(url, contentType, Stringify(payload));
if(accessTokenRequest.StatusCode == 200) {
var tokenResponse = Platform.Function.ParseJSON(accessTokenRequest.Response[0]);
var accessToken = tokenResponse.access_token;
}
} catch (error) {
Write(Stringify(error));
}
</script>

Make a messageContact API Request

Below is an example messageContact API Request. The phone number passed in the payload must use the correct format for the designated country code. For example, a mobile number from the United States must include the numerical country code 1 and the area code, eg: 13175551212. [see code snippet on Github]

Host: https://YOUR_SUBDOMAIN.rest.marketingcloudapis.com
POST /sms/v1/messageContact/MzA6Nzg6MA/send
Content-Type: application/json
Authorization: Bearer YOUR_ACCESS_TOKEN
{
"mobileNumbers": [
"13175551212"
],
"Subscribe": true,
"Resubscribe": true,
"keyword": "JOINSMS"
}
view raw messageContact hosted with ❤ by GitHub

To ensure that the mobile number exists for the contact and that the contact subscribed to the specified keyword on your short code, set the Subscribe and Resubscribe values to true and specify the keyword parameter. If you’re not sure how to work with keywords, check out this help document: Keywords and Codes.

If the request is valid, the API returns a token that can be used to make a follow-up call to check the status of the request: [see code snippet on Github]

HTTP/1.1 202 Accepted
{
"tokenId": "c21NCNSDN2sMMWM2miosdjEHH",
}

Now, let’s combine the first script snippet we used to authenticate with the messageContact payload and make a POST request. Below will work with the v1 legacy package: [see code snippet on Github]

<script runat="server">
Platform.Load("Core","1.1.1");
try {
//API authentication
var authEndpoint = ""; //provide authentication endpoint
var payload = {
clientId: "", //provide Client Id
clientSecret: "" //provide Client Secret
};
var url = authEndpoint + "/v1/requestToken";
var contentType = "application/json";
var accessTokenRequest = HTTP.Post(url, contentType, Stringify(payload));
if(accessTokenRequest.StatusCode == 200) {
var tokenResponse = Platform.Function.ParseJSON(accessTokenRequest.Response[0]);
var accessToken = tokenResponse.accessToken;
}
//make a call using the messageContact route
var headerNames = ["Authorization"];
var headerValues = ["Bearer " + accessToken];
var smsEndpoint = ""; //provide rest endpoint
var smsPayload = {
"mobileNumbers": [
"" //pass phone number
],
"Subscribe": true,
"Resubscribe": true,
"keyword": "" //provide KEYWORD
};
var smsUrl = smsEndpoint + "/sms/v1/messageContact/xxxxxxxxx/send"; //provide message API key
var sendSMS = HTTP.Post(smsUrl, contentType, Stringify(smsPayload), headerNames, headerValues);
} catch (error) {
Write(Stringify(error));
}
</script>

In the above script, you will need to provide your endpoints, ClientId and ClientSecret (all three can be found in Setup > Apps > Installed Packages). You will also need to insert the message Api Key, the keyword and pass the recipient’s phone number.

Last but not least, always remember to put security measures into practice when setting up this kind of functionality on a CloudPage to prevent your ClientId and ClientSecret from being exposed.


Questions? Comments?

Leave a comment below or email me at zuzanna@sfmarketing.cloud.


10 thoughts on “Trigger SMS text messages using Server-Side JavaScript

  1. sharath

    Any References for Custom activity to send MMS in Journey Builder
    with out using the salesforce, And one more question, is it possible to add the Image in SMS through Amp scripting

    Like

    1. I am not sure what you mean exactly, but you can create/change the content of the SMS in Content Builder or in Mobile Studio. If what you meant is to change it dynamically, then you can use AMPscript in the SMS body to populate the content.

      Like

      1. Luis Hernández Caballero

        Hi,

        thank you for your reply. I want to change the SMS content dynamically in the API call.

        Is it possible?

        Thanks
        PD: Sorry, I replied at thw wrong place

        Like

  2. Luis Hernández Caballero

    After lots of attempts finaly a got a valid token using this script: https://pastebin.com/F6LvGn23

    But, when I try to send the SMS, it replies with

    {“message”:”An error occurred when attempting to evaluate a HTTPPost function call. See inner exception for details.”,”description”:”ExactTarget.OMM.FunctionExecutionException: An error occurred when attempting to evaluate a HTTPPost function call. See inner exception for details.\r\n Error Code: OMM_FUNC_EXEC_ERROR\r\n – from Jint –> \r\n\r\n — inner exception 1—\r\n\r\nSystem.Net.WebException: The remote server returned an error: (401) Unauthorized. – from System\r\n\r\n\r\n\r\n”}

    What Am I doing wrong?

    thanks

    Luis

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s