sms.go 1.9 KB

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