smsbao.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package smsplat
  2. import (
  3. "fmt"
  4. "net/url"
  5. "strconv"
  6. "strings"
  7. "git.wenlab.co/joe/kettle/htp"
  8. "git.wenlab.co/joe/kettle/sms"
  9. "git.wenlab.co/joe/kettle/utl"
  10. )
  11. const (
  12. url_SENDSMS = "http://api.smsbao.com/sms"
  13. query_SENDSMS = "u=%s&p=%s&m=%s&c=%s"
  14. url_BALANCE = "http://www.smsbao.com/query"
  15. query_BALANCE = "u=%s&p=%s"
  16. )
  17. func NewSmsBao(username, password string) sms.ISms {
  18. return &smsBao{
  19. username: username,
  20. password: password,
  21. c: htp.NewClient(),
  22. }
  23. }
  24. type smsBao struct {
  25. username, password string
  26. c *htp.Client
  27. }
  28. func (self *smsBao) Send(phone, msg string) error {
  29. uri := fmt.Sprintf(url_SENDSMS+"?"+query_SENDSMS, self.username, self.password, phone, url.QueryEscape(msg))
  30. var err error = nil
  31. data, err := self.c.Get(uri)
  32. if err != nil {
  33. return err
  34. }
  35. if string(data) != "0" {
  36. err = sms.ErrSmsNoMoney
  37. }
  38. return err
  39. }
  40. //TODO: this implement is error. // @see official docs
  41. func (self *smsBao) SendTpl(phone, tpl string, params []byte) error {
  42. return self.Send(phone, tpl)
  43. }
  44. func (self *smsBao) GetBalance() (float64, error) {
  45. return 0, utl.ErrNotImplemented
  46. }
  47. func (self *smsBao) GetAvailable() (int64, error) {
  48. uri := fmt.Sprintf(url_BALANCE+"?"+query_BALANCE, self.username, self.password)
  49. clt := htp.NewClient()
  50. data, err := clt.Get(uri)
  51. if err != nil {
  52. return 0, err
  53. }
  54. sbody := fmt.Sprintf("%s", data)
  55. lines := strings.Split(sbody, "\n")
  56. if len(lines) < 2 {
  57. return 0, sms.ErrSmsProviderReturnBadValue
  58. }
  59. if lines[0] != "0" {
  60. return 0, sms.ErrSmsProviderReturnBadValue
  61. }
  62. parts := strings.Split(lines[1], ",")
  63. if len(parts) < 2 {
  64. return 0, sms.ErrSmsProviderReturnBadValue
  65. }
  66. remains, err := strconv.ParseInt(parts[1], 10, 64)
  67. if err != nil {
  68. return 0, err
  69. }
  70. return remains, nil
  71. }
  72. func (self *smsBao) Name() string {
  73. return "smsbao.com"
  74. }