sms.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package services
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "hongze/hz_eta_api/services/alarm_msg"
  7. "hongze/hz_eta_api/utils"
  8. "io/ioutil"
  9. "net/http"
  10. "net/url"
  11. )
  12. func SendSmsCode(mobile, ip string, codeType int, vcode string) bool {
  13. flag := false
  14. tplId := ""
  15. switch codeType {
  16. case utils.REGISTER_CODE:
  17. tplId = "206722"
  18. case utils.LOGIN_CODE:
  19. tplId = "65692"
  20. }
  21. result, err := sendSms(mobile, tplId, vcode)
  22. if err != nil {
  23. fmt.Println("发送短信失败")
  24. return false
  25. }
  26. fmt.Println("result", string(result))
  27. var netReturn map[string]interface{}
  28. err = json.Unmarshal(result, &netReturn)
  29. if err != nil {
  30. go alarm_msg.SendAlarmMsg("短信验证码发送失败 ErrMsg:"+err.Error()+" result"+string(result), 3)
  31. //go utils.SendEmail("短信验证码发送失败","err:"+err.Error()+" result"+string(result), utils.EmailSendToUsers)
  32. flag = false
  33. }
  34. if netReturn["error_code"].(float64) == 0 {
  35. fmt.Printf("接口返回result字段是:\r\n%v", netReturn["result"])
  36. flag = true
  37. } else {
  38. go alarm_msg.SendAlarmMsg("短信验证码发送失败 ErrMsg:"+err.Error()+" result"+string(result), 3)
  39. //go utils.SendEmail("短信验证码发送失败"," result"+string(result), utils.EmailSendToUsers)
  40. flag = false
  41. }
  42. return flag
  43. }
  44. func sendSms(mobile, tplId, code string) (rs []byte, err error) {
  45. if utils.JhGnAppKey == `` {
  46. err = errors.New("短信未配置")
  47. return
  48. }
  49. var Url *url.URL
  50. apiURL := "http://v.juhe.cn/sms/send"
  51. //初始化参数
  52. param := url.Values{}
  53. //配置请求参数,方法内部已处理urlencode问题,中文参数可以直接传参
  54. param.Set("mobile", mobile) //接受短信的用户手机号码
  55. param.Set("tpl_id", tplId) //您申请的短信模板ID,根据实际情况修改
  56. param.Set("tpl_value", "#code#="+code) //您设置的模板变量,根据实际情况
  57. param.Set("key", utils.JhGnAppKey) //应用APPKEY(应用详细页查询)
  58. Url, err = url.Parse(apiURL)
  59. if err != nil {
  60. fmt.Printf("解析url错误:\r\n%v", err)
  61. return nil, err
  62. }
  63. //如果参数中有中文参数,这个方法会进行URLEncode
  64. Url.RawQuery = param.Encode()
  65. resp, err := http.Get(Url.String())
  66. if err != nil {
  67. fmt.Println("err:", err)
  68. return nil, err
  69. }
  70. defer resp.Body.Close()
  71. return ioutil.ReadAll(resp.Body)
  72. }