{"_id":"56b201173b6f690d00bdb68e","project":"568fce2a04440a1700e4cb47","category":{"_id":"56b200c6f48f270d00e0de70","pages":["56b22b962d96461700599228","56b3240705daaa2300363143","56b33a9978a12121009006a1","56b33ab2af176a0d00964ce1","56cae5309f4ae20b00644dca","56d412878001e30b00896dd2","56d6c28947f18a2d0088d620","56d87228a957fb1500765a63"],"project":"568fce2a04440a1700e4cb47","version":"568fce2b04440a1700e4cb4a","__v":8,"sync":{"url":"","isSync":false},"reference":false,"createdAt":"2016-02-03T13:29:42.367Z","from_sync":false,"order":2,"slug":"node","title":"Node.js Quickstarts"},"user":"55116f88e2990b0d00fb0552","version":{"_id":"568fce2b04440a1700e4cb4a","project":"568fce2a04440a1700e4cb47","__v":20,"createdAt":"2016-01-08T14:56:43.101Z","releaseDate":"2016-01-08T14:56:43.101Z","categories":["568fce2b04440a1700e4cb4b","568fd1b8b700ce0d002f4b1c","568fd23804440a1700e4cb5b","568fd2444719c119002ce5d8","568ff21204440a1700e4cbc1","5693732c8aa8040d009f2c28","5693738393445b0d00abdad0","5693740093445b0d00abdad1","56937445974aaa0d001ca699","5693b82173f48f0d0075c90d","5694c4cd1005590d0062cb25","569f854466a5640d00efa54c","56a264cdd15dd70d008d825b","56aa56bf318e6c1700a19ddb","56b0e6347ae4550d000627bd","56b200c0f48f270d00e0de6f","56b200c6f48f270d00e0de70","56b22a9665ddf50d0076ba40","56e92ef71996862200fd7f42","574d6577fb835c0e00ca316a"],"is_deprecated":false,"is_hidden":false,"is_beta":false,"is_stable":true,"codename":"","version_clean":"1.0.0","version":"1.0"},"__v":12,"parentDoc":null,"updates":[],"next":{"pages":[],"description":""},"createdAt":"2016-02-03T13:31:03.865Z","link_external":false,"link_url":"","githubsync":"","sync_unique":"","hidden":false,"api":{"settings":"","results":{"codes":[]},"auth":"required","params":[],"url":""},"isReference":false,"order":0,"body":"[block:callout]\n{\n  \"type\": \"info\",\n  \"title\": \"\",\n  \"body\": \"Full source for these quickstarts can be downloaded from http://download.dynmark.com/Files/API/Quickstart/Node.zip\"\n}\n[/block]\n##Prerequisites\nYou'll need a Dynmark account to be able to send messages. You can use a trial account to send a limited number of free messages for testing.\n\n##Hello World via SMS\nWe're going to create a simple Node.js based web application that sends a hello message when the user lands on a page. We'll make use of the Express package to handle the site framework and the Request package to handle the REST call to the Dynmark API.\n\n1. Create a new Node site\n2. Import *express* and *request-promise* packages using npm\n3. Create sendMessage.js containing a single function \n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"var express = require('express');\\nvar request = require('request-promise');\\nvar router = express.Router();\\n\\nrouter.get('/sendMessage', function(req, res, next) {\\n    request({\\n        method: 'POST',\\n        url: 'https://services.dynmark.com/webapi/message/send',\\n        auth: {\\n            'user': ':::at:::Username@',\\n            'pass': '@Password@'\\n        },\\n        timeout: 130000,\\n        json: true,\\n        body: [{\\n            from: \\\"Example\\\",\\n            to: \\\"447700900000\\\",\\n            body: \\\"Hello, this is a test message\\\",\\n            deliveryStatusUrl: \\\"https://inbound.example.com/SmsReceipts\\\",\\n            clientRef: \\\"msg-\\\" + (++messageId).toString()\\n        }]\\n    })\\n    .then(function(body) {\\n      \\tconsole.log(body);\\n    });\\n});\\n\\nmodule.exports = router;\\n\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\nLets look at the details:\n1. You'll need your Dynmark username and password to authenticate calls.\n2. We use the [Request-Promise](https://www.npmjs.com/package/request-promise) package to send our REST calls to the Dynmark API. You could alternatively use Node's native http.request.\n3. We create an Express route that accepts HTTP GET\n4. We define an SMS message request containing the bare minimum details to send an SMS.\n4. Results are output to the console\n\nUsers often make mistakes entering their details, so we check the HTTP status for common failures and for  Let's add some code to check the response from the API for validation failures:\n\n1. Change the *request* call to check results and add code to check for HTTP 200 OK. This shows that the API call was in a valid format.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"    .then(function(body) {\\n        if (body[0].successful)\\n        {\\n            res.write(\\\"<div>We sent you a message.</div>\\\")\\n        }\\n        else\\n        {\\n            res.write(\\\"<div>Sorry, we couldn't sent you a message.</div>\\\");\\n            if (body[0].validationFailures.some(r => r.failureCode == \\\"ToInvalid\\\"))\\n            {\\n                res.write(\\\"<div>Your phone number doesn't look like a valid number.</div>\\\");\\n            }\\n        }\\n        res.end();\\n    })\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n3. We should also check for HTTP 401 Unauthorised to ensure we're using the right credentials, and since we're using an anonymous type to build the request, HTTP 400 Bad Request to ensure we've submitted a request with no typos or incorrect property names.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"    .catch(function(err)\\n    {\\n        if (err.statusCode == 401)\\n        {\\n            res.write(\\\"<div>Invalid credentials</div>\\\")\\n        }\\n        else if (err.statusCode == 400)\\n        {\\n            res.write(\\\"<div>Bad request format</div>\\\")\\n        }\\n        else\\n        {\\n            res.write(\\\"<div>Non success response</div>\\\")\\n        }\\n        res.end();\\n    });\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]","excerpt":"Sending text messages via the REST API","slug":"qs-node-send-sms-messages","type":"basic","title":"Send SMS Messages"}

Send SMS Messages

Sending text messages via the REST API

[block:callout] { "type": "info", "title": "", "body": "Full source for these quickstarts can be downloaded from http://download.dynmark.com/Files/API/Quickstart/Node.zip" } [/block] ##Prerequisites You'll need a Dynmark account to be able to send messages. You can use a trial account to send a limited number of free messages for testing. ##Hello World via SMS We're going to create a simple Node.js based web application that sends a hello message when the user lands on a page. We'll make use of the Express package to handle the site framework and the Request package to handle the REST call to the Dynmark API. 1. Create a new Node site 2. Import *express* and *request-promise* packages using npm 3. Create sendMessage.js containing a single function [block:code] { "codes": [ { "code": "var express = require('express');\nvar request = require('request-promise');\nvar router = express.Router();\n\nrouter.get('/sendMessage', function(req, res, next) {\n request({\n method: 'POST',\n url: 'https://services.dynmark.com/webapi/message/send',\n auth: {\n 'user': '@Username@',\n 'pass': '@Password@'\n },\n timeout: 130000,\n json: true,\n body: [{\n from: \"Example\",\n to: \"447700900000\",\n body: \"Hello, this is a test message\",\n deliveryStatusUrl: \"https://inbound.example.com/SmsReceipts\",\n clientRef: \"msg-\" + (++messageId).toString()\n }]\n })\n .then(function(body) {\n \tconsole.log(body);\n });\n});\n\nmodule.exports = router;\n", "language": "javascript" } ] } [/block] Lets look at the details: 1. You'll need your Dynmark username and password to authenticate calls. 2. We use the [Request-Promise](https://www.npmjs.com/package/request-promise) package to send our REST calls to the Dynmark API. You could alternatively use Node's native http.request. 3. We create an Express route that accepts HTTP GET 4. We define an SMS message request containing the bare minimum details to send an SMS. 4. Results are output to the console Users often make mistakes entering their details, so we check the HTTP status for common failures and for Let's add some code to check the response from the API for validation failures: 1. Change the *request* call to check results and add code to check for HTTP 200 OK. This shows that the API call was in a valid format. [block:code] { "codes": [ { "code": " .then(function(body) {\n if (body[0].successful)\n {\n res.write(\"<div>We sent you a message.</div>\")\n }\n else\n {\n res.write(\"<div>Sorry, we couldn't sent you a message.</div>\");\n if (body[0].validationFailures.some(r => r.failureCode == \"ToInvalid\"))\n {\n res.write(\"<div>Your phone number doesn't look like a valid number.</div>\");\n }\n }\n res.end();\n })", "language": "javascript" } ] } [/block] 3. We should also check for HTTP 401 Unauthorised to ensure we're using the right credentials, and since we're using an anonymous type to build the request, HTTP 400 Bad Request to ensure we've submitted a request with no typos or incorrect property names. [block:code] { "codes": [ { "code": " .catch(function(err)\n {\n if (err.statusCode == 401)\n {\n res.write(\"<div>Invalid credentials</div>\")\n }\n else if (err.statusCode == 400)\n {\n res.write(\"<div>Bad request format</div>\")\n }\n else\n {\n res.write(\"<div>Non success response</div>\")\n }\n res.end();\n });", "language": "javascript" } ] } [/block]