Skip to main content

Short Message Service (SMS) Guide

There are plenty of scenarios in which your app may need to send text messages to your users:

  • User verification: When a user attempts to log in or change their password, a text message containing verification code can be sent to the user to ensure the security of the account.
  • Operation verification: For apps demanding high security levels (like banking apps), when a user performs sensitive operations like transferring money or making payments, a verification code can be helpful to confirm if the user themself is performing the operation.
  • Notifications and marketing: Merchants may send users notifications containing status updates regarding their orders, or campaigns regarding new products and promotions.

After enabling SMS in your app's dashboard (see Enabling SMS), you will be able to send text messages to your users through your app:

// Sending text message to +19490008888 using the template (Register_Notice)
AVCloud.RequestSMSCodeAsync("+19490008888","Register_Notice",null,null).ContinueWith(t =>
{
var result = t.Result;
// result being True means the request is completed
});

The actual message received by the user looks like this:

【Thanks for joining LeanCloud, the leading backend-as-a-service provider.

The content of the text message comes from the template named Register_Notice which needs to be created in your app's dashboard in advance.

Enabling SMS

Enabling SMS in Security Settings

To start using SMS, make sure you already have an app created, then go to the app's [Dashboard > Settings > Security and enable SMS:

「服务开关」下面的「短信服务」是打开的。

Completing SMS Settings

Then go to Dashboard > Messaging > SMS > Settings > SMS settings and ensure the following option is enabled:

Enable SMS verification code (open up requestSmsCode and verifySmsCode)

  • Enabled: The app is able to incorporate features related to SMS, including verification when there are users performing sensitive operations, logging in at unusual locations, making payments, etc.
  • Disabled: Requests for sending and verifying verification codes will be rejected. Note that this won't affect verification for user accounts.

Using SMS for Verification

It is becoming quite common that apps rely on SMS for signing up, logging in, and performing verification for sensitive operations. Here we use a shopping app as an example to explain how you can use LeanCloud's SMS to complete a verification:

  1. The user places an order
    A sensitive operation is initiated.

  2. Call API to send text message
    Keep in mind that we are assuming that you have already completed the setup process mentioned earlier.

    // Here 10 means to make verification code valid for 10 minutes
    AVCloud.RequestSMSCodeAsync("+19490008888","App Name","some operation",10).ContinueWith(t =>
    {
    if(!t.Result)
    {
    // Request completed
    }
    });
  1. The user receives the text message and enters the code
    Before continuing, we suggest that you implement verification on the client side to check if the code entered is in a valid format (has valid length and does not contain invalid characters). This helps your app avoid making unnecessary requests to the server and could potentially enhance the user experience.

  2. Call API to check if the code is valid
    Please pay attention to the sequence of the parameters being passed into the function. Here we assume the verification code is "123456":

    AVCloud.VerifySmsCodeAsync("123456","+19490008888").ContinueWith(t =>{
    if(t.Result)
    {
    // Successfully verified
    }
    });

The same verification logic can be applied to other scenarios like logging in at unusual locations or updating sensitive information. You would call the same API and follow the same steps. The only thing you need to do is to design a UI that fits your requirements.

Sending Verification Code by Calling

Although the delivery rate of text messages is pretty close to 100%, some apps demand even higher rate and expects better security at the same time. That's why we also provide the service to deliver verification code via phone call. The code below shows how you can use it:

AVCloud.RequestVoiceCodeAsync ("+19490008888").ContinueWith(t =>{
// Call made successfully
});

Now the user would receive a phone call telling them the 6-digit verification code. Call the following method to complete the verification:

AVCloud.VerifySmsCodeAsync("123456","+19490008888").ContinueWith(t =>{
if(t.Result)
{
// Successfully verified
}
});

The method verifies if the code entered is correct.

Templates

Except for verification messages, to send text messages, you need to create a template beforehand. Once a template is created, when calling LeanCloud's API to send messages, you only need to plug in the variables used in these templates rather than to pass in the entire text message as a string.

Creating Templates

To create a template, go to your app's dashboard and navigate to Messaging > SMS > Settings.

Using Templates

Assuming that you have created a template named Order_Notice with the following content:

Your package for the order will be delivered by the end of today.

Now you can send a text message with this template:

var env = new Dictionary<string,object>()
{
{"order_id","7623432424540"} // Plug the actual value into the template
};
AVCloud.RequestSMSCodeAsync("+19490008888", "Order_Notice", env, null).ContinueWith(t =>
{
var result = t.Result;
// result being True means the request is completed
});

