From 398f2ec6aed39dac8a6a97e0032e77acb9ef8758 Mon Sep 17 00:00:00 2001 From: kaiiak Date: Mon, 8 Feb 2021 09:42:46 +0800 Subject: [PATCH] long url to short url (#367) * long url to short url * Decode by util.DecodeWithError --- officialaccount/basic/short_url.go | 52 ++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 officialaccount/basic/short_url.go diff --git a/officialaccount/basic/short_url.go b/officialaccount/basic/short_url.go new file mode 100644 index 0000000..94be9bb --- /dev/null +++ b/officialaccount/basic/short_url.go @@ -0,0 +1,52 @@ +package basic + +import ( + "fmt" + + "github.com/silenceper/wechat/v2/util" +) + +const ( + // 将一条长链接转成短链接 + // https://developers.weixin.qq.com/doc/offiaccount/Account_Management/URL_Shortener.html + long2shortURL = "https://api.weixin.qq.com/cgi-bin/shorturl?access_token=%s" + long2shortAction = "long2short" +) + +type ( + reqLong2ShortURL struct { + Action string `json:"action"` + LongURL string `json:"long_url"` + } + resplong2ShortURL struct { + ShortURL string `json:"short_url"` + util.CommonError + } +) + +// Long2ShortURL 将一条长链接转成短链接 +func (basic *Basic) Long2ShortURL(longURL string) (shortURL string, err error) { + var ( + req = &reqLong2ShortURL{ + Action: long2shortAction, + LongURL: longURL, + } + resp = new(resplong2ShortURL) + ac, uri string + responseBytes []byte + ) + ac, err = basic.GetAccessToken() + if err != nil { + return + } + uri = fmt.Sprintf(long2shortURL, ac) + responseBytes, err = util.PostJSON(uri, req) + if err != nil { + return + } + if err = util.DecodeWithError(responseBytes, resp, long2shortAction); err != nil { + return + } + shortURL = resp.ShortURL + return +}