Updated on 2023-11-17 GMT+08:00

Node.js

Example

Sending SMSs, Sending SMSs in Batches, Receiving Status Reports

Environment

Node.js 8.12.0 or later versions are required. The examples in this section are developed based on Node.js 8.12.0.

  • Sending SMSs shows an example of sending group SMSs with a single template. Sending SMSs in batches shows an example of sending group SMSs with multiple templates.
  • The examples described in this document may involve the use of personal data. You are advised to comply with relevant laws and regulations and take measures to ensure that personal data is fully protected.
  • The examples described in this document are for demonstration purposes only. Commercial use of the examples is prohibited.
  • Information in this document is for your reference only. It does not constitute any offer or commitment.

Sending SMSs

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
/*jshint esversion: 6 */
var https = require('https'); //Introduce the HTTPS module.
var url = require('url'); //Introduce the URL module.
var querystring = require('querystring'); //Introduce the querystring module.

//Mandatory. The values here are example values only. Obtain the actual values based on Development Preparation.
var realUrl = 'https://smsapi.ap-southeast-1.myhuaweicloud.com:443/sms/batchSendSms/v1'; // Application access address and API access URI
var appKey = 'c8RWg3ggEcyd4D3p94bf3Y7x1Ile'; //Application Key
// Hard-coded or plaintext appKey/appSecret is risky. For security, encrypt your appKey/appSecret and store them in the configuration file or environment variables.
var appSecret = 'q4Ii87Bh************80SfD7Al'; //Application Secret
var sender = 'csms12345678'; // Channel number for Chinese mainland SMS or international SMS
var templateId = '8ff55eac1d0b478ab3c06c3c6a492300'; //Template ID

//Mandatory for Chinese mainland SMS. This parameter is valid and mandatory when Template Type corresponding to templateId is Universal template. The signature name must be approved and be the same type as the template.
//This parameter is not required for international SMS.
var signature = "Huawei Cloud SMS test"; // Signature

//Mandatory. Global number format (including the country code), for example, +8615123456789. Use commas (,) to separate multiple numbers.
var receiver = '+8615123456789,+8615234567890'; //Recipient numbers

//Optional. Address for receiving SMS status reports. The domain name is recommended. If this parameter is set to an empty value or left unspecified, customers do not receive status reports.
var statusCallBack = '';

/**
 * Optional. If a non-variable template is used, assign an empty value to this parameter, for example, var templateParas = '';
 * Example of a single-variable template: If the template content is "Your verification code is ${NUM_6}", templateParas can be set to '["369751"]'.
 * Example of a dual-variable template: If the template content is "You have ${NUM_2} delivered to ${TXT_20}", templateParas can be set to '["3","main gate of People's Park"]'.
 * To view more information, choose Service Overview > Template and Variable Specifications.
 */
var templateParas = '["369751"]'; //Template variable. The following uses a single-variable verification code SMS message as an example. The customer needs to generate a 6-digit verification code and define it as a character string to prevent the loss of first digits 0 (for example, 002569 is changed to 2569).

/**
 * Construct the request body.
 * 
 * @param sender
 * @param receiver
 * @param templateId
 * @param templateParas
 * @param statusCallBack
 * @param signature | Signature name, which must be specified when the universal template for Chinese mainland SMS is used.
 * @returns
 */
function buildRequestBody(sender, receiver, templateId, templateParas, statusCallBack, signature){
    if (null !== signature && signature.length > 0) {
        return querystring.stringify({
            'from': sender,
            'to': receiver,
            'templateId': templateId,
            'templateParas': templateParas,
            'statusCallback': statusCallBack,
            'signature': signature
        });
    }

    return querystring.stringify({
        'from': sender,
        'to': receiver,
        'templateId': templateId,
        'templateParas': templateParas,
        'statusCallback': statusCallBack
    });
}

/**
 * Construct the value of X-WSSE.
 * 
 * @param appKey
 * @param appSecret
 * @returns
 */
function buildWsseHeader(appKey, appSecret){
    var crypto = require('crypto');
    var util = require('util');

    var time = new Date(Date.now()).toISOString().replace(/.[0-9]+\Z/, 'Z'); //Created
    var nonce = crypto.randomBytes(64).toString('hex'); //Nonce
    var passwordDigestBase64Str = crypto.createHash('sha256').update(nonce + time + appSecret).digest('base64'); //PasswordDigest

    return util.format('UsernameToken Username="%s",PasswordDigest="%s",Nonce="%s",Created="%s"', appKey, passwordDigestBase64Str, nonce, time);
}

