client.go 7.3 KB

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