aliyunSMS.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. const express = require('express')
  2. const router = express.Router()
  3. const SMSClient = require('@alicloud/sms-sdk')
  4. const config = require('./config')
  5. // ACCESS_KEY_ID/ACCESS_KEY_SECRET 根据实际申请的账号信息进行替换
  6. const accessKeyId = config.accessKeyId
  7. const secretAccessKey = config.secretAccessKey
  8. const smsClient = new SMSClient({accessKeyId, secretAccessKey})
  9. const main = async (number, code) => {
  10. let data = await smsClient.sendSMS({
  11. PhoneNumbers: number,
  12. SignName: '阿里云短信测试专用',
  13. TemplateCode: 'SMS_133180335',
  14. TemplateParam: '{"code":"' + code + '"}'
  15. })
  16. return data
  17. }
  18. router.post('/', async (req, res) => {
  19. console.log(req.body.number)
  20. let code = Math.floor(Math.random() * 99999)
  21. req.session.code = code
  22. console.log(req.session.code)
  23. if (/^1[3|4|5|8][0-9]\d{4,8}$/.test(req.body.number)) {
  24. try{
  25. let data = await main(req.body.number, code)
  26. if (data.Code === 'OK') {
  27. res.status(201).send({
  28. code: 'ok'
  29. })
  30. } else {
  31. res.status(202).send({
  32. err: '服务器繁忙,请重新再试'
  33. })
  34. }
  35. } catch (e) {
  36. if (e.code == "isv.BUSINESS_LIMIT_CONTROL") {
  37. res.status(202).send({
  38. err: '你号码已经限流,请稍后再试'
  39. })
  40. }
  41. }
  42. } else {
  43. res.status(202).send({
  44. err: '请检查手机格式是否正确'
  45. })
  46. }
  47. })
  48. module.exports = router