The actual text message received by the user would look like this:

【BuyBuyBuy】Your package for the order 7623432424540 will be delivered by the end of today.

Preventing Abuse with CAPTCHA

While SMS allows developers to offer a better experience to their customers, it could also get abused by people with bad intentions, which not only causes financial loss but also brings a negative impact to the reputation of their apps. Hackers may gather a list of websites that allow users to trigger text messages without going through CAPTCHA and use programs to automatically send text messages using these sites. Here are some possible consequences:

  • To website owners, their sites will continuously receive requests to send out text messages and they will have to pay more for that;
  • To users of phone numbers, they will receive tons of irrelevant text messages containing verification codes.

To prevent such abuse, CAPTCHA can be used to filter out requests that are not made by humans. You might have seen something like this in many other websites which asks you to enter the text appearing in an image:

A page requiring user to type in the characters in an image.

To prevent hackers from abusing your app, you can require each user to enter the characters in an image before they can request an SMS verification code for free using LeanCloud's service.

Here is a basic workflow of CAPTCHA:

sequenceDiagram User (browser)->App server: 1. Request for sign-up or log-in page App server->User (browser): 2. Show sign-up or log-in page User (browser)->LeanCloud: 3. Request CAPTCHA LeanCloud->User (browser): 4. Show CAPTCHA User (browser)->LeanCloud: 5. Request to verify user input LeanCloud->User (browser): 6. Return token User (browser)->LeanCloud: 7. Request to send verification code (with token attached) LeanCloud->User (browser): 8. Return result or send verification code User (browser)->App server: 9. Submit form to sign up or log in App server->LeanCloud: 10. Verify the code LeanCloud->App server: 11. Return result of verification App server->User (browser): 12. Return result of operation
  1. The user opens the sign-up or log-in page and request for CAPTCHA from LeanCloud.
  2. The user fills in their personal information, including the text in the CAPTCHA image, and clicks on a button to verify the input.
  3. After LeanCloud verifies that the input is correct, it sends a verification code to the number.
  4. The user submits the form and the app sends the verification code entered by the user to LeanCloud for further verification.
  5. LeanCloud returns if the verification code is correct or not. If it is correct, the user completes signing up or logging in.

Enabling CAPTCHA

To enable CAPTCHA for SMS verification codes, go to your app's Dashboard > Settings > Security and turn on CAPTCHA.

If you wish CAPTCHA to be enabled for all types of text messages sent out from your app, go to Dashboard > Messaging > SMS > Settings > SMS Settings and enable Require CAPTCHA before sending messages. Once enabled, any request for sending a text message without going through CAPTCHA will receive an error.

LeanCloud's CAPTCHA service can only provide a minimum level of abuse prevention. You are free to add third-party CAPTCHA services to your website.

An Example of Using CAPTCHA on a Website

Now we will build a basic page with HTML and JavaScript to demonstrate how you can use our CAPTCHA service on your website.

Initialization

Initialize CAPTCHA component:

AV.Captcha.request().then(function (captcha) {
captcha.bind({
textInput: 'captcha-code', // The id for textInput
image: 'captcha-image', // The id for image element
verifyButton: 'verify' // The id for verify button
}, {
success: function (validateCode) {
console.log('The input is correct.');
},
error: function (error) {
console.error(error.message);
}
});
});

Parameters

The following parameters can be passed in when initializing an AV.Captcha instance with AV.Captcha.request():

{{ sms.paramsRequestCaptcha() }}

For example, to initialize a captcha instance with height being 30px and width being 80px:

AV.Captcha.request({ width: 80, height: 30 });

captcha.bind() binds the captcha instance with the element on the user interface. It supports the following parameters:

NameTypeDescription
textInputstring or HTMLInputElementThe input box for entering text, or its id.
imagestring or HTMLImageElementThe image component for displaying CAPTCHA image, or its id.
verifyButtonstring or HTMLElementThe button for proceeding, or its id.

Full Code

Here is the full code for our demo:

<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Testing CAPTCHA</title>
</head>

