short_url.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. package basic
  2. import (
  3. "fmt"
  4. "github.com/silenceper/wechat/v2/util"
  5. )
  6. const (
  7. // 将一条长链接转成短链接
  8. // https://developers.weixin.qq.com/doc/offiaccount/Account_Management/URL_Shortener.html
  9. long2shortURL = "https://api.weixin.qq.com/cgi-bin/shorturl?access_token=%s"
  10. long2shortAction = "long2short"
  11. )
  12. type (
  13. reqLong2ShortURL struct {
  14. Action string `json:"action"`
  15. LongURL string `json:"long_url"`
  16. }
  17. resplong2ShortURL struct {
  18. ShortURL string `json:"short_url"`
  19. util.CommonError
  20. }
  21. )
  22. // Long2ShortURL 将一条长链接转成短链接
  23. func (basic *Basic) Long2ShortURL(longURL string) (shortURL string, err error) {
  24. var (
  25. req = &reqLong2ShortURL{
  26. Action: long2shortAction,
  27. LongURL: longURL,
  28. }
  29. resp = new(resplong2ShortURL)
  30. ac, uri string
  31. responseBytes []byte
  32. )
  33. ac, err = basic.GetAccessToken()
  34. if err != nil {
  35. return
  36. }
  37. uri = fmt.Sprintf(long2shortURL, ac)
  38. responseBytes, err = util.PostJSON(uri, req)
  39. if err != nil {
  40. return
  41. }
  42. err = util.DecodeWithError(responseBytes, resp, long2shortAction)
  43. return resp.ShortURL, err
  44. }