Hi there!
In this post, I'll show you how to send SMS using Globe Labs in NodeJS.
You must be comfortable using JavaScript, Express, and Axios.
Without further ado, let's get started.
Creating our keys in Globe Labs console.
First, create an app in the Globe Labs console.
Let’s add the app name, descriptions, your support email so customers and users can contact you, and your API type.
If you hit submit, the form requires you to put a Redirect URI.
A Redirect URI is a publicly accessible link that will receive an authorization code from Globe Labs after opting in.
Let’s create our Redirect URI using NodeJS.
- Create a folder and initialize an npm project using
npm init -y
. That will create a package.json with default values. - Next, install Express and cors by running the following:
npm install express cors
- In our root folder, create an
index.js
file with the following code below:
const express = require('express');
const cors = require('cors');
// Initialize the app;
const app = express();
// Allows Cross-Origin Resource Sharing for this app.
app.use(cors());
app.use(express.json());
// Assign a port where the app is exposed.
const port = process.env.PORT || 8080;
// For now, we just need to log each request received.
// Globe Labs requires the endpoint to send a 200 OK status.
app.get('/', (req, res) => {
console.log(req.query);
res.sendStatus(200);
});
- Open the package.json file add a
start
script under the scripts field.
"scripts": {
"start": "node index.js",
},
And we're good! We can deploy this code in Heroku, Google Cloud, or AWS, which will provide you a public HTTP endpoint for our Redirect URI.
In this tutorial, I’m going to use Heroku. Here’s a guide on how to create and initialize a Heroku App to your NodeJS project.
- I’m going to initialize Git in my folder by running the following:
git init
Create a .gitignore
file and add /node_modules so we can ignore the dependency folder.
- Build and deploy to Heroku by running:
heroku git:remote -a <your folder name for the app>
git add .
git commit -m "Initialized files"
git push heroku master
If we now go back to our console and click “Open App”, a tab will open with your publicly accessible URI.
Go back to the Globe Labs, enter our publicly accessible URI to the form, and hit Submit.
Now we have a Short Code, App ID, and App Secret.
These are sensitive credentials so store them properly!
Acquiring Permissions from our Users.
Privacy is essential for people today and we should treat personal information as sensitive data.
Globe Labs allows users to opt-in or stop receiving SMS in the future.
For now, we are going to use WebForm to get permissions from our users. We need to provide an experience from our apps that will redirect them to this specific link:
https://developer.globelabs.com.ph/dialog/oauth/YOUR_APP_ID_HERE
The link will show a verification page that asks permission to send SMS to the user's number.
Note: It is important that you redirect your users first to the permissions screen. The link pattern is shown above. Once the user successfully gave their permission to use their number, you can start receiving an authorization code which you can exchange for the access token.
To exchange the authorization code to access token, we need to update our code to the following:
First, we need to add our APP_ID and APP_SECRET in our server’s config vars.
There are better ways of storing APP_SECRET using Key Management Systems. For this tutorial, we’ll set this to our app's Config Vars. Here's a guide from Heroku.
Next, we need to update our endpoint to handle the code sent by Globe Labs after receiving permission.
// in your index.js
app.get('/', (req, res) => {
const APP_ID = process.env.APP_ID;
const APP_SECRET = process.env.APP_SECRET;
const code = req.query.code;
if (!code) {
res.status(403).send({ message: 'Invalid request.'});
};
});
The code shall be sent to our server from Globe Labs via request query. We should also handle what happens if we received an empty code.
Next, we need to construct a URL to send the request back to Globe Labs.
// in your index.js
app.get('/', (req, res) => {
const APP_ID = process.env.APP_ID;
const APP_SECRET = process.env.APP_SECRET;
const code = req.query.code;
if (!code) {
res.status(403).send({ message: 'Invalid request.'});
};
// Construct our POST url.
const globe_labs_url = `https://developer.globelabs.com.ph/oauth/access_token?app_id=${APP_ID}&app_secret=${APP_SECRET}&code=${code}`;
});
To send the request, we are going to use Axios.
First, we need to install it as our dependency:
npm install axios
Then, import it on top of our app.
// in your index.js
const express = require('express');
const cors = require('cors');
const axios = require('axios').default;
After that, send an empty request to the constructed URL earlier.
// Send it to Globe Labs!
axios.post(globe_labs_url, {})
.then((response) => {
const access_token = response.data.access_token;
const subscriber_number = response.data.subscriber_number;
// Store this to the database!
console.log(access_token, subscriber_number);
res.send(`Thank you for registering your phone number. To stop receiving SMS notifications, send STOP to ${SHORT_CODE} for Globe or ${SHORT_CODE_CROSS_TELCO} for other networks.`);
})
.catch((err) => {
// If there was an error, we should log it.
console.error(err);
response.status(500).send({ message: 'Internal Server Error'});
})
Your index.js should look like this:
// in your index.js
const express = require('express');
const cors = require('cors');
const axios = require('axios').default;
// Initialize the app;
const app = express();
// Allows Cross-Origin Resource Sharing for this app.
app.use(cors());
app.use(express.json());
app.get('/', (req, res) => {
const APP_ID = process.env.APP_ID;
const APP_SECRET = process.env.APP_SECRET;
const code = req.query.code;
if (!code) {
res.status(403).send({ message: 'Invalid request.'});
};
// Construct our POST url.
const globe_labs_url = `https://developer.globelabs.com.ph/oauth/access_token?app_id=${APP_ID}&app_secret=${APP_SECRET}&code=${code}`;
// Send it to Globe Labs!
axios.post(globe_labs_url, {})
.then((response) => {
const access_token = response.data.access_token;
const subscriber_number = response.data.subscriber_number;
// Store this to the database!
console.log(access_token, subscriber_number);
res.send(`Thank you for registering your phone number. To stop receiving SMS notifications, send STOP to ${SHORT_CODE} for Globe or ${SHORT_CODE_CROSS_TELCO} for other networks.`);
})
.catch((err) => {
// If there was an error, we should log it.
console.error(err);
res.status(500).send({ message: 'Internal Server Error'});
})
});
app.listen(port, () => {
console.log(`Server is up on port ${port}`);
})
The response includes an access token and the subscriber's number.
It’s time to send SMS!
Now that we have the user’s access token, we can now send SMS.
First, we have to modify our code and add an endpoint that allows us to send the message.
Add the following code on top above the app.listen
line.
app.post('/send', (req, res) => {
// Get the access token, the subscriber number and the message from the request.
const access_token = req.body.access_token;
const subscriber_number = req.body.subscriber_number;
const message = req.body.message;
// Next, we need our app short code's last 4 digits;
const SHORT_CODE_SUFFIX = process.env.SHORT_CODE.substr(-4);
// Then, we need to compose our payload that we will send to Globe Labs.
const payload = {
outboundSMSMessageRequest: {
outboundSMSTextMessage: {
message: message
},
senderAddress: SHORT_CODE_SUFFIX,
address: `+63${subscriber_number}`
}
}
// Compose our url
const url = `https://devapi.globelabs.com.ph/smsmessaging/v1/outbound/${SHORT_CODE_SUFFIX}/requests?access_token=${access_token}`;
// Send the request via Axios.
axios.post(url, payload, {
headers: {
'Content-Type': 'application/json'
}
})
.then(() => {
// Success!
res.send(`Message sent!`);
})
.catch((err) => {
// If there was an error, we should log it.
console.error(err);
res.sendStatus(500);
})
});
This creates a POST endpoint that accepts an access token, subscriber number, and the message that we want to send to a user.
Using Postman, we can test the endpoint by entering the following:
<Redirect URI> + / + send
In this case:
If we now hit send, the entered (verified) number should start receiving SMS!
Important Notes
The subscriber’s number should match the provided access token from the successful verification. For this demo, we used
+63
as the country code.You will get a 401 response from Globe Labs if you try to enter a number with a different access token. Same results if you try to enter an unverified number.
You should monitor your Globe Labs wallet! Your topped-up balance expires after one year.
The access token shall no longer work when your user sends
STOP
(orSTOPSVC
for other networks) to your shortcode. Your redirect URI shall receive JSON data of the unsubscription event. You should be able to handle this on your backend.
The code is available at this repo.
Top comments (3)
Hi, Thank you for sharing, and more power to Globelabs Team.
I have a question, is there any cost on Opt-in via SMS to the subscribers?
Hi John! Sorry for a very late reply
As of current documentation, there's no cost of opting in via SMS to subscribers. The charge (on your wallet) comes after you use your API credentials in sending SMS.
Hello Sir Ivan, May I know if the Location Based Service API of Globe Labs is still working? I keep getting an error: no location result from any of my subscribers.