Skip to content

Instantly share code, notes, and snippets.

@brunomarks7
Created July 9, 2022 02:13
Show Gist options
  • Save brunomarks7/4e3ef5aafa30450e8e66a9779c748f33 to your computer and use it in GitHub Desktop.
Save brunomarks7/4e3ef5aafa30450e8e66a9779c748f33 to your computer and use it in GitHub Desktop.
Send transactional messages with MessageBird WhatsApp API
const messagebird = require('messagebird')(process.env.MESSAGEBIRD_API_KEY, null, ["ENABLE_CONVERSATIONSAPI_WHATSAPP_SANDBOX"]);
const urlTracker = tracking_code => {
if (tracking_code.slice(0, 2) == 'ME') {
return 'https://melhorrastreio.com.br/rastreio/';
}
return 'https://www.linkcorreios.com.br/';
}
const sendWhatsApp = async function(phone, templateName, params) {
return new Promise((resolve, reject) => {
messagebird.conversations.start({
'to': `55${phone}`,
'channelId': process.env.MESSAGEBIRD_CHANNEL_ID,
'type': 'hsm',
'content': {
'hsm': {
'namespace': process.env.MESSAGEBIRD_TEMPLATE_NAMESPACE_API,
'templateName': templateName,
'language': {
'policy': 'deterministic',
'code': 'pt_BR'
},
'params': params
}
}
}, function (err, response) {
if (err) {
return resolve(err);
}
console.log('whatsapp api sent!')
return resolve(response);
})
})
}
export default async function handler(req, res) {
if (req.method !== 'POST') {
res.status(400).send({ message: 'Only POST requests allowed' })
return
}
const { phone, order_id, tracking_code, first_name, last_name } = req.body
if (phone && order_id && tracking_code && first_name) {
const tracking_link = urlTracker(tracking_code) + tracking_code;
const params = [
{"default": first_name},
{"default": tracking_link}
];
const sendData = await sendWhatsApp(phone, 'tracking_code', params);
const messageID = sendData.id;
if (messageID) {
return res.status(200).json({ 'Status': sendData });
} else {
console.log('error')
return res.status(200).json(sendData);
}
} else {
console.log('Empty tracking code')
return res.status(200).send({ message: 'Empty tracking code' })
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment