sms.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. package sms
  2. import (
  3. "encoding/json"
  4. "github.com/go-resty/resty/v2"
  5. )
  6. const (
  7. SUCCESS = "success"
  8. )
  9. type SMS struct {
  10. Appid string
  11. Signature string
  12. }
  13. func NewSMS(appid, signature string) *SMS {
  14. return &SMS{
  15. Appid: appid,
  16. Signature: signature,
  17. }
  18. }
  19. type SendRes struct {
  20. Status string `json:"status"`
  21. Send_id string `json:"send_id"`
  22. Fee int `json:"fee"`
  23. Msg string `json:"msg"`
  24. Code int `json:"code"`
  25. }
  26. type XSendRes struct {
  27. Status string `json:"status"`
  28. Send_id string `json:"send_id"`
  29. Fee float64 `json:"fee"`
  30. Msg string `json:"msg"`
  31. Code string `json:"code"`
  32. }
  33. // 短信发送
  34. func (t *SMS) Send(to, content string) (SendRes, error) {
  35. client := resty.New()
  36. resp, err := client.R().
  37. SetHeader("Content-Type", "application/x-www-form-urlencoded").
  38. SetFormData(map[string]string{
  39. "appid": t.Appid,
  40. "signature": t.Signature,
  41. "to": to,
  42. "content": content,
  43. }).
  44. SetResult(&SendRes{}).
  45. Post("https://api-v4.mysubmail.com/sms/send.json")
  46. if err != nil {
  47. return SendRes{}, err
  48. }
  49. temp := SendRes{}
  50. if err = json.Unmarshal(resp.Body(), &temp); err != nil {
  51. return SendRes{}, err
  52. }
  53. return temp, nil
  54. }
  55. // 短信模板发送
  56. func (t *SMS) SmsXSend(to, addr string) (XSendRes, error) {
  57. type Vars struct {
  58. Addr string `json:"addr"`
  59. }
  60. vars := Vars{Addr: addr}
  61. b, _ := json.Marshal(vars)
  62. client := resty.New()
  63. resp, err := client.R().
  64. SetHeader("Content-Type", "application/x-www-form-urlencoded").
  65. SetFormData(map[string]string{
  66. "appid": t.Appid,
  67. "signature": t.Signature,
  68. "to": to,
  69. "project": "ZZ7fYr",
  70. "vars": string(b),
  71. }).
  72. SetResult(&XSendRes{}).
  73. Post("https://api-v4.mysubmail.com/sms/xsend")
  74. if err != nil {
  75. return XSendRes{}, err
  76. }
  77. temp := XSendRes{}
  78. if err = json.Unmarshal(resp.Body(), &temp); err != nil {
  79. return XSendRes{}, err
  80. }
  81. return temp, nil
  82. }