client.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. package wechat
  2. import (
  3. "encoding/hex"
  4. "encoding/json"
  5. "fmt"
  6. "net/url"
  7. "time"
  8. "git.chuangxin1.com/myth/sacred/cache"
  9. "git.chuangxin1.com/myth/sacred/hash"
  10. )
  11. // NewClient new client
  12. func NewClient(appID, appSecret, token, encodingAESKey string) *Client {
  13. key := keyC(appID)
  14. if v, ok := cache.Load(key); ok {
  15. return v.(*Client)
  16. }
  17. c := &Client{AppID: appID, AppSecret: appSecret, Token: token, EncodingAESKey: encodingAESKey}
  18. cache.Store(key, c)
  19. return c
  20. }
  21. // TokenFromCache token from cache
  22. func (wc *Client) TokenFromCache(ok bool) {
  23. wc.UseCacheToken = ok
  24. }
  25. // getToken get token
  26. func (wc *Client) getToken() (token string, err error) {
  27. key := keyToken(wc.AppID)
  28. if wc.UseCacheToken {
  29. var ct ClientToken
  30. s := ``
  31. s, err = cache.RedisGet(key)
  32. if err != nil {
  33. return
  34. }
  35. err = json.Unmarshal([]byte(s), &ct)
  36. if err != nil {
  37. return
  38. }
  39. token = ct.AccessToken
  40. return
  41. }
  42. now := time.Now().Unix()
  43. if wc.LastTokenTime > 0 {
  44. if now-wc.LastTokenTime < TokenExpires {
  45. token = wc.AccessToken
  46. return
  47. }
  48. }
  49. token, err = wc.RefreshToken(now)
  50. return
  51. }
  52. // RefreshToken refresh token, now current timestamp
  53. func (wc *Client) RefreshToken(now int64) (token string, err error) {
  54. key := keyToken(wc.AppID)
  55. uri := BaseURL + "/cgi-bin/token?"
  56. args := url.Values{}
  57. args.Add("grant_type", "client_credential")
  58. args.Add("appid", wc.AppID)
  59. args.Add("secret", wc.AppSecret)
  60. uri += args.Encode()
  61. var res ResponseToken
  62. _, err = getJSON(uri, &res)
  63. if err != nil {
  64. return
  65. }
  66. err = res.Check()
  67. if err != nil {
  68. return
  69. }
  70. wc.LastTokenTime = now
  71. wc.AccessToken = res.AccessToken
  72. cache.Store(keyC(wc.AppID), wc)
  73. ct := ClientToken{AppID: wc.AppID, AccessToken: wc.AccessToken, LastTokenTime: now}
  74. bs, _ := json.Marshal(ct)
  75. cache.RedisSet(key, string(bs), 0)
  76. token = res.AccessToken
  77. return
  78. }
  79. func (wc *Client) getTicket(now int64) (ticket string, err error) {
  80. key := keyTicket(wc.AppID)
  81. if wc.UseCacheToken {
  82. var ct ClientTicket
  83. s := ``
  84. s, err = cache.RedisGet(key)
  85. if err != nil {
  86. return
  87. }
  88. err = json.Unmarshal([]byte(s), &ct)
  89. if err != nil {
  90. return
  91. }
  92. ticket = ct.Ticket
  93. return
  94. }
  95. if wc.LastTicketTime > 0 {
  96. if now-wc.LastTicketTime < TicketExpires {
  97. ticket = wc.Ticket
  98. return
  99. }
  100. }
  101. ticket, err = wc.RefreshTicket(now)
  102. return
  103. }
  104. // RefreshTicket refresh tocket, now current timestamp
  105. func (wc *Client) RefreshTicket(now int64) (ticket string, err error) {
  106. key := keyTicket(wc.AppID)
  107. args := url.Values{}
  108. args.Add("access_token", wc.AccessToken)
  109. args.Add("type", "jsapi")
  110. uri := BaseURL + "/cgi-bin/ticket/getticket?"
  111. uri += args.Encode()
  112. var res ResponseTicket
  113. _, err = getJSON(uri, &res)
  114. if err != nil {
  115. return
  116. }
  117. err = res.Check()
  118. if err != nil {
  119. return
  120. }
  121. wc.LastTicketTime = now
  122. wc.Ticket = res.Ticket
  123. cache.Store(keyC(wc.AppID), wc)
  124. ct := ClientTicket{AppID: wc.AppID, LastTicketTime: now, Ticket: res.Ticket}
  125. bs, _ := json.Marshal(ct)
  126. cache.RedisSet(key, string(bs), 0)
  127. ticket = res.Ticket
  128. return
  129. }
  130. // Info client info
  131. func (wc Client) Info() (c *Client, ct ClientToken, ct1 ClientTicket, err error) {
  132. key := keyC(wc.AppID)
  133. if v, ok := cache.Load(key); ok {
  134. c = v.(*Client)
  135. }
  136. s := ``
  137. s, err = cache.RedisGet(keyToken(wc.AppID))
  138. if err != nil {
  139. return
  140. }
  141. err = json.Unmarshal([]byte(s), &ct)
  142. if err != nil {
  143. return
  144. }
  145. s, err = cache.RedisGet(keyTicket(wc.AppID))
  146. if err != nil {
  147. return
  148. }
  149. err = json.Unmarshal([]byte(s), &ct1)
  150. if err != nil {
  151. return
  152. }
  153. return
  154. }
  155. // GetUserInfo user info
  156. func (wc Client) GetUserInfo(openid string) (res UserInfo, err error) {
  157. uri := BaseURL + "/cgi-bin/user/info?"
  158. if wc.AccessToken, err = wc.getToken(); err != nil {
  159. return
  160. }
  161. args := url.Values{}
  162. args.Add("access_token", wc.AccessToken)
  163. args.Add("openid", openid)
  164. args.Add("lang", "zh_CN")
  165. uri += args.Encode()
  166. _, err = getJSON(uri, &res)
  167. if err != nil {
  168. return
  169. }
  170. err = res.Check()
  171. return
  172. }
  173. // GetUserList user list
  174. func (wc Client) GetUserList(nextOpenID string) (res UserList, err error) {
  175. uri := BaseURL + "/cgi-bin/user/get?"
  176. if wc.AccessToken, err = wc.getToken(); err != nil {
  177. return
  178. }
  179. args := url.Values{}
  180. args.Add("access_token", wc.AccessToken)
  181. args.Add("next_openid", nextOpenID)
  182. uri += args.Encode()
  183. _, err = getJSON(uri, &res)
  184. if err != nil {
  185. return
  186. }
  187. err = res.Check()
  188. return
  189. }
  190. // GetMaterial 永久资料
  191. func (wc Client) GetMaterial(mtype string, offset, count int) (res Material, err error) {
  192. uri := BaseURL + "/cgi-bin/material/batchget_material?"
  193. if wc.AccessToken, err = wc.getToken(); err != nil {
  194. return
  195. }
  196. args := url.Values{}
  197. data := make(map[string]interface{})
  198. args.Add("access_token", wc.AccessToken)
  199. data["type"] = mtype
  200. data["offset"] = offset
  201. data["count"] = count
  202. uri += args.Encode()
  203. _, err = getJSON(uri, &res)
  204. if err != nil {
  205. return
  206. }
  207. err = res.Check()
  208. return
  209. }
  210. // GetMenu 查询自定义菜单
  211. func (wc Client) GetMenu() (res Menu, err error) {
  212. uri := BaseURL + "/cgi-bin/get_current_selfmenu_info?"
  213. if wc.AccessToken, err = wc.getToken(); err != nil {
  214. return
  215. }
  216. args := url.Values{}
  217. args.Add("access_token", wc.AccessToken)
  218. uri += args.Encode()
  219. _, err = getJSON(uri, &res)
  220. if err != nil {
  221. return
  222. }
  223. err = res.Check()
  224. return
  225. }
  226. // CreateMenu 创建自定义菜单
  227. func (wc Client) CreateMenu(menu FormMenu) (err error) {
  228. uri := BaseURL + "/cgi-bin/menu/create?"
  229. if wc.AccessToken, err = wc.getToken(); err != nil {
  230. return
  231. }
  232. args := url.Values{}
  233. args.Add("access_token", wc.AccessToken)
  234. uri += args.Encode()
  235. var res ResponseMsg
  236. _, err = postJSON(&res, uri, menu)
  237. if err != nil {
  238. return
  239. }
  240. err = res.Check()
  241. return
  242. }
  243. // GetSignPackage JS 签名
  244. // uri 当前 URL
  245. // nonceStr 随机字符串
  246. func (wc Client) GetSignPackage(uri, nonceStr string) (sign SignPackage, err error) {
  247. if wc.AccessToken, err = wc.getToken(); err != nil {
  248. return
  249. }
  250. var (
  251. s string
  252. unix int64
  253. )
  254. unix = time.Now().Unix()
  255. if wc.Ticket, err = wc.getTicket(unix); err != nil {
  256. return
  257. }
  258. s = `jsapi_ticket=` + wc.Ticket
  259. s += `&noncestr=` + nonceStr
  260. s += `&timestamp=` + fmt.Sprintf("%d", unix)
  261. s += `&url=` + uri
  262. hs, _ := hash.SHA1([]byte(s))
  263. sign.AppID = wc.AppID
  264. sign.NonceStr = nonceStr
  265. sign.Signature = hex.EncodeToString(hs)
  266. sign.Timestamp = unix
  267. sign.Ticket = wc.Ticket
  268. sign.URL = uri
  269. return
  270. }
  271. // SendTemplateMessage send template message
  272. // POST /cgi-bin/message/template/send?access_token=ACCESS_TOKEN
  273. func (wc Client) SendTemplateMessage(template TemplateMessage) (res TemplateResponse, err error) {
  274. uri := BaseURL + "/cgi-bin/message/template/send?"
  275. if wc.AccessToken, err = wc.getToken(); err != nil {
  276. return
  277. }
  278. args := url.Values{}
  279. args.Add("access_token", wc.AccessToken)
  280. uri += args.Encode()
  281. _, err = postJSON(&res, uri, template)
  282. if err != nil {
  283. return
  284. }
  285. err = res.Check()
  286. return
  287. }