client.go 7.3 KB

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