client.go 5.7 KB

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