wechat.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. package models
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "github.com/beego/beego/v2/client/orm"
  6. "github.com/rdlucklib/rdluck_tools/http"
  7. "hongze/hongze_mfyx/utils"
  8. "io/ioutil"
  9. netHttp "net/http"
  10. "strconv"
  11. "strings"
  12. "time"
  13. )
  14. type WxLoginReq struct {
  15. Code string `description:"微信code"`
  16. }
  17. type WxToken struct {
  18. AccessToken string
  19. ExpiresIn int64
  20. Id int64
  21. }
  22. type SenceRule struct {
  23. Scene string `json:"scene"`
  24. Page string `json:"page,omitempty"`
  25. Width int `json:"width,omitempty"`
  26. AutoColor bool `json:"auto_color,omitempty"`
  27. LineColor string `json:"line_color,omitempty"`
  28. IsHyaline bool `json:"is_hyaline,omitempty"`
  29. }
  30. // BufferRule 图片buffer
  31. type BufferRule struct {
  32. Buffer []byte `json:"Buffer"`
  33. }
  34. // ReturnBodyRule 微信返回通过结果集
  35. type ReturnBodyRule struct {
  36. ErrorCode int `json:"errcode,omitempty"`
  37. ErrorMessage string `json:"errmsg,omitempty"`
  38. }
  39. func GetWxAccessToken() (accessTokenStr string, err error) {
  40. o := orm.NewOrmUsingDB("weekly_report")
  41. sql := `SELECT * FROM wx_token LIMIT 1`
  42. wxToken := new(WxToken)
  43. err = o.Raw(sql).QueryRow(&wxToken)
  44. if err != nil && err.Error() != utils.ErrNoRow() {
  45. return
  46. }
  47. //Token不存在
  48. if wxToken == nil {
  49. fmt.Println("wxToken is empty")
  50. accessToken, err := GetWxToken()
  51. if err != nil {
  52. return "", err
  53. }
  54. if accessToken.AccessToken != "" {
  55. expiresIn := time.Now().Add(time.Duration(accessToken.ExpiresIn) * time.Second).Unix()
  56. addSql := "insert into wx_token (access_token,expires_in) values (?,?)"
  57. _, err = o.Raw(addSql, accessToken.AccessToken, expiresIn).Exec()
  58. accessTokenStr = accessToken.AccessToken
  59. }
  60. return accessTokenStr, err
  61. } else {
  62. //判断token是否过期
  63. if time.Now().Unix() > wxToken.ExpiresIn {
  64. accessToken, err := GetWxToken()
  65. fmt.Println(accessToken)
  66. if err != nil {
  67. return "", err
  68. }
  69. if accessToken.AccessToken != "" {
  70. expiresIn := time.Now().Add(time.Duration(accessToken.ExpiresIn) * time.Second).Unix()
  71. updateSql := "update wx_token set access_token = ?,expires_in = ? "
  72. _, err = o.Raw(updateSql, accessToken.AccessToken, expiresIn).Exec()
  73. accessTokenStr = accessToken.AccessToken
  74. fmt.Println("更新 TOKEN:", err)
  75. }
  76. return accessTokenStr, err
  77. } else {
  78. return wxToken.AccessToken, nil
  79. }
  80. }
  81. return
  82. }
  83. func GetWxToken() (item *WxAccessToken, err error) {
  84. getUrl := "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + utils.WxPublicAppId + "&secret=" + utils.WxPublicAppSecret
  85. result, err := http.Get(getUrl)
  86. if err != nil {
  87. return
  88. }
  89. err = json.Unmarshal(result, &item)
  90. if err != nil {
  91. fmt.Println("GetWxToken Unmarshal Err:%s", err.Error())
  92. return
  93. }
  94. if item.Errmsg != "" {
  95. utils.FileLog.Info("GetWxToken fail result:%s", string(result))
  96. err = fmt.Errorf(item.Errmsg)
  97. }
  98. return
  99. }
  100. func GetWxAccessTokenByXzs() (accessTokenStr string, err error) {
  101. if utils.RunMode == "release" {
  102. //缓存校验
  103. cacheKey := "xygxxzs_wxtoken"
  104. accessTokenStr, _ = utils.Rc.RedisString(cacheKey)
  105. if accessTokenStr != "" {
  106. return
  107. } else {
  108. WxAccessToken, errWx := GetWxTokenByXzs()
  109. if errWx != nil {
  110. err = errWx
  111. return
  112. }
  113. accessTokenStr = WxAccessToken.AccessToken
  114. utils.Rc.Put(cacheKey, WxAccessToken.AccessToken, time.Second*7000)
  115. }
  116. } else {
  117. accessTokenStr, err = GetWxAccessToken()
  118. if err != nil {
  119. return
  120. }
  121. }
  122. return
  123. }
  124. // 获取小助手的微信Token
  125. func GetWxTokenByXzs() (item *WxAccessToken, err error) {
  126. getUrl := "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + utils.WxPublicIdXzs + "&secret=" + utils.WxPublicSecretXzs
  127. result, err := http.Get(getUrl)
  128. if err != nil {
  129. return
  130. }
  131. err = json.Unmarshal(result, &item)
  132. if err != nil {
  133. fmt.Println("GetWxToken Unmarshal Err:%s", err.Error())
  134. return
  135. }
  136. if item.Errmsg != "" {
  137. utils.FileLog.Info("GetWxToken fail result:%s", string(result))
  138. err = fmt.Errorf(item.Errmsg)
  139. }
  140. return
  141. }
  142. type WxAccessToken struct {
  143. AccessToken string `json:"access_token"`
  144. ExpiresIn int `json:"expires_in"`
  145. RefreshToken string `json:"refresh_token"`
  146. Openid string `json:"openid"`
  147. Unionid string `json:"unionid"`
  148. Scope string `json:"scope"`
  149. Errcode int `json:"errcode"`
  150. Errmsg string `json:"errmsg"`
  151. }
  152. type WxUsers struct {
  153. Total int
  154. Count int
  155. Data struct {
  156. Openid []string
  157. }
  158. NextOpenid string
  159. }
  160. func WxUsersGet() (openIdStr string) {
  161. accessToken, err := GetWxAccessToken()
  162. if err != nil {
  163. utils.FileLog.Info("GetWxAccessToken Err:%s", err.Error())
  164. return
  165. }
  166. url := "https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + accessToken
  167. result, err := http.Get(url)
  168. if err != nil {
  169. utils.FileLog.Info("GetUser Err:", err.Error())
  170. return
  171. }
  172. item := new(WxUsers)
  173. err = json.Unmarshal(result, &item)
  174. if err != nil {
  175. fmt.Println("Unmarshal Err:", err.Error())
  176. return
  177. }
  178. openIdStr = strings.Join(item.Data.Openid, "','")
  179. openIdStr = "'" + openIdStr + "'"
  180. utils.FileLog.Info("openIdStr:%s", openIdStr)
  181. return
  182. }
  183. type WxCheckContentJson struct {
  184. Detail []WxCheckContentJsonDetail `json:"detail"`
  185. Errcode int `json:"errcode"`
  186. Errmsg string `json:"errmsg"`
  187. Result WxCheckContentJsonResult `json:"result"`
  188. }
  189. type WxCheckContentJsonDetail struct {
  190. Label int
  191. KeyWord string
  192. Prob int
  193. Strategy string
  194. Errcode int
  195. }
  196. type WxCheckContentJsonResult struct {
  197. Suggest string
  198. Label int
  199. }
  200. func WxCheckContent(token, openId, content string) (suggest string) {
  201. url := "https://api.weixin.qq.com/wxa/msg_sec_check?access_token=" + token
  202. fmt.Println(url)
  203. //result, err := http.Post(url, content)
  204. //if err != nil {
  205. // utils.FileLog.Info("GetUser Err:", err.Error())
  206. // return
  207. //}
  208. method := "POST"
  209. payload := strings.NewReader(`{
  210. "openid":"` + openId + `",
  211. "scene":` + strconv.Itoa(2) + `,
  212. "version":` + strconv.Itoa(2) + `,
  213. "content":"` + content + `"
  214. }`)
  215. client := &netHttp.Client{}
  216. req, err := netHttp.NewRequest(method, url, payload)
  217. if err != nil {
  218. return
  219. }
  220. req.Header.Add("Content-Type", "application/json")
  221. postBody, err := client.Do(req)
  222. if err != nil {
  223. return
  224. }
  225. defer postBody.Body.Close()
  226. body, err := ioutil.ReadAll(postBody.Body)
  227. if err != nil {
  228. fmt.Println(err)
  229. utils.FileLog.Info(err.Error())
  230. return
  231. }
  232. item := new(WxCheckContentJson)
  233. err = json.Unmarshal(body, &item)
  234. if err != nil {
  235. fmt.Println("Unmarshal Err:", err.Error())
  236. return
  237. }
  238. fmt.Println(item.Result.Label)
  239. fmt.Println(item.Result.Suggest)
  240. suggest = item.Result.Suggest
  241. return
  242. }