wechat.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. package models
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "github.com/beego/beego/v2/client/orm"
  7. "github.com/rdlucklib/rdluck_tools/http"
  8. "hongze/hz_crm_api/utils"
  9. "strings"
  10. "time"
  11. )
  12. type WxToken struct {
  13. AccessToken string
  14. ExpiresIn int64
  15. Id int64
  16. }
  17. func GetWxAccessToken() (accessTokenStr string, err error) {
  18. o := orm.NewOrm()
  19. sql := `SELECT * FROM wx_token LIMIT 1`
  20. wxToken := new(WxToken)
  21. err = o.Raw(sql).QueryRow(&wxToken)
  22. if err != nil && err.Error() != utils.ErrNoRow() {
  23. utils.FileLog.Info("Get wxToken Err:", err.Error())
  24. return
  25. }
  26. //Token不存在
  27. if wxToken == nil {
  28. fmt.Println("wxToken is empty")
  29. accessToken, err := GetWxToken(utils.WxAppId, utils.WxAppSecret)
  30. if err != nil {
  31. return "", err
  32. }
  33. if accessToken.AccessToken != "" {
  34. expiresIn := time.Now().Add(time.Duration(accessToken.ExpiresIn) * time.Second).Unix()
  35. addSql := "insert into wx_token (access_token,expires_in) values (?,?)"
  36. _, err = o.Raw(addSql, accessToken.AccessToken, expiresIn).Exec()
  37. accessTokenStr = accessToken.AccessToken
  38. }
  39. return accessTokenStr, err
  40. } else {
  41. //判断token是否过期
  42. if time.Now().Unix() > wxToken.ExpiresIn {
  43. accessToken, err := GetWxToken(utils.WxAppId, utils.WxAppSecret)
  44. if err != nil {
  45. return "", err
  46. }
  47. if accessToken.AccessToken != "" {
  48. expiresIn := time.Now().Add(time.Duration(accessToken.ExpiresIn) * time.Second).Unix()
  49. updateSql := "update wx_token set access_token = ?,expires_in = ? "
  50. _, err = o.Raw(updateSql, accessToken.AccessToken, expiresIn).Exec()
  51. accessTokenStr = accessToken.AccessToken
  52. fmt.Println("更新 TOKEN:", err)
  53. }
  54. return accessTokenStr, err
  55. } else {
  56. return wxToken.AccessToken, nil
  57. }
  58. }
  59. return
  60. }
  61. type WxAccessToken struct {
  62. AccessToken string `json:"access_token"`
  63. ExpiresIn int `json:"expires_in"`
  64. Errcode int `json:"errcode"`
  65. Errmsg string `json:"errmsg"`
  66. }
  67. func GetWxToken(wxAppId, wxAppSecret string) (item *WxAccessToken, err error) {
  68. getUrl := "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + wxAppId + "&secret=" + wxAppSecret
  69. result, err := http.Get(getUrl)
  70. if err != nil {
  71. utils.FileLog.Info("GetWxToken Err:", err.Error())
  72. return
  73. }
  74. err = json.Unmarshal(result, &item)
  75. if err != nil {
  76. fmt.Println(fmt.Sprintf("GetWxToken Unmarshal Err:%s", err.Error()))
  77. return
  78. }
  79. if item.Errmsg != "" {
  80. utils.FileLog.Info(fmt.Sprintf("GetWxToken fail result:%s", string(result)))
  81. }
  82. return
  83. }
  84. type WxUsers struct {
  85. WxBase
  86. Total int
  87. Count int
  88. Data struct {
  89. Openid []string
  90. }
  91. NextOpenid string `json:"next_openid"`
  92. }
  93. // 微信接口基础返回数据
  94. type WxBase struct {
  95. Errcode int
  96. Errmsg string
  97. }
  98. func WxUsersGet() (openIdStr string) {
  99. accessToken, err := GetWxAccessToken()
  100. if err != nil {
  101. utils.FileLog.Info("GetWxAccessToken Err:%s", err.Error())
  102. return
  103. }
  104. //关注的openid切片
  105. openIdList := make([]string, 0)
  106. //下一个openid
  107. nextOpenid := ""
  108. QUERY_WX:
  109. url := "https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + accessToken + "&next_openid=" + nextOpenid
  110. result, err := http.Get(url)
  111. if err != nil {
  112. utils.FileLog.Info("GetUser Err:", err.Error())
  113. return
  114. }
  115. item := new(WxUsers)
  116. err = json.Unmarshal(result, &item)
  117. if err != nil {
  118. fmt.Println("Unmarshal Err:", err.Error())
  119. return
  120. }
  121. if item.Errcode != 0 {
  122. utils.FileLog.Info("微信接口返回异常 Err:", item.Errmsg)
  123. return
  124. }
  125. err = errors.New(item.Errmsg)
  126. openIdList = append(openIdList, item.Data.Openid...)
  127. //如果数量大于10000条,同时下个openid不为空,那么继续查询
  128. if item.Count >= 10000 && item.NextOpenid != "" {
  129. nextOpenid = item.NextOpenid
  130. goto QUERY_WX
  131. }
  132. openIdStr = strings.Join(openIdList, "','")
  133. openIdStr = "'" + openIdStr + "'"
  134. return
  135. }
  136. func GetWxAccessTokenByXzs() (accessTokenStr string, err error) {
  137. if utils.RunMode == "release" {
  138. cacheKey := "xygxxzs_wxtoken"
  139. accessTokenStr, _ = utils.Rc.RedisString(cacheKey)
  140. if accessTokenStr != "" {
  141. return
  142. } else {
  143. WxAccessToken, errWx := GetWxTokenByXzs()
  144. if errWx != nil {
  145. err = errWx
  146. return
  147. }
  148. accessTokenStr = WxAccessToken.AccessToken
  149. utils.Rc.Put(cacheKey, WxAccessToken.AccessToken, time.Second*7000)
  150. }
  151. } else {
  152. accessTokenStr, err = GetWxAccessToken()
  153. if err != nil {
  154. return
  155. }
  156. }
  157. return
  158. }
  159. // 获取小助手的微信Token
  160. func GetWxTokenByXzs() (item *WxAccessToken, err error) {
  161. getUrl := "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + utils.WxPublicIdXzs + "&secret=" + utils.WxPublicSecretXzs
  162. result, err := http.Get(getUrl)
  163. if err != nil {
  164. return
  165. }
  166. err = json.Unmarshal(result, &item)
  167. if err != nil {
  168. fmt.Println("GetWxToken Unmarshal Err:%s", err.Error())
  169. return
  170. }
  171. if item.Errmsg != "" {
  172. utils.FileLog.Info("GetWxToken fail result:%s", string(result))
  173. err = fmt.Errorf(item.Errmsg)
  174. }
  175. return
  176. }
  177. func WxUsersGetV1() (openIdList []string) {
  178. accessToken, err := GetWxAccessToken()
  179. if err != nil {
  180. utils.FileLog.Info("GetWxAccessToken Err:%s", err.Error())
  181. return nil
  182. }
  183. //关注的openid切片
  184. openIdList = make([]string, 0)
  185. //下一个openid
  186. nextOpenid := ""
  187. QUERY_WX:
  188. url := "https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + accessToken + "&next_openid=" + nextOpenid
  189. result, err := http.Get(url)
  190. if err != nil {
  191. utils.FileLog.Info("GetUser Err:", err.Error())
  192. return
  193. }
  194. item := new(WxUsers)
  195. err = json.Unmarshal(result, &item)
  196. if err != nil {
  197. fmt.Println("Unmarshal Err:", err.Error())
  198. return
  199. }
  200. if item.Errcode != 0 {
  201. utils.FileLog.Info("微信接口返回异常 Err:", item.Errmsg)
  202. return
  203. }
  204. err = errors.New(item.Errmsg)
  205. openIdList = append(openIdList, item.Data.Openid...)
  206. //如果数量大于10000条,同时下个openid不为空,那么继续查询
  207. if item.Count >= 10000 && item.NextOpenid != "" {
  208. nextOpenid = item.NextOpenid
  209. goto QUERY_WX
  210. }
  211. return openIdList
  212. }