var urlobj = url.parse(realUrl); //Parse the realUrl character string and return a URL object.

var options = {
    host: urlobj.hostname, //Host name
    port: urlobj.port, //Port
    path: urlobj.pathname, //URI
    method: 'POST', //The request method is POST.
    headers: { //Request headers
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': 'WSSE realm="SDP",profile="UsernameToken",type="Appkey"',
        'X-WSSE': buildWsseHeader(appKey, appSecret)
    },
    rejectUnauthorized: false //Ignore the certificate trust issues to prevent API calling failures caused by HTTPS certificate authentication failures.
};
//Request body. If the signature name is not required, set signature to null.
var body = buildRequestBody(sender, receiver, templateId, templateParas, statusCallBack, signature);

var req = https.request(options, (res) => {
    console.log('statusCode:', res.statusCode); //The response code is recorded.

    res.setEncoding('utf8'); //Set the response data encoding format.
    res.on('data', (d) => {
        console.log('resp:', d); //The response data is recorded.
    });
});
req.on('error', (e) => {
    console.error(e.message); //When a request error occurs, error details are recorded.
});
req.write(body); //Send data in the request body.
req.end(); //End the request.

Sending SMSs in Batches

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
/*jshint esversion: 6 */
var https = require('https'); //Introduce the HTTPS module.
var url = require('url'); //Introduce the URL module.

//Mandatory. The values here are example values only. Obtain the actual values based on Development Preparation.
var realUrl = 'https://smsapi.ap-southeast-1.myhuaweicloud.com:443/sms/batchSendDiffSms/v1'; // Application access address and API access URI
// Hard-coded or plaintext appKey/appSecret is risky. For security, encrypt your appKey/appSecret and store them in the configuration file or environment variables.
var appKey = 'c8RWg3ggEcyd4D3p94bf3Y7x1Ile'; //Application Key
var appSecret = 'q4Ii87Bh************80SfD7Al'; //Application Secret
var sender = 'csms12345678'; // Channel number for Chinese mainland SMS or international SMS
var templateId1 = '8ff55eac1d0b478ab3c06c3c6a492300'; //Template ID 1
var templateId2 = '8ff55eac1d0b478ab3c06c3c6a492300'; //Template ID 2
//Mandatory for Chinese mainland SMS. This parameter is valid and mandatory when Template Type corresponding to templateId is Universal template. The signature name must be approved and be the same type as the template.
//This parameter is not required for international SMS.
var signature1 = "Huawei Cloud SMS test"; // Signature 1
var signature2 = "Huawei Cloud SMS test"; // Signature 2

//Mandatory. Global number format (including the country code), for example, +8615123456789. Use commas (,) to separate multiple numbers.
var receiver1 = ['+8615123456789','+8615234567890']; //Recipient number of template 1
var receiver2 = ['+8615123456789','+8615234567890']; //Recipient number of template 2

//Optional. Address for receiving SMS status reports. The domain name is recommended. If this parameter is set to an empty value or left unspecified, customers do not receive status reports.
var statusCallBack = '';

/**
 * Optional. If a non-variable template is used, assign an empty value to this parameter, for example, var templateParas = [];
 * Example of a single-variable template: If the template content is "Your verification code is ${NUM_6}", templateParas can be set to ['369751'].
 * Example of a dual-variable template: If the template content is "You have ${NUM_2} parcels delivered to ${TXT_20}", templateParas can be set to ['3','main gate of People's Park'].
 * To view more information, choose Service Overview > Template and Variable Specifications.
 */
var templateParas1 = ['123456']; //Template 1 variable. The following uses a single-variable verification code SMS message as an example. The customer needs to generate a 6-digit verification code and define it as a character string to prevent the loss of first digits 0 (for example, 002569 is changed to 2569).
var templateParas2 = ['234567']; //Template 2 variable. The following uses a single-variable verification code SMS message as an example. The customer needs to generate a 6-digit verification code and define it as a character string to prevent the loss of first digits 0 (for example, 002569 is changed to 2569).

/**
 * Construct the value of smsContent.
 * 
 * @param receiver
 * @param templateId
 * @param templateParas
 * @param signature | Signature name, which must be specified when the universal template for Chinese mainland SMS is used.
 * @returns
 */
