{"_id":"56c74a05af5bc40d00d6bb5b","user":"55116f88e2990b0d00fb0552","__v":10,"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"},"parentDoc":null,"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"},"updates":[],"next":{"pages":[],"description":""},"createdAt":"2016-02-19T16:59:49.029Z","link_external":false,"link_url":"","githubsync":"","sync_unique":"","hidden":false,"api":{"results":{"codes":[]},"settings":"","auth":"required","params":[],"url":""},"isReference":false,"order":4,"body":"[block:callout]\n{\n  \"type\": \"info\",\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.\nYou already have a sample site set up as per the [Send SMS Messages](doc:qs-node-send-sms-messages) sample.\n\n##Registration\nWe're going to create a simple Node.js based web application that verifies a user's phone number during a registration process. We'll make use of the Express package to handle the site framework and the Request-Promise package to handle the REST call to the Dynmark API.\n\n1. Build the registration page view. This will accept the user's phone number and post to itself.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"extends layout\\n\\nblock content\\n\\n    p To complete your registration, please enter your mobile phone number. A verification code will be sent to this number.\\n    form(action=\\\"register\\\" method=\\\"POST\\\")\\n        input(type=\\\"text\\\" name=\\\"phoneNumber\\\" value=\\\"447700090000\\\")\\n        input(type=\\\"submit\\\" value=\\\"Register\\\")\\n\\n    div= message\\n    \",\n      \"language\": \"text\",\n      \"name\": \"jade\"\n    }\n  ]\n}\n[/block]\n2. Build the registration controller\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"var express = require('express');\\nvar request = require('request-promise');\\nvar router = express.Router();\\nglobal.verifyRequestId = null;\\n\\nrouter.get('/register', function(req, res, next) {\\n    res.render('register');\\n});\\n\\nrouter.post('/register', function(req, res, next) {\\n    var phoneNumber = req.body.phoneNumber;\\n    if (phoneNumber)\\n    {\\n        request({\\n            method: 'POST',\\n            url: 'https://services.dynmark.com/webapi/verify',\\n            auth: {\\n                'user': ':::at:::Username@',\\n                'pass': '@Password@'\\n            },\\n            timeout: 130000,\\n            json: true,\\n            body: {\\n                from: \\\"Example\\\",\\n                to: phoneNumber\\n            }\\n        })\\n        .then(function(body) {\\n            global.verifyRequestId = body.requestId;\\n            if (body.numberStatus === \\\"On\\\" || body.numberStatus === \\\"Off\\\")\\n            {\\n                res.redirect(\\\"verify\\\");\\n                res.end();\\n            }\\n            else\\n            {\\n                res.render('register', {message:\\\"Sorry, that number appears to be dead.\\\"});\\n            }\\n        })\\n        .catch(function(err)\\n        {\\n            var errors = \\\"\\\";\\n            if (err.statusCode == 401)\\n            {\\n                errors = \\\"Invalid credentials\\\";\\n            }\\n            else if (err.statusCode == 400)\\n            {\\n                if (err.error.some(r => r.failureCode == \\\"ToInvalid\\\"))\\n                {\\n                    errors += \\\"Your phone number doesn't look like a valid number.\\\";\\n                }\\n                if (err.error.some(r => r.failureCode == \\\"Throttled\\\"))\\n                {\\n                    errors += \\\"Please wait for 30 seconds before requesting a resend.\\\";\\n                }\\n            }\\n            else\\n            {\\n                errors = \\\"Non success response\\\";\\n            }\\n            \\n            res.render('register', {message:errors});\\n        });\\n    }\\n    else\\n    {\\n        res.render('register');\\n    }\\n});\\n\\nmodule.exports = router;\",\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 to render the initial form\n4. We create an Express route that accepts HTTP POST to handle the submission of the form\n  * If a phone number has been supplied we POST a verify create request\n  * If we get a successful response (which will be 202 Created), we check the numberStatus property for *On* and *Off* to see if a code was sent to the phone. Any other value means the code wasn't sent because the number is dead or invalid.\n  * If we get a 400 Bad Request, we check for common error codes and output a message.\n\nNow lets create the the verify page.\n1. Build the verify page view. This will allow the user to enter the code sent to their phone and will post to itself.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"extends layout\\n\\nblock content\\n\\n    p Please enter the code we sent to complete your registration\\n    form(action=\\\"verify\\\" method=\\\"POST\\\")\\n        input(type=\\\"text\\\" name=\\\"code\\\")\\n        input(type=\\\"submit\\\" value=\\\"Verify\\\")\\n\\n    div= message\\n    \",\n      \"language\": \"text\",\n      \"name\": \"jade\"\n    }\n  ]\n}\n[/block]\n2. Add another route to register.js to handle the verify page route\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"router.get('/verify', function(req, res, next) {\\n    res.render('verify');\\n});\\n\\nrouter.post('/verify', function(req, res, next) {\\n    var code = req.body.code;\\n    if (code && global.verifyRequestId)\\n    {\\n        request({\\n            method: 'PUT',\\n            url: 'https://services.dynmark.com/webapi/verify/' + global.verifyRequestId + \\\"/validate\\\",\\n            auth: {\\n                'user': '@Username@',\\n                'pass': '@Password@'\\n            },\\n            timeout: 130000,\\n            json: true,\\n            body: {\\n                code: code\\n            }\\n        })\\n        .then(function(body) {\\n            if (body && body.status == \\\"CodeVerified\\\")\\n            {\\n                res.render('verify', {message:\\\"Your code was correct and is verified.\\\"});\\n            }\\n            else\\n            {\\n                res.render('verify', {message:\\\"Sorry, that code was not recognised. Reason \\\" + (body ? body.status : \\\"CodeUnrecognised\\\")});\\n            }\\n        })\\n        .catch(function(err)\\n        {\\n            var errors = \\\"\\\";\\n            if (err.statusCode == 401)\\n            {\\n                errors = \\\"Invalid credentials\\\";\\n            }\\n            else if (err.statusCode == 400)\\n            {\\n                errors = \\\"Please correct errors\\\";\\n            }\\n            else\\n            {\\n                errors = \\\"Non success response\\\";\\n            }\\n            \\n            res.render('verify', {message:errors});\\n        })\\n        .finally(function()\\n        {\\n        });\\n    }\\n    else\\n    {\\n        res.render('verify');\\n    }\\n});\\n\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\nLets look at the details:.\n1. We create an Express route that accepts HTTP GET to render the initial form\n2. We create an Express route that accepts HTTP POST to handle the submission of the form\n  * If a code has been supplied, we PUT a [verify validate request](doc:rest-verify-validate) with the requestId that we stored earlier.\n  * If we get a successful response (which will be 200 OK) we check the status property for *CodeVerified* to see if the code was accepted. At this point the code is marked as used and subsequent calls with this code will return CodeUnrecognised.\n  * If we get a 400 Bad Request, we check for common error codes and output a message.","excerpt":"An example of how Verify can be used as part of an authentication process to check the owner of a mobile number","slug":"qs-node-verify","type":"basic","title":"Use Verify to check mobile number ownership"}

Use Verify to check mobile number ownership

An example of how Verify can be used as part of an authentication process to check the owner of a mobile number

[block:callout] { "type": "info", "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. You already have a sample site set up as per the [Send SMS Messages](doc:qs-node-send-sms-messages) sample. ##Registration We're going to create a simple Node.js based web application that verifies a user's phone number during a registration process. We'll make use of the Express package to handle the site framework and the Request-Promise package to handle the REST call to the Dynmark API. 1. Build the registration page view. This will accept the user's phone number and post to itself. [block:code] { "codes": [ { "code": "extends layout\n\nblock content\n\n p To complete your registration, please enter your mobile phone number. A verification code will be sent to this number.\n form(action=\"register\" method=\"POST\")\n input(type=\"text\" name=\"phoneNumber\" value=\"447700090000\")\n input(type=\"submit\" value=\"Register\")\n\n div= message\n ", "language": "text", "name": "jade" } ] } [/block] 2. Build the registration controller [block:code] { "codes": [ { "code": "var express = require('express');\nvar request = require('request-promise');\nvar router = express.Router();\nglobal.verifyRequestId = null;\n\nrouter.get('/register', function(req, res, next) {\n res.render('register');\n});\n\nrouter.post('/register', function(req, res, next) {\n var phoneNumber = req.body.phoneNumber;\n if (phoneNumber)\n {\n request({\n method: 'POST',\n url: 'https://services.dynmark.com/webapi/verify',\n auth: {\n 'user': '@Username@',\n 'pass': '@Password@'\n },\n timeout: 130000,\n json: true,\n body: {\n from: \"Example\",\n to: phoneNumber\n }\n })\n .then(function(body) {\n global.verifyRequestId = body.requestId;\n if (body.numberStatus === \"On\" || body.numberStatus === \"Off\")\n {\n res.redirect(\"verify\");\n res.end();\n }\n else\n {\n res.render('register', {message:\"Sorry, that number appears to be dead.\"});\n }\n })\n .catch(function(err)\n {\n var errors = \"\";\n if (err.statusCode == 401)\n {\n errors = \"Invalid credentials\";\n }\n else if (err.statusCode == 400)\n {\n if (err.error.some(r => r.failureCode == \"ToInvalid\"))\n {\n errors += \"Your phone number doesn't look like a valid number.\";\n }\n if (err.error.some(r => r.failureCode == \"Throttled\"))\n {\n errors += \"Please wait for 30 seconds before requesting a resend.\";\n }\n }\n else\n {\n errors = \"Non success response\";\n }\n \n res.render('register', {message:errors});\n });\n }\n else\n {\n res.render('register');\n }\n});\n\nmodule.exports = router;", "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 to render the initial form 4. We create an Express route that accepts HTTP POST to handle the submission of the form * If a phone number has been supplied we POST a verify create request * If we get a successful response (which will be 202 Created), we check the numberStatus property for *On* and *Off* to see if a code was sent to the phone. Any other value means the code wasn't sent because the number is dead or invalid. * If we get a 400 Bad Request, we check for common error codes and output a message. Now lets create the the verify page. 1. Build the verify page view. This will allow the user to enter the code sent to their phone and will post to itself. [block:code] { "codes": [ { "code": "extends layout\n\nblock content\n\n p Please enter the code we sent to complete your registration\n form(action=\"verify\" method=\"POST\")\n input(type=\"text\" name=\"code\")\n input(type=\"submit\" value=\"Verify\")\n\n div= message\n ", "language": "text", "name": "jade" } ] } [/block] 2. Add another route to register.js to handle the verify page route [block:code] { "codes": [ { "code": "router.get('/verify', function(req, res, next) {\n res.render('verify');\n});\n\nrouter.post('/verify', function(req, res, next) {\n var code = req.body.code;\n if (code && global.verifyRequestId)\n {\n request({\n method: 'PUT',\n url: 'https://services.dynmark.com/webapi/verify/' + global.verifyRequestId + \"/validate\",\n auth: {\n 'user': '@Username@',\n 'pass': '@Password@'\n },\n timeout: 130000,\n json: true,\n body: {\n code: code\n }\n })\n .then(function(body) {\n if (body && body.status == \"CodeVerified\")\n {\n res.render('verify', {message:\"Your code was correct and is verified.\"});\n }\n else\n {\n res.render('verify', {message:\"Sorry, that code was not recognised. Reason \" + (body ? body.status : \"CodeUnrecognised\")});\n }\n })\n .catch(function(err)\n {\n var errors = \"\";\n if (err.statusCode == 401)\n {\n errors = \"Invalid credentials\";\n }\n else if (err.statusCode == 400)\n {\n errors = \"Please correct errors\";\n }\n else\n {\n errors = \"Non success response\";\n }\n \n res.render('verify', {message:errors});\n })\n .finally(function()\n {\n });\n }\n else\n {\n res.render('verify');\n }\n});\n", "language": "javascript" } ] } [/block] Lets look at the details:. 1. We create an Express route that accepts HTTP GET to render the initial form 2. We create an Express route that accepts HTTP POST to handle the submission of the form * If a code has been supplied, we PUT a [verify validate request](doc:rest-verify-validate) with the requestId that we stored earlier. * If we get a successful response (which will be 200 OK) we check the status property for *CodeVerified* to see if the code was accepted. At this point the code is marked as used and subsequent calls with this code will return CodeUnrecognised. * If we get a 400 Bad Request, we check for common error codes and output a message.