client.go 5.7 KB

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