function initDiffSms(receiver, templateId, templateParas, signature){
    if (null !== signature && signature.length > 0) {
        return {'to': receiver, 'templateId': templateId, 'templateParas': templateParas, 'signature': signature};
    }
    return {'to': receiver, 'templateId': templateId, 'templateParas': templateParas};
}

/**
 * Construct the value of X-WSSE.
 * 
 * @param appKey
 * @param appSecret
 * @returns
 */
function buildWsseHeader(appKey, appSecret){
    var crypto = require('crypto');
    var util = require('util');

    var time = new Date(Date.now()).toISOString().replace(/.[0-9]+\Z/, 'Z'); //Created
    var nonce = crypto.randomBytes(64).toString('hex'); //Nonce
    var passwordDigestBase64Str = crypto.createHash('sha256').update(nonce + time + appSecret).digest('base64'); //PasswordDigest

    return util.format('UsernameToken Username="%s",PasswordDigest="%s",Nonce="%s",Created="%s"', appKey, passwordDigestBase64Str, nonce, time);
}

var body = JSON.stringify ({ //Request body)
    'from': sender,
    'statusCallback': statusCallBack,
    'smsContent': [
        //smsContent. If the signature name is not required, set signature to null.
        initDiffSms(receiver1, templateId1, templateParas1, signature1),
        initDiffSms(receiver2, templateId2, templateParas2, signature2)
    ]}
);

var urlobj = url.parse(realUrl); //Parse the realUrl character string and return a URL object.

var options = {
    host: urlobj.hostname, //Host name
    port: urlobj.port, //Port
    path: urlobj.pathname, //URI
    method: 'POST', //The request method is POST.
    headers: { //Request headers
        'Content-Type': 'application/json',
        'Authorization': 'WSSE realm="SDP",profile="UsernameToken",type="Appkey"',
        'X-WSSE': buildWsseHeader(appKey, appSecret)
    },
    rejectUnauthorized: false //Ignore the certificate trust issues to prevent API calling failures caused by HTTPS certificate authentication failures.
};

var req = https.request(options, (res) => {
    console.log('statusCode:', res.statusCode); //The response code is recorded.

    res.setEncoding('utf8'); //Set the response data encoding format.
    res.on('data', (d) => {
        console.log('resp:', d); //The response data is recorded.
    });
});
req.on('error', (e) => {
    console.error(e.message); //When a request error occurs, error details are recorded.
});
req.write(body); //Send data in the request body.
req.end(); //End the request.

Receiving Status Reports

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/*jshint esversion: 6 */

//Data example (urlencode) of the status report reported by the SMS platform
//var success_body = "sequence=1&total=1&updateTime=2018-10-31T08%3A43%3A41Z&source=2&smsMsgId=2ea20735-f856-4376-afbf-570bd70a46ee_11840135&status=DELIVRD";
var failed_body = "orgCode=E200027&sequence=1&total=1&updateTime=2018-10-31T08%3A43%3A41Z&source=2&smsMsgId=2ea20735-f856-4376-afbf-570bd70a46ee_11840135&status=RTE_ERR";

/**
 * Parse the status report data.
 * 
 * @param data: Status report data reported by the SMS platform.
 * @returns
 */
function onSmsStatusReport(data) {
    var querystring = require('querystring');
    var keyValues = querystring.parse(data);//Parse the status report data.

    /**
             * Example: Parsing status is used as an example. 
     * 
     * 'smsMsgId': Unique ID of an SMS
     * 'total': Number of SMS segments
     * 'sequence': Sequence number of an SMS after splitting
     * 'source': Status report source
     * 'updateTime': Resource update time
     * 'status': Enumeration values of the status report
     * 'orgCode': Status code
     */
    var status = keyValues.status; //Enumerated values of the status report
    //Check whether the SMS is successfully sent based on the value of status.
    if ('DELIVRD' === status.toUpperCase()) {
        console.log('Send sms success. smsMsgId: ', keyValues.smsMsgId);
    } else {
        //The SMS fails to be sent. The values of status and orgCode are recorded.
        console.log('Send sms failed. smsMsgId: ', keyValues.smsMsgId);
        console.log('Failed status: ', status);
        console.log('Failed orgCode: ', keyValues.orgCode);
    }
}

// onSmsStatusReport(success_body);
onSmsStatusReport(failed_body);