token.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package wx
  2. import (
  3. "github.com/silenceper/wechat/oauth"
  4. "sync"
  5. "time"
  6. )
  7. type tokenTiming struct {
  8. Token *oauth.ResAccessToken
  9. Timing time.Time
  10. }
  11. var tokenMap map[string]*tokenTiming
  12. var mutex sync.Mutex
  13. func init(){
  14. tokenMap = make(map[string]*tokenTiming)
  15. tokenCheckLoop()
  16. }
  17. func addToken(openId string, token *oauth.ResAccessToken) {
  18. mutex.Lock()
  19. defer mutex.Unlock()
  20. if _, exists := tokenMap[openId]; !exists{
  21. tokenMap[openId] = &tokenTiming{
  22. Token: token,
  23. Timing: time.Now(),
  24. }
  25. }
  26. }
  27. func getToken(openId string) *oauth.ResAccessToken{
  28. mutex.Lock()
  29. defer mutex.Unlock()
  30. if t, exists := tokenMap[openId]; !exists{
  31. return nil
  32. }else{
  33. return t.Token
  34. }
  35. }
  36. func removeToken(openId string){
  37. mutex.Lock()
  38. defer mutex.Unlock()
  39. if _, exists := tokenMap[openId]; exists{
  40. delete(tokenMap, openId)
  41. }
  42. }
  43. func tokenCheckLoop(){
  44. go func(){
  45. t:=time.NewTicker(10 * 60 * time.Second)
  46. for {
  47. select {
  48. case <-t.C:
  49. mutex.Lock()
  50. ks := make([]string, 0)
  51. for k, v := range tokenMap{
  52. if time.Now().Sub(v.Timing) > 90 * time.Minute{
  53. ks = append(ks, k)
  54. }
  55. }
  56. for i := range ks{
  57. //t, err := wxoauth.RefreshAccessToken(tokenMap[ks[i]].Token.RefreshToken)
  58. //if err != nil{
  59. // delete(tokenMap, ks[i])
  60. // continue
  61. //}else{
  62. // tokenMap[ks[i]] = t
  63. //}
  64. // 暂时删除不刷新
  65. delete(tokenMap, ks[i])
  66. }
  67. mutex.Unlock()
  68. }
  69. }
  70. }()
  71. }