new_sms_service.go 5.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  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(redisClient.Context(),"code_msg_"+mobile, code_str, time.Minute*10)
  46. redisClient.Incr(redisClient.Context(),"code_msg_" + mobile + "_" + cur_date).Result()
  47. // 取出地址信息,因为上面已经验证过,这里就直接解密而不做错误判断了
  48. bytesPass, _ := base64.StdEncoding.DecodeString(aespass)
  49. tpass := utils.AESDecrypt(bytesPass)
  50. redisClient.Incr(redisClient.Context(),"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. if err != nil {
  59. return &SMSServiceError{Err: "缺少关键参数"}
  60. }
  61. tpass := utils.AESDecrypt(bytesPass)
  62. if len(tpass) == 0 {
  63. return &SMSServiceError{Err: "缺少关键参数"}
  64. }
  65. cur_date := time.Now().Format("2006-01-02")
  66. add_redis, err := redisClient.Get(redisClient.Context(),"ip:host_" + cur_date + "_" + tpass).Result()
  67. if err != nil {
  68. return &SMSServiceError{Err: "缺少关键参数"}
  69. }
  70. ip_max_send_count, _ := beego.AppConfig.Int("ip_max_send_count")
  71. if add_count, _ := strconv.Atoi(add_redis); add_count >= ip_max_send_count {
  72. return &SMSServiceError{Err: "当前IP发送短信超过限制"}
  73. }
  74. moblie_count, _ := redisClient.Get(redisClient.Context(),"code_msg_" + mobile + "_" + cur_date).Result()
  75. moblie_count_int, _ := strconv.Atoi(moblie_count)
  76. if moblie_max, _ := beego.AppConfig.Int("moblie_max_send_count"); moblie_count_int >= moblie_max {
  77. return &SMSServiceError{Err: "当前手机号发送短信超过限制"}
  78. }
  79. return nil
  80. }
  81. // 指定模板群发短信
  82. // 返回值为发送了 n 条短信、短信平台返回的 report 数组[{"code":"0", "msg":"OK", "smsid":"f96f79240e372587e9284cd580d8f953", "mobile":"18011984299", "count":"1"}]
  83. func batchSendMessage(templateID int, params []string, mobiles []string) (int, []interface{}, error) {
  84. sms_api := beego.AppConfig.String("sms_baseUrl") + "sendsms"
  85. mobileStr := strings.Join(mobiles, ",")
  86. appID, sid, token := getSMSConfig()
  87. requestParams := make(map[string]interface{})
  88. requestParams["appid"] = appID
  89. requestParams["sid"] = sid
  90. requestParams["token"] = token
  91. requestParams["templateid"] = strconv.Itoa(templateID)
  92. requestParams["mobile"] = mobileStr
  93. if params != nil && len(params) != 0 {
  94. paramStr := strings.Join(params, ",")
  95. requestParams["param"] = paramStr
  96. }
  97. paramsBytes, _ := json.Marshal(requestParams)
  98. resp, requestErr := http.Post(sms_api, "application/json", bytes.NewBuffer(paramsBytes))
  99. if requestErr != nil {
  100. utils.ErrorLog("短信平台模板群发接口调用失败: %v", requestErr)
  101. return 0, nil, requestErr
  102. }
  103. defer resp.Body.Close()
  104. body, ioErr := ioutil.ReadAll(resp.Body)
  105. if ioErr != nil {
  106. utils.ErrorLog("短信平台模板群发接口返回数据读取失败: %v", ioErr)
  107. return 0, nil, ioErr
  108. }
  109. var respJSON map[string]interface{}
  110. utils.InfoLog(string(body))
  111. if err := json.Unmarshal([]byte(string(body)), &respJSON); err != nil {
  112. utils.ErrorLog("短信平台模板群发接口返回数据解析JSON失败: %v", err)
  113. return 0, nil, err
  114. }
  115. if respJSON["code"].(string) != "000000" {
  116. msg := respJSON["msg"].(string)
  117. utils.ErrorLog("短信平台模板群发接口请求失败: %v", msg)
  118. return 0, nil, &SMSServiceError{"短信平台模板群发接口请求失败"}
  119. } else {
  120. utils.SuccessLog("短信发送成功 report: %v", respJSON["report"])
  121. if len(mobiles) > 1 {
  122. count, _ := strconv.Atoi(respJSON["count_sum"].(string))
  123. return count, respJSON["report"].([]interface{}), nil
  124. } else {
  125. return 1, nil, nil
  126. }
  127. }
  128. }