client.go 6.9 KB

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