<body>
<label>Phone Number
<input type="text" id="phone" />
</label>
<br />
<label>Verification Code
<input type="text" id="captcha-code" />
</label>
<img id="captcha-image" />
<br />
<button id="verify">Send Code</button>
<!-- Include LeanCloud SDK -->
<script src="//cdn.jsdelivr.net/npm/leancloud-storage@{{jssdkversion}}/dist/av-min.js"></script>
<script>
var appId = '{{appid}}'; // Your appId
var appKey = '{{appkey}}'; // Your appKey
AV.init({ appId, appKey });
// AV.Captcha.request() generates an 85px x 30px AV.Captcha instance by default
AV.Captcha.request().then(function (captcha) {
// Bind CAPTCHA with DOM elements using captcha.bind
captcha.bind({
textInput: 'captcha-code', // The id for textInput
image: 'captcha-image', // The id for image element
verifyButton: 'verify' // The id for verify button
}, {
success: function (validateCode) {
var phoneNumber = document.getElementById('phone').value;
console.log('The input is correct. Now send verification code to: ' + phoneNumber);
AV.Cloud.requestSmsCode({
mobilePhoneNumber: phoneNumber,
name: 'App Name',
validate_token: validateCode,
op: 'some operation',
ttl: 10
}).then(function () {
console.log('Message sent.');
}, function (err) {
console.error('Failed to send message.', err.message);
});
},
error: function (error) {
console.error(error.message);
}
});
});
</script>
</body>

</html>

CAPTCHA APIs

Getting Images

AVCloud.RequestCaptchaAsync(width:85, height:30).ContinueWith(t =>{
var captchaData = t.Result;
var url = captchaData.Url; // The URL of the image used to display the image
var captchaToken = captchaData.captchaToken; // The server tells the CAPTCHA being used based on this token
});

Verifying User Inputs

After obtaining a CAPTCHA, you can display the image on your page (for non-web platforms like iOS and Android, use an image component to display the image). After the user enters the text into the input box, use the method below to verify the input:

AVCloud.VerifyCaptchaAsync("Plug user input here, for example: AM8N",'Plug captchaToken here').CotinuteWith(t =>{
var validate_token = result;
});

Sending SMS Verification Codes with validate_token

If the input is correct, continue to send SMS verification code with the validate_token obtained:

// +19490008888: Phone number
// New_Series: Template name
AVCloud.RequestSMSCodeAsync("+19490008888","New_Series",null,null,"The validate_token obtained earlier").ContinueWith(t =>
{
var result = t.Result;
// result being True means the request is completed
});

International Text Messages

For a list of countries and regions that LeanCloud can reach out through SMS, please refer to the Pricing page on our website.

Note that Chinese networks have very strict rules applied to SMS traffic. Messages sent to China numbers may be delayed or not delivered at all. If you want to send messages to China numbers, we recommend you create an application at LeanCloud China and send these messages there instead. Templates created at LeanCloud China will go through a review process and get registered with Chinese networks in the end. Only approved templates can be used for sending messages.

Integrating with LeanCloud User System

LeanCloud offers a built-in user system for you to quickly implement features that allow users to sign up, log in, and reset passwords. With the help of SMS, these operations can be done with users' phone numbers as well.

You can find the following settings in your app's Dashboard > LeanStorage > Settings > Account:

Send verification SMS when users register or change phone numbers from clients

  • Enabled: If you pass in a phone number when calling user-related API interfaces, a text message with verification code will be automatically sent. However, you still need to manually invoke the /verifyMobilePhone/<code> interface to set the mobilePhoneVerified field of the _User table to true. Therefore, it is not recommended to enable this option. If you want to verify the number when binding or updating a phone number, please use the requestChangePhoneNumber interface instead.
  • Disabled: No text message will be sent when calling user-related API interfaces.

Do not allow users with unverified phone numbers to log in

  • Enabled: An AVUser with unverified number cannot log in using phone number and password or phone number and verification code. This user can still log in with username and password.
  • Disabled: Whether a user's phone number is verified will not affect the methods this user can use to log in.

Allow users with unverified phone numbers to reset passwords with SMS

  • Enabled: Allow an AVUser with unverified number to reset their password with SMS verification code.
  • Disabled: An AVUser must have their phone number verified (mobilePhoneVerified being true) before they can reset their password with SMS verification code.

Allow users with verified phone numbers to login with SMS

  • Enabled: An AVUser can log in with phone number and verification code.
  • Disabled: An AVUser cannot log in with phone number and verification code.

You can learn how to sign up and log in with phone numbers as well as how to verify existing users' phone numbers in LeanStorage Guides.