new_sms_service.go 5.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. package service
  2. import (
  3. "bytes"
  4. "encoding/base64"
  5. "encoding/json"
  6. "io/ioutil"
  7. "math/rand"
  8. "net/http"
  9. "strconv"
  10. "strings"
  11. "time"
  12. "Xcx_New/utils"
  13. "github.com/astaxie/beego"
  14. )
  15. type NewSMSServiceError struct {
  16. Err string
  17. }
  18. func (e *NewSMSServiceError) Error() string {
  19. return e.Err
  20. }
  21. // 有如下两个外部可调用的接口:SendSMSUseTemplate、SendSMSWithCustomContent两个函数
  22. // 但是实际上我打算将 SendSMSUseTemplate 作为底层函数使用,不直接提供外界:
  23. // 这需要提供数个默认模板,通过为这几个模板创建独立便利函数,封装 SendSMSUseTemplate 的参数 defaultTemplateID 和 params
  24. // 发送验证码短信
  25. // 参数 aespass 是加密后的地址信息,用于限制频繁调用
  26. func SendVerificationCodeSMS(mobile string, aespass string) error {
  27. if len(mobile) == 0 {
  28. return &SMSServiceError{Err: "手机号为空"}
  29. }
  30. if err := newCheckVerificationCodeSMSLimit(aespass, mobile); err != nil {
  31. return err
  32. }
  33. var code_str string
  34. for i := 0; i < 6; i++ {
  35. rand.Seed(time.Now().UnixNano())
  36. code_str += strconv.Itoa(rand.Intn(10))
  37. }
  38. templateID, _ := beego.AppConfig.Int("sms_verification_code_templateid")
  39. utils.TraceLog("验证码为%v", code_str)
  40. _, _, err := batchSendMessage(templateID, []string{code_str}, []string{mobile})
  41. if err == nil {
  42. redisClient := RedisClient()
  43. defer redisClient.Close()
  44. cur_date := time.Now().Format("2006-01-02")
  45. redisClient.Set("code_msg_"+mobile, code_str, time.Minute*10)
  46. redisClient.Incr("code_msg_" + mobile + "_" + cur_date).Result()
  47. // 取出地址信息,因为上面已经验证过,这里就直接解密而不做错误判断了
  48. bytesPass, _ := base64.StdEncoding.DecodeString(aespass)
  49. tpass := utils.AESDecrypt(bytesPass)
  50. redisClient.Incr("ip:host_" + cur_date + "_" + tpass).Result()
  51. }
  52. return err
  53. }
  54. func newCheckVerificationCodeSMSLimit(aespass string, mobile string) error {
  55. redisClient := RedisClient()
  56. defer redisClient.Close()
  57. bytesPass, err := base64.StdEncoding.DecodeString(aespass)
  58. utils.TraceLog("bytesPass:%v err:%v", bytesPass, err)
  59. utils.TraceLog("aespass:%v", aespass)
  60. if err != nil {
  61. return &SMSServiceError{Err: "缺少关键参数1"}
  62. }
  63. tpass := utils.AESDecrypt(bytesPass)
  64. if len(tpass) == 0 {
  65. return &SMSServiceError{Err: "缺少关键参数2"}
  66. }
  67. cur_date := time.Now().Format("2006-01-02")
  68. add_redis, err := redisClient.Get("ip:host_" + cur_date + "_" + tpass).Result()
  69. if err != nil {
  70. return &SMSServiceError{Err: "缺少关键参数3"}
  71. }
  72. ip_max_send_count, _ := beego.AppConfig.Int("ip_max_send_count")
  73. if add_count, _ := strconv.Atoi(add_redis); add_count >= ip_max_send_count {
  74. return &SMSServiceError{Err: "当前IP发送短信超过限制"}
  75. }
  76. moblie_count, _ := redisClient.Get("code_msg_" + mobile + "_" + cur_date).Result()
  77. moblie_count_int, _ := strconv.Atoi(moblie_count)
  78. if moblie_max, _ := beego.AppConfig.Int("moblie_max_send_count"); moblie_count_int >= moblie_max {
  79. return &SMSServiceError{Err: "当前手机号发送短信超过限制"}
  80. }
  81. return nil
  82. }
  83. // 指定模板群发短信
  84. // 返回值为发送了 n 条短信、短信平台返回的 report 数组[{"code":"0", "msg":"OK", "smsid":"f96f79240e372587e9284cd580d8f953", "mobile":"18011984299", "count":"1"}]
  85. func batchSendMessage(templateID int, params []string, mobiles []string) (int, []interface{}, error) {
  86. sms_api := beego.AppConfig.String("sms_baseUrl") + "sendsms"
  87. mobileStr := strings.Join(mobiles, ",")
  88. appID, sid, token := getSMSConfig()
  89. requestParams := make(map[string]interface{})
  90. requestParams["appid"] = appID
  91. requestParams["sid"] = sid
  92. requestParams["token"] = token
  93. requestParams["templateid"] = strconv.Itoa(templateID)
  94. requestParams["mobile"] = mobileStr
  95. if params != nil && len(params) != 0 {
  96. paramStr := strings.Join(params, ",")
  97. requestParams["param"] = paramStr
  98. }
  99. paramsBytes, _ := json.Marshal(requestParams)
  100. resp, requestErr := http.Post(sms_api, "application/json", bytes.NewBuffer(paramsBytes))
  101. if requestErr != nil {
  102. utils.ErrorLog("短信平台模板群发接口调用失败: %v", requestErr)
  103. return 0, nil, requestErr
  104. }
  105. defer resp.Body.Close()
  106. body, ioErr := ioutil.ReadAll(resp.Body)
  107. if ioErr != nil {
  108. utils.ErrorLog("短信平台模板群发接口返回数据读取失败: %v", ioErr)
  109. return 0, nil, ioErr
  110. }
  111. var respJSON map[string]interface{}
  112. utils.InfoLog(string(body))
  113. if err := json.Unmarshal([]byte(string(body)), &respJSON); err != nil {
  114. utils.ErrorLog("短信平台模板群发接口返回数据解析JSON失败: %v", err)
  115. return 0, nil, err
  116. }
  117. if respJSON["code"].(string) != "000000" {
  118. msg := respJSON["msg"].(string)
  119. utils.ErrorLog("短信平台模板群发接口请求失败: %v", msg)
  120. return 0, nil, &SMSServiceError{"短信平台模板群发接口请求失败"}
  121. } else {
  122. utils.SuccessLog("短信发送成功 report: %v", respJSON["report"])
  123. if len(mobiles) > 1 {
  124. count, _ := strconv.Atoi(respJSON["count_sum"].(string))
  125. return count, respJSON["report"].([]interface{}), nil
  126. } else {
  127. return 1, nil, nil
  128. }
  129. }
  130. }