client.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. package wechat
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "net/url"
  7. "time"
  8. "git.chuangxin1.com/cx/myth/cache"
  9. "git.chuangxin1.com/cx/myth"
  10. )
  11. func keyC(appid string) string {
  12. return "wechat:client:" + appid
  13. }
  14. func keyToken(appid string) string {
  15. return "wechat:client:token:" + appid
  16. }
  17. func keyTicket(appid string) string {
  18. return "wechat:client:ticket:" + appid
  19. }
  20. // NewClient new client
  21. func NewClient(appID, appSecret, token, encodingAESKey string) *Client {
  22. key := keyC(appID)
  23. if v, ok := memcache.Load(key); ok {
  24. return v.(*Client)
  25. }
  26. c := &Client{AppID: appID, AppSecret: appSecret, Token: token, EncodingAESKey: encodingAESKey, UseCacheToken: true}
  27. memcache.Store(key, c)
  28. return c
  29. }
  30. // getToken get token
  31. func (wc *Client) getToken() (token string, err error) {
  32. key := keyToken(wc.AppID)
  33. if wc.UseCacheToken {
  34. var ct ClientToken
  35. s := ``
  36. s, err = cache.Get(key)
  37. if err != nil {
  38. return
  39. }
  40. err = json.Unmarshal([]byte(s), &ct)
  41. if err != nil {
  42. return
  43. }
  44. token = ct.AccessToken
  45. return
  46. }
  47. //wc.ReadLock.Lock()
  48. //defer wc.ReadLock.Unlock()
  49. now := time.Now().Unix()
  50. if wc.LastTokenTime > 0 {
  51. if now-wc.LastTokenTime < TokenExpires {
  52. token = wc.AccessToken
  53. return
  54. }
  55. }
  56. token, err = wc.upToken(key, now)
  57. return
  58. }
  59. func (wc *Client) upToken(key string, now int64) (token string, err error) {
  60. uri := BaseURL + "/cgi-bin/token?"
  61. args := url.Values{}
  62. args.Add("grant_type", "client_credential")
  63. args.Add("appid", wc.AppID)
  64. args.Add("secret", wc.AppSecret)
  65. uri += args.Encode()
  66. var jq *myth.JSONQuery
  67. if jq, err = getJSON(uri); err == nil {
  68. wc.LastTokenTime = now
  69. var accessToken string
  70. accessToken, err = jq.String(`access_token`)
  71. wc.AccessToken = accessToken
  72. token = wc.AccessToken
  73. key1 := keyC(wc.AppID)
  74. memcache.Store(key1, wc)
  75. ct := ClientToken{AppID: wc.AppID, AccessToken: wc.AccessToken, LastTokenTime: now}
  76. bs, _ := json.Marshal(ct)
  77. cache.Set(key, string(bs), 0)
  78. //cache.Store(key, accessToken)
  79. //log.Println("upToken", key, string(bs))
  80. }
  81. return
  82. }
  83. // 更新公众号 access_token
  84. func (wc *Client) UpdateToken() (token string, err error) {
  85. key := keyToken(wc.AppID)
  86. token, err = wc.upToken(key, time.Now().Unix())
  87. return
  88. }
  89. func (wc *Client) getTicket(now int64) (ticket string, err error) {
  90. key := keyTicket(wc.AppID)
  91. if wc.UseCacheToken {
  92. var ct ClientTicket
  93. s := ``
  94. s, err = cache.Get(key)
  95. if err != nil {
  96. return
  97. }
  98. err = json.Unmarshal([]byte(s), &ct)
  99. if err != nil {
  100. return
  101. }
  102. ticket = ct.Ticket
  103. return
  104. }
  105. //now := time.Now().Unix()
  106. var jq *myth.JSONQuery
  107. if wc.LastTicketTime > 0 {
  108. if now-wc.LastTicketTime < TicketExpires {
  109. ticket = wc.Ticket
  110. return
  111. }
  112. }
  113. args := url.Values{}
  114. args.Add("access_token", wc.AccessToken)
  115. args.Add("type", "jsapi")
  116. uri := BaseURL + "/cgi-bin/ticket/getticket?"
  117. uri += args.Encode()
  118. if jq, err = getJSON(uri); err == nil {
  119. ticket, err = jq.String(`ticket`)
  120. wc.LastTicketTime = now
  121. wc.Ticket = ticket
  122. key := keyC(wc.AppID)
  123. memcache.Store(key, wc)
  124. var ct ClientTicket
  125. ct.AppID = wc.AppID
  126. ct.Ticket = ticket
  127. ct.LastTicketTime = now
  128. bs, _ := json.Marshal(ct)
  129. cache.Set(key, string(bs), 0)
  130. }
  131. return
  132. }
  133. func (wc *Client) upTicket(now int64) (ticket string, err error) {
  134. key := keyTicket(wc.AppID)
  135. var jq *myth.JSONQuery
  136. args := url.Values{}
  137. args.Add("access_token", wc.AccessToken)
  138. args.Add("type", "jsapi")
  139. uri := BaseURL + "/cgi-bin/ticket/getticket?"
  140. uri += args.Encode()
  141. if jq, err = getJSON(uri); err == nil {
  142. ticket, err = jq.String(`ticket`)
  143. wc.LastTicketTime = now
  144. wc.Ticket = ticket
  145. var ct ClientTicket
  146. ct.AppID = wc.AppID
  147. ct.LastTicketTime = now
  148. ct.Ticket = ticket
  149. bs, _ := json.Marshal(ct)
  150. cache.Set(key, string(bs), 0)
  151. //log.Println("upTicket", key, string(bs))
  152. }
  153. return
  154. }
  155. // 更新公众号 js ticket
  156. func (wc *Client) UpdateTicket() (ticket string, err error) {
  157. ticket, err = wc.upTicket(time.Now().Unix())
  158. return
  159. }
  160. // TokenUseCache token from cache
  161. func (wc *Client) TokenUseCache(ok bool) {
  162. wc.UseCacheToken = ok
  163. wc.TokenFromCache = ok
  164. }
  165. // GetCodeURL get code 授权获取 OpenID URL(静默授权)
  166. // /connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect
  167. // 转向到
  168. // redirect_uri/?code=CODE&state=STATE
  169. func (wc Client) GetCodeURL(redirectURL, state string) (uri string) {
  170. uri = OpenURL + "/connect/oauth2/authorize?"
  171. args := url.Values{}
  172. args.Add("appid", wc.AppID)
  173. args.Add("redirect_uri", redirectURL)
  174. args.Add("response_type", "code")
  175. args.Add("scope", "snsapi_base")
  176. args.Add("state", state)
  177. uri += args.Encode()
  178. uri += "#wechat_redirect"
  179. return
  180. }
  181. // GetUserInfoCodeURL get code 授权获取 OpenID URL
  182. // /connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
  183. // 转向到
  184. // redirect_uri/?code=CODE&state=STATE
  185. func (wc Client) GetUserInfoCodeURL(redirectURL, state string) (uri string) {
  186. uri = OpenURL + "/connect/oauth2/authorize?"
  187. args := url.Values{}
  188. args.Add("appid", wc.AppID)
  189. args.Add("redirect_uri", redirectURL)
  190. args.Add("response_type", "code")
  191. args.Add("scope", "snsapi_userinfo")
  192. args.Add("state", state)
  193. uri += args.Encode()
  194. uri += "#wechat_redirect"
  195. return
  196. }
  197. // GetOpenID 获取 OpenID
  198. // /sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
  199. func (wc Client) GetOpenID(code string) (jq *myth.JSONQuery, err error) {
  200. uri := BaseURL + "/sns/oauth2/access_token?"
  201. if wc.AccessToken, err = wc.getToken(); err != nil {
  202. return
  203. }
  204. args := url.Values{}
  205. args.Add("access_token", wc.AccessToken)
  206. args.Add("appid", wc.AppID)
  207. args.Add("secret", wc.AppSecret)
  208. args.Add("code", code)
  209. args.Add("grant_type", "authorization_code")
  210. uri += args.Encode()
  211. jq, err = getJSON(uri)
  212. return
  213. }
  214. // GetUserInfo user info
  215. func (wc Client) GetUserInfo(openid string) (info UserInfo, err error) {
  216. uri := BaseURL + "/cgi-bin/user/info?"
  217. if wc.AccessToken, err = wc.getToken(); err != nil {
  218. return
  219. }
  220. args := url.Values{}
  221. args.Add("access_token", wc.AccessToken)
  222. args.Add("openid", openid)
  223. args.Add("lang", "zh_CN")
  224. uri += args.Encode()
  225. var msg myth.HTTPMessage
  226. msg, err = getBody(uri)
  227. if err == nil {
  228. err = msg.JSON(&info)
  229. }
  230. return
  231. }
  232. // GetUserList user list
  233. func (wc Client) GetUserList(nextOpenID string) (list UserList, err error) {
  234. uri := BaseURL + "/cgi-bin/user/get?"
  235. if wc.AccessToken, err = wc.getToken(); err != nil {
  236. return
  237. }
  238. args := url.Values{}
  239. args.Add("access_token", wc.AccessToken)
  240. args.Add("next_openid", nextOpenID)
  241. uri += args.Encode()
  242. var msg myth.HTTPMessage
  243. msg, err = getBody(uri)
  244. if err == nil {
  245. err = msg.JSON(&list)
  246. }
  247. return
  248. }
  249. // GetMaterial 永久资料
  250. func (wc Client) GetMaterial(mtype string, offset, count int) (material Material, err error) {
  251. uri := BaseURL + "/cgi-bin/material/batchget_material?"
  252. if wc.AccessToken, err = wc.getToken(); err != nil {
  253. return
  254. }
  255. args := url.Values{}
  256. data := make(map[string]interface{})
  257. args.Add("access_token", wc.AccessToken)
  258. data["type"] = mtype
  259. data["offset"] = offset
  260. data["count"] = count
  261. uri += args.Encode()
  262. var msg myth.HTTPMessage
  263. msg, err = postJSON(uri, data)
  264. if err == nil {
  265. err = msg.JSON(&material)
  266. }
  267. return
  268. }
  269. // GetMenu 查询自定义菜单
  270. func (wc Client) GetMenu() (menu Menu, err error) {
  271. uri := BaseURL + "/cgi-bin/get_current_selfmenu_info?"
  272. if wc.AccessToken, err = wc.getToken(); err != nil {
  273. return
  274. }
  275. args := url.Values{}
  276. data := make(map[string]interface{})
  277. args.Add("access_token", wc.AccessToken)
  278. uri += args.Encode()
  279. var msg myth.HTTPMessage
  280. msg, err = postJSON(uri, data)
  281. if err == nil {
  282. err = msg.JSON(&menu)
  283. }
  284. return
  285. }
  286. // CreateMenu 创建自定义菜单
  287. func (wc Client) CreateMenu(menu FormMenu) (err error) {
  288. uri := BaseURL + "/cgi-bin/menu/create?"
  289. if wc.AccessToken, err = wc.getToken(); err != nil {
  290. return
  291. }
  292. args := url.Values{}
  293. args.Add("access_token", wc.AccessToken)
  294. uri += args.Encode()
  295. var msg myth.HTTPMessage
  296. msg, err = postJSON(uri, menu)
  297. if err != nil {
  298. return
  299. }
  300. jq, e := msg.JSONQuery()
  301. if e != nil {
  302. err = e
  303. return
  304. }
  305. code, _ := jq.Int(`errcode`)
  306. errmsg, _ := jq.String(`errmsg`)
  307. if code != ErrReqOk {
  308. err = errors.New(errmsg)
  309. }
  310. return
  311. }
  312. // GetSignPackage JS 签名
  313. //
  314. // uri 当前 URL
  315. // nonceStr 随机字符串
  316. func (wc Client) GetSignPackage(uri, nonceStr string) (sign SignPackage, err error) {
  317. if wc.AccessToken, err = wc.getToken(); err != nil {
  318. return
  319. }
  320. var (
  321. s string
  322. unix int64
  323. )
  324. unix = time.Now().Unix()
  325. if wc.Ticket, err = wc.getTicket(unix); err != nil {
  326. return
  327. }
  328. s = `jsapi_ticket=` + wc.Ticket
  329. s += `&noncestr=` + nonceStr
  330. s += `&timestamp=` + fmt.Sprintf("%d", unix)
  331. s += `&url=` + uri
  332. sign.AppID = wc.AppID
  333. sign.NonceStr = nonceStr
  334. sign.Signature = myth.SHA1(s)
  335. sign.Timestamp = unix
  336. sign.Ticket = wc.Ticket
  337. sign.URL = uri
  338. return
  339. }
  340. // SendTemplateMessage send template message
  341. // POST /cgi-bin/message/template/send?access_token=ACCESS_TOKEN
  342. func (wc Client) SendTemplateMessage(template TemplateMessage) (res TemplateResponse, err error) {
  343. uri := BaseURL + "/cgi-bin/message/template/send?"
  344. if wc.AccessToken, err = wc.getToken(); err != nil {
  345. return
  346. }
  347. args := url.Values{}
  348. args.Add("access_token", wc.AccessToken)
  349. uri += args.Encode()
  350. var msg myth.HTTPMessage
  351. msg, err = postJSON(uri, template)
  352. if err == nil {
  353. err = json.Unmarshal(msg.Body, &res)
  354. }
  355. return
  356. }
  357. // SendTemplatex send template message
  358. // POST /cgi-bin/message/template/send?access_token=ACCESS_TOKEN
  359. func (wc Client) SendTemplatex(data any) (res TemplateResponse, err error) {
  360. uri := BaseURL + "/cgi-bin/message/template/send?"
  361. if wc.AccessToken, err = wc.getToken(); err != nil {
  362. return
  363. }
  364. args := url.Values{}
  365. args.Add("access_token", wc.AccessToken)
  366. uri += args.Encode()
  367. var msg myth.HTTPMessage
  368. msg, err = postJSON(uri, data)
  369. if err == nil {
  370. err = json.Unmarshal(msg.Body, &res)
  371. }
  372. return
  373. }
  374. // TemplateMessageReslut template message reslut
  375. func (wc Client) TemplateMessageReslut(jq *myth.JSONQuery) (code int, id int64, err error) {
  376. code, _ = jq.Int(`errcode`)
  377. errmsg, _ := jq.String(`errmsg`)
  378. id, _ = jq.Int64(`msgid`)
  379. if code != ErrReqOk {
  380. err = errors.New(errmsg)
  381. }
  382. return
  383. }
  384. // SendTemplateMessageX 发送自定义模版消息
  385. func (wc Client) SendTemplateMessageX(data []byte) (res TemplateResponse, err error) {
  386. uri := BaseURL + "/cgi-bin/message/template/send?"
  387. if wc.AccessToken, err = wc.getToken(); err != nil {
  388. return
  389. }
  390. args := url.Values{}
  391. args.Add("access_token", wc.AccessToken)
  392. uri += args.Encode()
  393. var msg myth.HTTPMessage
  394. msg, err = postJSONData(uri, data)
  395. if err == nil {
  396. err = json.Unmarshal(msg.Body, &res)
  397. }
  398. return
  399. }