wechat.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  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_web_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 WxTicket struct {
  23. Errcode int `json:"errcode"`
  24. Errmsg string `json:"errmsg"`
  25. Ticket string `json:"ticket"`
  26. }
  27. type WechatSign struct {
  28. AppId string
  29. NonceStr string
  30. Timestamp int64
  31. Url string
  32. Signature string
  33. RawString string
  34. }
  35. type WxAccessToken struct {
  36. AccessToken string `json:"access_token"`
  37. ExpiresIn int `json:"expires_in"`
  38. RefreshToken string `json:"refresh_token"`
  39. Openid string `json:"openid"`
  40. Unionid string `json:"unionid"`
  41. Scope string `json:"scope"`
  42. Errcode int `json:"errcode"`
  43. Errmsg string `json:"errmsg"`
  44. }
  45. type WxUsers struct {
  46. Total int
  47. Count int
  48. Data struct {
  49. Openid []string
  50. }
  51. NextOpenid string
  52. }
  53. func GetWxAccessToken() (accessTokenStr string, err error) {
  54. o := orm.NewOrmUsingDB("weekly_report")
  55. sql := `SELECT * FROM wx_token LIMIT 1`
  56. wxToken := new(WxToken)
  57. err = o.Raw(sql).QueryRow(&wxToken)
  58. if err != nil && err.Error() != utils.ErrNoRow() {
  59. return
  60. }
  61. //Token不存在
  62. if wxToken == nil {
  63. fmt.Println("wxToken is empty")
  64. accessToken, err := GetWxToken()
  65. if err != nil {
  66. return "", err
  67. }
  68. if accessToken.AccessToken != "" {
  69. expiresIn := time.Now().Add(time.Duration(accessToken.ExpiresIn) * time.Second).Unix()
  70. addSql := "insert into wx_token (access_token,expires_in) values (?,?)"
  71. _, err = o.Raw(addSql, accessToken.AccessToken, expiresIn).Exec()
  72. accessTokenStr = accessToken.AccessToken
  73. }
  74. return accessTokenStr, err
  75. } else {
  76. //判断token是否过期
  77. if time.Now().Unix() > wxToken.ExpiresIn {
  78. accessToken, err := GetWxToken()
  79. fmt.Println(accessToken)
  80. if err != nil {
  81. return "", err
  82. }
  83. if accessToken.AccessToken != "" {
  84. expiresIn := time.Now().Add(time.Duration(accessToken.ExpiresIn) * time.Second).Unix()
  85. updateSql := "update wx_token set access_token = ?,expires_in = ? "
  86. _, err = o.Raw(updateSql, accessToken.AccessToken, expiresIn).Exec()
  87. accessTokenStr = accessToken.AccessToken
  88. fmt.Println("更新 TOKEN:", err)
  89. }
  90. return accessTokenStr, err
  91. } else {
  92. return wxToken.AccessToken, nil
  93. }
  94. }
  95. return
  96. }
  97. func GetWxToken() (item *WxAccessToken, err error) {
  98. getUrl := "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + utils.WxPublicAppId + "&secret=" + utils.WxPublicAppSecret
  99. result, err := http.Get(getUrl)
  100. if err != nil {
  101. return
  102. }
  103. err = json.Unmarshal(result, &item)
  104. if err != nil {
  105. fmt.Println("GetWxToken Unmarshal Err:%s", err.Error())
  106. return
  107. }
  108. if item.Errmsg != "" {
  109. utils.FileLog.Info("GetWxToken fail result:%s", string(result))
  110. err = fmt.Errorf(item.Errmsg)
  111. }
  112. return
  113. }
  114. func GetWxAccessTokenByXzs() (accessTokenStr string, err error) {
  115. if utils.RunMode == "release" {
  116. //缓存校验
  117. cacheKey := "xygxxzs_wxtoken"
  118. accessTokenStr, _ = utils.Rc.RedisString(cacheKey)
  119. if accessTokenStr != "" {
  120. return
  121. } else {
  122. WxAccessToken, errWx := GetWxTokenByXzs()
  123. if errWx != nil {
  124. err = errWx
  125. return
  126. }
  127. accessTokenStr = WxAccessToken.AccessToken
  128. utils.Rc.Put(cacheKey, WxAccessToken.AccessToken, time.Second*7000)
  129. }
  130. } else {
  131. accessTokenStr, err = GetWxAccessToken()
  132. if err != nil {
  133. return
  134. }
  135. }
  136. return
  137. }
  138. // 获取小助手的微信Token
  139. func GetWxTokenByXzs() (item *WxAccessToken, err error) {
  140. getUrl := "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + utils.WxPublicAppId + "&secret=" + utils.WxPublicAppSecret
  141. result, err := http.Get(getUrl)
  142. if err != nil {
  143. return
  144. }
  145. err = json.Unmarshal(result, &item)
  146. if err != nil {
  147. fmt.Println("GetWxToken Unmarshal Err:%s", err.Error())
  148. return
  149. }
  150. if item.Errmsg != "" {
  151. utils.FileLog.Info("GetWxToken fail result:%s", string(result))
  152. err = fmt.Errorf(item.Errmsg)
  153. }
  154. return
  155. }
  156. type WxCheckContentJson struct {
  157. Detail []WxCheckContentJsonDetail `json:"detail"`
  158. Errcode int `json:"errcode"`
  159. Errmsg string `json:"errmsg"`
  160. Result WxCheckContentJsonResult `json:"result"`
  161. }
  162. type WxCheckContentJsonDetail struct {
  163. Label int
  164. KeyWord string
  165. Prob int
  166. Strategy string
  167. Errcode int
  168. }
  169. type WxCheckContentJsonResult struct {
  170. Suggest string
  171. Label int
  172. }
  173. func WxCheckContent(token, openId, content string) (suggest string) {
  174. url := "https://api.weixin.qq.com/wxa/msg_sec_check?access_token=" + token
  175. fmt.Println(url)
  176. //result, err := http.Post(url, content)
  177. //if err != nil {
  178. // utils.FileLog.Info("GetUser Err:", err.Error())
  179. // return
  180. //}
  181. method := "POST"
  182. payload := strings.NewReader(`{
  183. "openid":"` + openId + `",
  184. "scene":` + strconv.Itoa(2) + `,
  185. "version":` + strconv.Itoa(2) + `,
  186. "content":"` + content + `"
  187. }`)
  188. client := &netHttp.Client{}
  189. req, err := netHttp.NewRequest(method, url, payload)
  190. if err != nil {
  191. return
  192. }
  193. req.Header.Add("Content-Type", "application/json")
  194. postBody, err := client.Do(req)
  195. if err != nil {
  196. return
  197. }
  198. defer postBody.Body.Close()
  199. body, err := ioutil.ReadAll(postBody.Body)
  200. if err != nil {
  201. fmt.Println(err)
  202. utils.FileLog.Info(err.Error())
  203. return
  204. }
  205. item := new(WxCheckContentJson)
  206. err = json.Unmarshal(body, &item)
  207. if err != nil {
  208. fmt.Println("Unmarshal Err:", err.Error())
  209. return
  210. }
  211. fmt.Println(item.Result.Label)
  212. fmt.Println(item.Result.Suggest)
  213. suggest = item.Result.Suggest
  214. return
  215. }