mini.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. package wechat
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "net/url"
  6. "time"
  7. "git.chuangxin1.com/cx/myth"
  8. "git.chuangxin1.com/cx/myth/cache"
  9. )
  10. func keyMini(appid string) string {
  11. return "wechat:mini:client:" + appid
  12. }
  13. func keyMiniToken(appid string) string {
  14. return "wechat:mini:client:token:" + appid
  15. }
  16. // NewMiniClient new mini client
  17. func NewMiniClient(appID, appSecret string) *MiniClient {
  18. key := keyMini(appID)
  19. if v, ok := memcache.Load(key); ok {
  20. return v.(*MiniClient)
  21. }
  22. c := &MiniClient{AppID: appID, AppSecret: appSecret}
  23. memcache.Store(key, c)
  24. return c
  25. }
  26. // GetMiniOpenID get openid by code
  27. func (mc *MiniClient) GetMiniOpenID(frm FormCode) (s MiniSession, err error) {
  28. uri := BaseURL + "/sns/jscode2session?"
  29. args := url.Values{}
  30. args.Add("grant_type", "authorization_code")
  31. args.Add("appid", mc.AppID)
  32. args.Add("secret", mc.AppSecret)
  33. args.Add("js_code", frm.Code)
  34. uri += args.Encode()
  35. var jq *myth.JSONQuery
  36. if jq, err = getJSON(uri); err == nil {
  37. s.OpenID, err = jq.String(`openid`)
  38. s.SessionKey, _ = jq.String(`session_key`)
  39. s.UnionID, _ = jq.String(`unionid`)
  40. }
  41. return
  42. }
  43. // getToken get token
  44. func (mc *MiniClient) getToken() (token string, err error) {
  45. /*
  46. now := time.Now().Unix()
  47. if mc.LastTokenTime > 0 {
  48. if now-mc.LastTokenTime < TokenExpires {
  49. token = mc.AccessToken
  50. return
  51. }
  52. }
  53. // */
  54. key := keyMiniToken(mc.AppID)
  55. var ct ClientToken
  56. s := ``
  57. now := time.Now().Unix()
  58. s, err = cache.Get(key)
  59. if err == nil {
  60. err = json.Unmarshal([]byte(s), &ct)
  61. if err != nil {
  62. return
  63. }
  64. if mc.LastTokenTime > 0 {
  65. if now-mc.LastTokenTime < TokenExpires {
  66. token = mc.AccessToken
  67. return
  68. }
  69. }
  70. }
  71. uri := BaseURL + "/cgi-bin/token?"
  72. args := url.Values{}
  73. args.Add("grant_type", "client_credential")
  74. args.Add("appid", mc.AppID)
  75. args.Add("secret", mc.AppSecret)
  76. uri += args.Encode()
  77. var jq *myth.JSONQuery
  78. if jq, err = getJSON(uri); err == nil {
  79. mc.LastTokenTime = now
  80. mc.AccessToken, err = jq.String(`access_token`)
  81. token = mc.AccessToken
  82. k := keyMini(mc.AppID)
  83. memcache.Store(k, mc)
  84. ct := ClientToken{AppID: mc.AppID, AccessToken: mc.AccessToken, LastTokenTime: now}
  85. bs, _ := json.Marshal(ct)
  86. cache.Set(key, string(bs), 0)
  87. }
  88. return
  89. }
  90. // TemplateList /cgi-bin/wxopen/template/list
  91. func (mc *MiniClient) TemplateList(offset, count int) (body []byte, err error) {
  92. uri := BaseURL + "/cgi-bin/wxopen/template/list?"
  93. if mc.AccessToken, err = mc.getToken(); err != nil {
  94. return
  95. }
  96. args := url.Values{}
  97. args.Add("access_token", mc.AccessToken)
  98. uri += args.Encode()
  99. params := make(map[string]interface{})
  100. params["offset"] = offset
  101. params["count"] = count
  102. var msg myth.HTTPMessage
  103. msg, err = postJSON(uri, params)
  104. if err == nil {
  105. body = msg.Body
  106. }
  107. /*
  108. data, err := json.Marshal(params)
  109. if err != nil {
  110. return
  111. }
  112. body, err = postJSONBody(uri, data)
  113. // */
  114. return
  115. }
  116. // MiniPhoneInfo 手机信息
  117. type MiniPhoneInfo struct {
  118. ResponseMsg
  119. PhoneInfo struct {
  120. PhoneNumber string `json:"phoneNumber"`
  121. PurePhoneNumber string `json:"purePhoneNumber"`
  122. CountryCode string `json:"countryCode"`
  123. Watermark struct {
  124. Timestamp int64 `json:"timestamp"`
  125. AppID string `json:"appid"`
  126. } `json:"watermark"`
  127. } `json:"phone_info"`
  128. }
  129. // GetPhoneInfo 获取手机信息 /wxa/business/getuserphonenumber
  130. func (mc *MiniClient) GetPhoneInfo(frm FormCode) (res MiniPhoneInfo, err error) {
  131. uri := BaseURL + "/wxa/business/getuserphonenumber?"
  132. if mc.AccessToken, err = mc.getToken(); err != nil {
  133. return
  134. }
  135. args := url.Values{}
  136. args.Add("access_token", mc.AccessToken)
  137. uri += args.Encode()
  138. var msg myth.HTTPMessage
  139. msg, err = postJSON(uri, frm)
  140. if err != nil {
  141. return
  142. }
  143. err = msg.JSON(&res)
  144. if err != nil {
  145. return
  146. }
  147. if res.ErrCode != 0 {
  148. err = errors.New(res.ErrMsg)
  149. }
  150. return
  151. }
  152. // TemplateSend /cgi-bin/message/wxopen/template/send
  153. func (mc *MiniClient) TemplateSend(template MiniTemplateMessage) (jq *myth.JSONQuery, err error) {
  154. uri := BaseURL + "/cgi-bin/message/wxopen/template/send?"
  155. if mc.AccessToken, err = mc.getToken(); err != nil {
  156. return
  157. }
  158. args := url.Values{}
  159. args.Add("access_token", mc.AccessToken)
  160. uri += args.Encode()
  161. var msg myth.HTTPMessage
  162. msg, err = postJSON(uri, template)
  163. if err == nil {
  164. jq, err = msg.JSONQuery()
  165. }
  166. return
  167. }
  168. // UniformSend /cgi-bin/message/wxopen/template/uniform_send
  169. func (mc *MiniClient) UniformSend(template MiniUniformMessage) (jq *myth.JSONQuery, err error) {
  170. uri := BaseURL + "/cgi-bin/message/wxopen/template/uniform_send?"
  171. if mc.AccessToken, err = mc.getToken(); err != nil {
  172. return
  173. }
  174. args := url.Values{}
  175. args.Add("access_token", mc.AccessToken)
  176. uri += args.Encode()
  177. var msg myth.HTTPMessage
  178. msg, err = postJSON(uri, template)
  179. if err == nil {
  180. jq, err = msg.JSONQuery()
  181. }
  182. return
  183. }