wechat.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package models
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "hongze/hongze_public_api/utils"
  6. "github.com/beego/beego/v2/client/orm"
  7. "github.com/rdlucklib/rdluck_tools/http"
  8. )
  9. type WxToken struct {
  10. AccessToken string
  11. ExpiresIn int64
  12. Id int64
  13. }
  14. type WxAccessToken struct {
  15. AccessToken string `json:"access_token"`
  16. ExpiresIn int `json:"expires_in"`
  17. Errcode int `json:"errcode"`
  18. Errmsg string `json:"errmsg"`
  19. }
  20. func GetWxToken(wxAppId,wxAppSecret string) (item *WxAccessToken, err error) {
  21. getUrl := "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + wxAppId + "&secret=" + wxAppSecret
  22. result, err := http.Get(getUrl)
  23. if err != nil {
  24. utils.FileLog.Info("GetWxToken Err:", err.Error())
  25. return
  26. }
  27. utils.FileLog.Info(fmt.Sprintf("GetWxAccessToken :%s", string(result)))
  28. err = json.Unmarshal(result, &item)
  29. if err != nil {
  30. fmt.Println(fmt.Sprintf("GetWxToken Unmarshal Err:%s", err.Error()))
  31. return
  32. }
  33. if item.Errmsg != "" {
  34. utils.FileLog.Info(fmt.Sprintf("GetWxToken fail result:%s", string(result)))
  35. }
  36. return
  37. }
  38. // ModifyAccessToken 修改wx_access_token
  39. func ModifyAccessToken(accessToken string,expiresIn int64)(err error){
  40. o := orm.NewOrm()
  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. utils.FileLog.Info("Get wxToken Err:", err.Error())
  46. return
  47. }
  48. if wxToken == nil {
  49. fmt.Println("wxToken is empty")
  50. addSql := "insert into wx_token (access_token,expires_in) values (?,?)"
  51. _, err = o.Raw(addSql, accessToken, expiresIn).Exec()
  52. } else {
  53. //判断token是否过期
  54. updateSql := "update wx_token set access_token = ?,expires_in = ? "
  55. _, err = o.Raw(updateSql, accessToken, expiresIn).Exec()
  56. fmt.Println("更新 TOKEN:", err)
  57. }
  58. return
  59. }