另客网go项目公用的代码库

sms.go 1.6KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package notice
  2. import (
  3. "encoding/xml"
  4. "fmt"
  5. "io/ioutil"
  6. "net/http"
  7. "net/url"
  8. "strings"
  9. )
  10. func SendChineseSMS(host, user, pass, mobile, content string) error {
  11. client := &http.Client{}
  12. req, err := http.NewRequest("POST", host, strings.NewReader("account="+user+"&password="+pass+"&mobile="+mobile+"&content="+content))
  13. if err != nil {
  14. return err
  15. }
  16. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  17. resp, err := client.Do(req)
  18. if err != nil {
  19. return err
  20. }
  21. defer resp.Body.Close()
  22. body, err := ioutil.ReadAll(resp.Body)
  23. if err != nil {
  24. return err
  25. }
  26. result := struct {
  27. Code int `xml:"code"`
  28. Msg string `xml:"msg"`
  29. }{}
  30. err = xml.Unmarshal(body, &result)
  31. if err != nil {
  32. return err
  33. }
  34. if result.Code != 2 {
  35. switch result.Code {
  36. case 406, 4030:
  37. return fmt.Errorf("phone number format is not correct")
  38. case 4072:
  39. return fmt.Errorf("your message must match the templat")
  40. case 4081:
  41. return fmt.Errorf("one verification code per minute per phone")
  42. case 4085:
  43. return fmt.Errorf("up to 5 verification codes a day")
  44. default:
  45. return fmt.Errorf("send sms faild")
  46. }
  47. }
  48. return nil
  49. }
  50. func SendForeignSMS(user, pass, mobile, content string) error {
  51. content = url.QueryEscape(content)
  52. url := "http://222.73.117.140:8044/mt?dc=15&tf=3&rf=1&un=" + user + "&pw=" + pass + "&da=" + mobile + "&sm=" + content
  53. resp, err := http.Get(url)
  54. if err != nil {
  55. return err
  56. }
  57. defer resp.Body.Close()
  58. body, err := ioutil.ReadAll(resp.Body)
  59. if err != nil {
  60. return err
  61. }
  62. result := string(body)
  63. if !strings.Contains(result, "id") {
  64. return fmt.Errorf("phone number format is not correct")
  65. }
  66. return nil
  67. }