sms.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package services
  2. import (
  3. "errors"
  4. "fmt"
  5. "github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi"
  6. "github.com/jinzhu/gorm"
  7. "lzyd-user-api/common"
  8. "lzyd-user-api/models"
  9. "lzyd-user-api/utils"
  10. )
  11. /**
  12. [Mysql]根据手机号及用户输入的验证码去查询数据
  13. */
  14. func GetValidSms(db *gorm.DB, mobile, code string, smsType int) models.ValidSms {
  15. var sms models.ValidSms
  16. sql := `SELECT sms_id, mobile_phone, valid_code, sms_type, create_at
  17. FROM lzyd_sms_valid
  18. WHERE mobile_phone = ? AND valid_code = ? AND sms_type = ?
  19. ORDER BY create_at DESC LIMIT 1`
  20. db.Raw(sql, mobile, code, smsType).Find(&sms)
  21. //fmt.Println(1111,sms)
  22. return sms
  23. }
  24. /**
  25. [Mysql]根据手机号及用户输入的验证码去查询是否存在用户
  26. */
  27. func GetValidSmsUser (db *gorm.DB, mobile string) models.SmsUser {
  28. var smsU models.SmsUser
  29. sql := `SELECT mobile_phone,is_delete
  30. FROM lzyd_user
  31. WHERE mobile_phone = ? AND is_delete = 0`
  32. db.Raw(sql, mobile).Find(&smsU)
  33. fmt.Println(smsU)
  34. return smsU
  35. }
  36. /**
  37. 根据手机号与类型匹配最近的一条短信记录
  38. */
  39. func GetLastValidSms(db *gorm.DB, mobile string, smsType int) models.ValidSms {
  40. var sms models.ValidSms
  41. sql := "SELECT `sms_id`, valid_code, create_at FROM lzyd_sms_valid WHERE mobile_phone = ? AND sms_type = ? ORDER BY create_at DESC LIMIT 1"
  42. db.Raw(sql, mobile, smsType).Find(&sms)
  43. return sms
  44. }
  45. /**
  46. 获取每天发送短信的总量
  47. */
  48. func CountOfToday(db *gorm.DB, tableName string) int64 {
  49. var count int64
  50. sql := fmt.Sprintf("SELECT COUNT(`sms_id`) FROM %s WHERE create_at > UNIX_TIMESTAMP(CAST(SYSDATE() AS DATE))", tableName)
  51. db.Raw(sql).Count(&count)
  52. return count
  53. }
  54. /**
  55. 调用模板发送短信
  56. */
  57. func SendSingleSms(mobile string, typ int) (string, error) {
  58. random := utils.GenRandomCode()
  59. client, err := dysmsapi.NewClientWithAccessKey(common.RegionId, common.AccessKeyId, common.AccessSecret)
  60. if err != nil {
  61. return "", err
  62. }
  63. request := dysmsapi.CreateSendSmsRequest()
  64. request.Scheme = "http"
  65. request.PhoneNumbers = mobile
  66. request.SignName = common.SignName
  67. request.TemplateCode = common.SmsTemplateCodeMap[typ]
  68. request.TemplateParam = "{\"code\": \"" + random + "\"}"
  69. response, err := client.SendSms(request)
  70. if err != nil {
  71. return "", err
  72. }
  73. if response.Code == "OK" && response.Message == "OK" {
  74. return random, nil
  75. }
  76. return "", errors.New(response.Message)
  77. }