client.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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. // NewClient new client
  18. func NewClient(appID, appSecret, token, encodingAESKey string) *Client {
  19. key := keyC(appID)
  20. if v, ok := memcache.Load(key); ok {
  21. return v.(*Client)
  22. }
  23. c := &Client{AppID: appID, AppSecret: appSecret, Token: token, EncodingAESKey: encodingAESKey}
  24. memcache.Store(key, c)
  25. return c
  26. }
  27. // getToken get token
  28. func (wc *Client) getToken() (token string, err error) {
  29. key := keyToken(wc.AppID)
  30. if wc.UseCacheToken {
  31. var ct ClientToken
  32. s := ``
  33. s, err = cache.Get(key)
  34. if err != nil {
  35. return
  36. }
  37. err = json.Unmarshal([]byte(s), &ct)
  38. if err != nil {
  39. return
  40. }
  41. token = ct.AccessToken
  42. return
  43. }
  44. //wc.ReadLock.Lock()
  45. //defer wc.ReadLock.Unlock()
  46. now := time.Now().Unix()
  47. if wc.LastTokenTime > 0 {
  48. if now-wc.LastTokenTime < TokenExpires {
  49. token = wc.AccessToken
  50. return
  51. }
  52. }
  53. uri := BaseURL + "/cgi-bin/token?"
  54. args := url.Values{}
  55. args.Add("grant_type", "client_credential")
  56. args.Add("appid", wc.AppID)
  57. args.Add("secret", wc.AppSecret)
  58. uri += args.Encode()
  59. var jq *myth.JSONQuery
  60. if jq, err = getJSON(uri); err == nil {
  61. wc.LastTokenTime = now
  62. var accessToken string
  63. accessToken, err = jq.String(`access_token`)
  64. wc.AccessToken = accessToken
  65. token = wc.AccessToken
  66. key1 := keyC(wc.AppID)
  67. memcache.Store(key1, wc)
  68. ct := ClientToken{AppID: wc.AppID, AccessToken: wc.AccessToken, LastTokenTime: now}
  69. bs, _ := json.Marshal(ct)
  70. cache.Set(key, string(bs), 0)
  71. //cache.Store(key, accessToken)
  72. }
  73. return
  74. }
  75. func (wc *Client) getTicket(now int64) (ticket string, err error) {
  76. var jq *myth.JSONQuery
  77. if wc.LastTicketTime > 0 {
  78. if now-wc.LastTicketTime < TicketExpires {
  79. ticket = wc.Ticket
  80. return
  81. }
  82. }
  83. args := url.Values{}
  84. args.Add("access_token", wc.AccessToken)
  85. args.Add("type", "jsapi")
  86. uri := BaseURL + "/cgi-bin/ticket/getticket?"
  87. uri += args.Encode()
  88. if jq, err = getJSON(uri); err == nil {
  89. ticket, err = jq.String(`ticket`)
  90. wc.LastTicketTime = now
  91. wc.Ticket = ticket
  92. key := keyC(wc.AppID)
  93. memcache.Store(key, wc)
  94. }
  95. return
  96. }
  97. // TokenUseCache token from cache
  98. func (wc *Client) TokenUseCache(ok bool) {
  99. wc.UseCacheToken = ok
  100. wc.TokenFromCache = ok
  101. }
  102. // GetCodeURL get code 授权获取 OpenID URL
  103. // /connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect
  104. // 转向到
  105. // redirect_uri/?code=CODE&state=STATE
  106. func (wc Client) GetCodeURL(redirectURL, state string) (uri string) {
  107. uri = OpenURL + "/connect/oauth2/authorize?"
  108. args := url.Values{}
  109. args.Add("appid", wc.AppID)
  110. args.Add("redirect_uri", redirectURL)
  111. args.Add("response_type", "code")
  112. args.Add("scope", "snsapi_base")
  113. args.Add("state", state)
  114. uri += args.Encode()
  115. uri += "#wechat_redirect"
  116. return
  117. }
  118. // GetOpenID 获取 OpenID
  119. // /sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
  120. func (wc Client) GetOpenID(code string) (jq *myth.JSONQuery, err error) {
  121. uri := BaseURL + "/sns/oauth2/access_token?"
  122. if wc.AccessToken, err = wc.getToken(); err != nil {
  123. return
  124. }
  125. args := url.Values{}
  126. args.Add("access_token", wc.AccessToken)
  127. args.Add("appid", wc.AppID)
  128. args.Add("secret", wc.AppSecret)
  129. args.Add("code", code)
  130. args.Add("grant_type", "authorization_code")
  131. uri += args.Encode()
  132. jq, err = getJSON(uri)
  133. return
  134. }
  135. // GetUserInfo user info
  136. func (wc Client) GetUserInfo(openid string) (info UserInfo, err error) {
  137. uri := BaseURL + "/cgi-bin/user/info?"
  138. if wc.AccessToken, err = wc.getToken(); err != nil {
  139. return
  140. }
  141. args := url.Values{}
  142. args.Add("access_token", wc.AccessToken)
  143. args.Add("openid", openid)
  144. args.Add("lang", "zh_CN")
  145. uri += args.Encode()
  146. var msg myth.HTTPMessage
  147. msg, err = getBody(uri)
  148. if err == nil {
  149. err = msg.JSON(&info)
  150. }
  151. return
  152. }
  153. // GetUserList user list
  154. func (wc Client) GetUserList(nextOpenID string) (list UserList, err error) {
  155. uri := BaseURL + "/cgi-bin/user/get?"
  156. if wc.AccessToken, err = wc.getToken(); err != nil {
  157. return
  158. }
  159. args := url.Values{}
  160. args.Add("access_token", wc.AccessToken)
  161. args.Add("next_openid", nextOpenID)
  162. uri += args.Encode()
  163. var msg myth.HTTPMessage
  164. msg, err = getBody(uri)
  165. if err == nil {
  166. err = msg.JSON(&list)
  167. }
  168. return
  169. }
  170. // GetMaterial 永久资料
  171. func (wc Client) GetMaterial(mtype string, offset, count int) (material Material, err error) {
  172. uri := BaseURL + "/cgi-bin/material/batchget_material?"
  173. if wc.AccessToken, err = wc.getToken(); err != nil {
  174. return
  175. }
  176. args := url.Values{}
  177. data := make(map[string]interface{})
  178. args.Add("access_token", wc.AccessToken)
  179. data["type"] = mtype
  180. data["offset"] = offset
  181. data["count"] = count
  182. uri += args.Encode()
  183. var msg myth.HTTPMessage
  184. msg, err = postJSON(uri, data)
  185. if err == nil {
  186. err = msg.JSON(&material)
  187. }
  188. return
  189. }
  190. // GetMenu 查询自定义菜单
  191. func (wc Client) GetMenu() (menu Menu, err error) {
  192. uri := BaseURL + "/cgi-bin/get_current_selfmenu_info?"
  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. uri += args.Encode()
  200. var msg myth.HTTPMessage
  201. msg, err = postJSON(uri, data)
  202. if err == nil {
  203. err = msg.JSON(&menu)
  204. }
  205. return
  206. }
  207. // CreateMenu 创建自定义菜单
  208. func (wc Client) CreateMenu(menu FormMenu) (err error) {
  209. uri := BaseURL + "/cgi-bin/menu/create?"
  210. if wc.AccessToken, err = wc.getToken(); err != nil {
  211. return
  212. }
  213. args := url.Values{}
  214. args.Add("access_token", wc.AccessToken)
  215. uri += args.Encode()
  216. var msg myth.HTTPMessage
  217. msg, err = postJSON(uri, menu)
  218. if err != nil {
  219. return
  220. }
  221. jq, e := msg.JSONQuery()
  222. if e != nil {
  223. err = e
  224. return
  225. }
  226. code, _ := jq.Int(`errcode`)
  227. errmsg, _ := jq.String(`errmsg`)
  228. if code != ErrReqOk {
  229. err = errors.New(errmsg)
  230. }
  231. return
  232. }
  233. // GetSignPackage JS 签名
  234. // uri 当前 URL
  235. // nonceStr 随机字符串
  236. func (wc Client) GetSignPackage(uri, nonceStr string) (sign SignPackage, err error) {
  237. if wc.AccessToken, err = wc.getToken(); err != nil {
  238. return
  239. }
  240. var (
  241. s string
  242. unix int64
  243. )
  244. unix = time.Now().Unix()
  245. if wc.Ticket, err = wc.getTicket(unix); err != nil {
  246. return
  247. }
  248. s = `jsapi_ticket=` + wc.Ticket
  249. s += `&noncestr=` + nonceStr
  250. s += `&timestamp=` + fmt.Sprintf("%d", unix)
  251. s += `&url=` + uri
  252. sign.AppID = wc.AppID
  253. sign.NonceStr = nonceStr
  254. sign.Signature = myth.SHA1(s)
  255. sign.Timestamp = unix
  256. sign.Ticket = wc.Ticket
  257. sign.URL = uri
  258. return
  259. }
  260. // SendTemplateMessage send template message
  261. // POST /cgi-bin/message/template/send?access_token=ACCESS_TOKEN
  262. func (wc Client) SendTemplateMessage(template TemplateMessage) (res TemplateResponse, err error) {
  263. uri := BaseURL + "/cgi-bin/message/template/send?"
  264. if wc.AccessToken, err = wc.getToken(); err != nil {
  265. return
  266. }
  267. args := url.Values{}
  268. args.Add("access_token", wc.AccessToken)
  269. uri += args.Encode()
  270. var msg myth.HTTPMessage
  271. msg, err = postJSON(uri, template)
  272. if err == nil {
  273. err = json.Unmarshal(msg.Body, &res)
  274. }
  275. return
  276. }
  277. // TemplateMessageReslut template message reslut
  278. func (wc Client) TemplateMessageReslut(jq *myth.JSONQuery) (code int, id int64, err error) {
  279. code, _ = jq.Int(`errcode`)
  280. errmsg, _ := jq.String(`errmsg`)
  281. id, _ = jq.Int64(`msgid`)
  282. if code != ErrReqOk {
  283. err = errors.New(errmsg)
  284. }
  285. return
  286. }