client.go 5.6 KB

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