client.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  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=snsapi_base&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. // GetUserInfoCodeURL get code 授权获取 OpenID URL
  119. // /connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
  120. // 转向到
  121. // redirect_uri/?code=CODE&state=STATE
  122. func (wc Client) GetUserInfoCodeURL(redirectURL, state string) (uri string) {
  123. uri = OpenURL + "/connect/oauth2/authorize?"
  124. args := url.Values{}
  125. args.Add("appid", wc.AppID)
  126. args.Add("redirect_uri", redirectURL)
  127. args.Add("response_type", "code")
  128. args.Add("scope", "snsapi_userinfo")
  129. args.Add("state", state)
  130. uri += args.Encode()
  131. uri += "#wechat_redirect"
  132. return
  133. }
  134. // GetOpenID 获取 OpenID
  135. // /sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
  136. func (wc Client) GetOpenID(code string) (jq *myth.JSONQuery, err error) {
  137. uri := BaseURL + "/sns/oauth2/access_token?"
  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("appid", wc.AppID)
  144. args.Add("secret", wc.AppSecret)
  145. args.Add("code", code)
  146. args.Add("grant_type", "authorization_code")
  147. uri += args.Encode()
  148. jq, err = getJSON(uri)
  149. return
  150. }
  151. // GetUserInfo user info
  152. func (wc Client) GetUserInfo(openid string) (info UserInfo, err error) {
  153. uri := BaseURL + "/cgi-bin/user/info?"
  154. if wc.AccessToken, err = wc.getToken(); err != nil {
  155. return
  156. }
  157. args := url.Values{}
  158. args.Add("access_token", wc.AccessToken)
  159. args.Add("openid", openid)
  160. args.Add("lang", "zh_CN")
  161. uri += args.Encode()
  162. var msg myth.HTTPMessage
  163. msg, err = getBody(uri)
  164. if err == nil {
  165. err = msg.JSON(&info)
  166. }
  167. return
  168. }
  169. // GetUserList user list
  170. func (wc Client) GetUserList(nextOpenID string) (list UserList, err error) {
  171. uri := BaseURL + "/cgi-bin/user/get?"
  172. if wc.AccessToken, err = wc.getToken(); err != nil {
  173. return
  174. }
  175. args := url.Values{}
  176. args.Add("access_token", wc.AccessToken)
  177. args.Add("next_openid", nextOpenID)
  178. uri += args.Encode()
  179. var msg myth.HTTPMessage
  180. msg, err = getBody(uri)
  181. if err == nil {
  182. err = msg.JSON(&list)
  183. }
  184. return
  185. }
  186. // GetMaterial 永久资料
  187. func (wc Client) GetMaterial(mtype string, offset, count int) (material Material, err error) {
  188. uri := BaseURL + "/cgi-bin/material/batchget_material?"
  189. if wc.AccessToken, err = wc.getToken(); err != nil {
  190. return
  191. }
  192. args := url.Values{}
  193. data := make(map[string]interface{})
  194. args.Add("access_token", wc.AccessToken)
  195. data["type"] = mtype
  196. data["offset"] = offset
  197. data["count"] = count
  198. uri += args.Encode()
  199. var msg myth.HTTPMessage
  200. msg, err = postJSON(uri, data)
  201. if err == nil {
  202. err = msg.JSON(&material)
  203. }
  204. return
  205. }
  206. // GetMenu 查询自定义菜单
  207. func (wc Client) GetMenu() (menu Menu, err error) {
  208. uri := BaseURL + "/cgi-bin/get_current_selfmenu_info?"
  209. if wc.AccessToken, err = wc.getToken(); err != nil {
  210. return
  211. }
  212. args := url.Values{}
  213. data := make(map[string]interface{})
  214. args.Add("access_token", wc.AccessToken)
  215. uri += args.Encode()
  216. var msg myth.HTTPMessage
  217. msg, err = postJSON(uri, data)
  218. if err == nil {
  219. err = msg.JSON(&menu)
  220. }
  221. return
  222. }
  223. // CreateMenu 创建自定义菜单
  224. func (wc Client) CreateMenu(menu FormMenu) (err error) {
  225. uri := BaseURL + "/cgi-bin/menu/create?"
  226. if wc.AccessToken, err = wc.getToken(); err != nil {
  227. return
  228. }
  229. args := url.Values{}
  230. args.Add("access_token", wc.AccessToken)
  231. uri += args.Encode()
  232. var msg myth.HTTPMessage
  233. msg, err = postJSON(uri, menu)
  234. if err != nil {
  235. return
  236. }
  237. jq, e := msg.JSONQuery()
  238. if e != nil {
  239. err = e
  240. return
  241. }
  242. code, _ := jq.Int(`errcode`)
  243. errmsg, _ := jq.String(`errmsg`)
  244. if code != ErrReqOk {
  245. err = errors.New(errmsg)
  246. }
  247. return
  248. }
  249. // GetSignPackage JS 签名
  250. // uri 当前 URL
  251. // nonceStr 随机字符串
  252. func (wc Client) GetSignPackage(uri, nonceStr string) (sign SignPackage, err error) {
  253. if wc.AccessToken, err = wc.getToken(); err != nil {
  254. return
  255. }
  256. var (
  257. s string
  258. unix int64
  259. )
  260. unix = time.Now().Unix()
  261. if wc.Ticket, err = wc.getTicket(unix); err != nil {
  262. return
  263. }
  264. s = `jsapi_ticket=` + wc.Ticket
  265. s += `&noncestr=` + nonceStr
  266. s += `&timestamp=` + fmt.Sprintf("%d", unix)
  267. s += `&url=` + uri
  268. sign.AppID = wc.AppID
  269. sign.NonceStr = nonceStr
  270. sign.Signature = myth.SHA1(s)
  271. sign.Timestamp = unix
  272. sign.Ticket = wc.Ticket
  273. sign.URL = uri
  274. return
  275. }
  276. // SendTemplateMessage send template message
  277. // POST /cgi-bin/message/template/send?access_token=ACCESS_TOKEN
  278. func (wc Client) SendTemplateMessage(template TemplateMessage) (res TemplateResponse, err error) {
  279. uri := BaseURL + "/cgi-bin/message/template/send?"
  280. if wc.AccessToken, err = wc.getToken(); err != nil {
  281. return
  282. }
  283. args := url.Values{}
  284. args.Add("access_token", wc.AccessToken)
  285. uri += args.Encode()
  286. var msg myth.HTTPMessage
  287. msg, err = postJSON(uri, template)
  288. if err == nil {
  289. err = json.Unmarshal(msg.Body, &res)
  290. }
  291. return
  292. }
  293. // TemplateMessageReslut template message reslut
  294. func (wc Client) TemplateMessageReslut(jq *myth.JSONQuery) (code int, id int64, err error) {
  295. code, _ = jq.Int(`errcode`)
  296. errmsg, _ := jq.String(`errmsg`)
  297. id, _ = jq.Int64(`msgid`)
  298. if code != ErrReqOk {
  299. err = errors.New(errmsg)
  300. }
  301. return
  302. }