WxAccess.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package Server
  2. import (
  3. "Wx_MP/conf"
  4. "Wx_MP/logs"
  5. "encoding/json"
  6. "fmt"
  7. _ "github.com/astaxie/beego/cache/redis"
  8. "io/ioutil"
  9. "net/http"
  10. "runtime"
  11. )
  12. type token struct {
  13. AccessToken string `json:"access_token"`
  14. ExpiresIn int `json:"expires_in"`
  15. }
  16. type sentence struct {
  17. Content string `json:"content"`
  18. Note string `json:"note"`
  19. Translation string `json:"translation"`
  20. }
  21. var redisCache_WxServer string
  22. //
  23. //func init() {
  24. //
  25. // logs.Println("============= Redis redisCache_WxServer =============")
  26. //
  27. // config := fmt.Sprintf(`{"key":"%s","conn":"%s","dbNum":"%s","password":"%s"}`,
  28. // "redis_WxServer", conf.Redis_address, conf.Redis_dbNum, conf.Redis_password)
  29. // logs.Println(config)
  30. // var err error
  31. // redisCache_WxServer, err = cache.NewCache("redis", config)
  32. // if err != nil || redisCache_WxServer == nil {
  33. // errMsg := "failed to init redis"
  34. // logs.Println(errMsg, err)
  35. // panic(err)
  36. // }
  37. //
  38. // logs.Println("============= init WxServer =============")
  39. //
  40. // //logs.Println("WxTokey:", getaccesstoken())
  41. //
  42. //}
  43. // 获取微信accesstoken
  44. func GetAccessToken(is bool) string {
  45. if runtime.GOOS == "windows" {
  46. return ""
  47. }
  48. if !is {
  49. if len(redisCache_WxServer) > 0 {
  50. return redisCache_WxServer
  51. }
  52. }
  53. url := fmt.Sprintf("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%v&secret=%v", conf.WX_appid, conf.WX_secret)
  54. resp, err := http.Get(url)
  55. logs.Println("获取微信token:", resp)
  56. fmt.Println("获取微信token:", resp)
  57. if err != nil {
  58. logs.Println("获取微信token失败", err)
  59. return ""
  60. }
  61. defer resp.Body.Close()
  62. body, err := ioutil.ReadAll(resp.Body)
  63. logs.Println("获取微信tokenBody:", body)
  64. fmt.Println("获取微信tokenBody:", body)
  65. if err != nil {
  66. logs.Println("微信token读取失败", err)
  67. return ""
  68. }
  69. token := token{}
  70. err = json.Unmarshal(body, &token)
  71. if err != nil {
  72. logs.Println("微信token解析json失败", err)
  73. return ""
  74. }
  75. logs.Println("token:", token)
  76. fmt.Println("token:", token)
  77. redisCache_WxServer = token.AccessToken
  78. return token.AccessToken
  79. }