client.go 5.3 KB

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