sms.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import express from 'express'
  2. import SMS from '../models/sms'
  3. import bulksms from '../config/bulksms'
  4. import base64 from 'base-64'
  5. import fetch from 'node-fetch'
  6. const sms = express.Router()
  7. sms.post('/send', async (req, res) => {
  8. try {
  9. const { recipients, body, sender } = req.body
  10. const Authorization = `Basic ${base64.encode(`${bulksms.tokenId}:${bulksms.tokenSecret}`)}`
  11. const response = await fetch(`https://api.bulksms.com/v1/messages`, {
  12. method: 'POST',
  13. headers: {
  14. 'Content-Type': 'application/json',
  15. Authorization
  16. },
  17. body: JSON.stringify({
  18. to: recipients,
  19. from: sender,
  20. body
  21. })
  22. })
  23. const responseContent = (response.status == 201) ?
  24. await response.json() :
  25. await response.text()
  26. const dbSMS = new SMS({
  27. sent: new Date(),
  28. body,
  29. recipients,
  30. sender,
  31. response: (response.status == 201) ? JSON.stringify(responseContent) : responseContent
  32. })
  33. dbSMS.save()
  34. if (response.status != 201) {
  35. throw Error(responseContent)
  36. }
  37. res.json(responseContent)
  38. } catch (error) {
  39. return res.status(400).json({ msg: error.toString() })
  40. }
  41. })
  42. sms.get('/credits', async (req, res) => {
  43. try {
  44. const Authorization = `Basic ${base64.encode(`${bulksms.tokenId}:${bulksms.tokenSecret}`)}`
  45. const response = await fetch(`https://api.bulksms.com/v1/profile`, {
  46. method: 'GET',
  47. headers: {
  48. Authorization
  49. }
  50. })
  51. if (response.status != 200) {
  52. throw Error(`Received status code ${response.status}`)
  53. }
  54. const responseJson = await response.json()
  55. res.json(responseJson.credits.balance)
  56. } catch (error) {
  57. return res.status(400).json({ msg: error.toString() })
  58. }
  59. })
  60. export default sms