scrm-go

open_wechat_job.go 5.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. package jobcron
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "time"
  6. "github.com/silenceper/wechat/util"
  7. "SCRM/service"
  8. "SCRM/service/wechat_service"
  9. "SCRM/utils"
  10. "github.com/astaxie/beego"
  11. "github.com/robfig/cron"
  12. )
  13. var openWechatCron *cron.Cron
  14. func init() {
  15. openWechatCron = cron.New()
  16. openWechatCron.AddFunc("@every 1h30m", func() {
  17. go func() {
  18. RequestComponentAccessToken()
  19. }()
  20. })
  21. openWechatCron.AddFunc("@every 1h30m", func() {
  22. go func() {
  23. RequestMpWechatAccessToken()
  24. }()
  25. })
  26. }
  27. func StartOpenWechatCron() {
  28. openWechatCron.Start()
  29. }
  30. var (
  31. token = beego.AppConfig.String("openwechattoken")
  32. appID = beego.AppConfig.String("openwechatappid")
  33. encodingAESKey = beego.AppConfig.String("openwechatencodingaeskey")
  34. appSecret = beego.AppConfig.String("openwechatsecret")
  35. )
  36. type ReqComponentAccessStruct struct {
  37. ComponentAppid string `json:"component_appid"`
  38. ComponentAppSecret string `json:"component_appsecret"`
  39. ComponentVerifyTicket string `json:"component_verify_ticket"`
  40. }
  41. //请求第三方平台的accessToken
  42. func RequestComponentAccessToken() {
  43. utils.InfoLog("Request ComponentAccessToken Start...")
  44. redisClient := service.RedisClient()
  45. defer redisClient.Close()
  46. componentVerifyTicket, err := redisClient.Get("sgj_patient:ComponentVerifyTicket").Result()
  47. if err != nil {
  48. utils.ErrorLog("读取ComponentVerifyTicket失败:%s", err)
  49. return
  50. }
  51. //假设 拿到了 component_verify_ticket ,开始通过接口 拿 component_access_token
  52. //获取第三方平台component_access_token,POST数据
  53. var ReqComponentAccess ReqComponentAccessStruct
  54. ReqComponentAccess.ComponentAppid = appID
  55. ReqComponentAccess.ComponentAppSecret = appSecret
  56. ReqComponentAccess.ComponentVerifyTicket = componentVerifyTicket
  57. fmt.Println(ReqComponentAccess)
  58. //创建请求
  59. uri := fmt.Sprintf("%s", "https://api.weixin.qq.com/cgi-bin/component/api_component_token")
  60. var responseBytes []byte
  61. responseBytes, err = util.PostJSON(uri, ReqComponentAccess)
  62. if err != nil {
  63. utils.ErrorLog("创建请求失败:%s", err)
  64. return
  65. }
  66. var res wechat_service.MPResult
  67. err = json.Unmarshal(responseBytes, &res)
  68. if err != nil {
  69. utils.ErrorLog("MPResult error:%s", err)
  70. return
  71. }
  72. if res.ErrCode > 0 {
  73. fmt.Println(res.ErrMsg)
  74. return
  75. }
  76. //body 是上面请求返回的json数据
  77. //{"component_access_token":"61W3mEpU66027wgNZ_MhGHNQDHnFATkDa9-2llqrMBjUwxRSNPbVsMmyD-yq8wZETSoE5NQgecigDrSHkPtIYA", "expires_in":7200}
  78. var access_token wechat_service.ComponentAccessToken
  79. // 将body的json解析成 access_token ComponentAccessToken
  80. err = json.Unmarshal(responseBytes, &access_token)
  81. if err != nil {
  82. utils.ErrorLog("Unmarshal json error:%s", err)
  83. return
  84. }
  85. err = redisClient.Set("sgj_patient:component_access_token", access_token.ComponentAccessToken, time.Second*7000).Err()
  86. fmt.Println("err错误是哦",err)
  87. if err != nil {
  88. utils.ErrorLog("redis set failed:%s", err)
  89. return
  90. }
  91. componentID, err := beego.AppConfig.Int64("openwechatcomponentid")
  92. if err != nil {
  93. utils.ErrorLog("get component id failed: %s", err)
  94. return
  95. }
  96. info := make(map[string]interface{}, 0)
  97. info["ComponentAccessToken"] = access_token.ComponentAccessToken
  98. info["UpdatedTime"] = time.Now().Unix()
  99. info["ComponentStatus"] = 1
  100. err = wechat_service.SaveWechatComponentInfoByMap(componentID, info)
  101. utils.InfoLog("Request ComponentAccessToken Finish.")
  102. }
  103. type ReqRefreshTokenStruct struct {
  104. ComponentAppid string `json:"component_appid"`
  105. AuthorizerAppid string `json:"authorizer_appid"`
  106. AuthorizerRefreshToken string `json:"authorizer_refresh_token"`
  107. }
  108. func RequestMpWechatAccessToken() {
  109. utils.InfoLog("Request MpWechatAccessToken start...")
  110. mps, err := wechat_service.GetAuthorizations()
  111. if err != nil {
  112. utils.ErrorLog("get mps error: %s", err)
  113. return
  114. }
  115. redisClient := service.RedisClient()
  116. defer redisClient.Close()
  117. componentAccessToken, err := redisClient.Get("sgj_patient:component_access_token").Result()
  118. if err != nil {
  119. utils.ErrorLog("get component_access_token error: %s", err)
  120. return
  121. }
  122. for _, item := range mps {
  123. var ReqRefreshToken ReqRefreshTokenStruct
  124. ReqRefreshToken.ComponentAppid = appID
  125. ReqRefreshToken.AuthorizerAppid = item.AuthorizerAppid
  126. ReqRefreshToken.AuthorizerRefreshToken = item.AuthorizerRefreshToken
  127. uri := fmt.Sprintf("%s?component_access_token=%s", "https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token", componentAccessToken)
  128. var responseBytes []byte
  129. responseBytes, err = util.PostJSON(uri, ReqRefreshToken)
  130. if err != nil {
  131. utils.ErrorLog("error: %s", err)
  132. continue
  133. }
  134. var res wechat_service.MPResult
  135. err = json.Unmarshal(responseBytes, &res)
  136. if err != nil {
  137. utils.ErrorLog("%s, error: %s", item.AuthorizerAppid, err)
  138. continue
  139. }
  140. if res.ErrCode > 0 {
  141. utils.ErrorLog("%s, error: %s", item.AuthorizerAppid, res.ErrMsg)
  142. continue
  143. }
  144. var accessToken wechat_service.RefreshToken
  145. err = json.Unmarshal(responseBytes, &accessToken)
  146. if err != nil {
  147. utils.ErrorLog("%s, Unmarshal error: %s", item.AuthorizerAppid, err)
  148. continue
  149. }
  150. info := *item
  151. info.AuthorizerAccessToken = accessToken.AuthorizerAccessToken
  152. info.AuthorizerRefreshToken = accessToken.AuthorizerRefreshToken
  153. info.UpdatedTime = time.Now().Unix()
  154. err = wechat_service.SaveAuthorizationInfo(&info)
  155. if err != nil {
  156. utils.ErrorLog("%s,Save error: %s", item.AuthorizerAppid, err)
  157. continue
  158. }
  159. atKey := fmt.Sprintf("Patient:AccessToken[%s]", item.AuthorizerAppid)
  160. _, err = redisClient.Set(atKey, accessToken.AuthorizerAccessToken, 0).Result()
  161. if err != nil {
  162. utils.ErrorLog("%s,Save redis error: %s", item.AuthorizerAppid, err)
  163. continue
  164. }
  165. }
  166. utils.InfoLog("Request MpWechatAccessToken END")
  167. }