push.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. package zoho
  2. import (
  3. "crm-api/pkg/configs"
  4. "crm-api/pkg/httpclient"
  5. "crm-api/pkg/lfshook"
  6. "encoding/json"
  7. "fmt"
  8. "io/ioutil"
  9. "net/http"
  10. "strconv"
  11. "time"
  12. "gopkg.in/ini.v1"
  13. )
  14. var TimestampList = make(map[string]string)
  15. var StartTimeList = make(map[string]time.Time) // 事件中 Timestamp 转 StartTime 有问题,重新记录时间
  16. // var CallTypeList = make(map[string]string) // 临时记录 incoming 和 outgoing
  17. var DialStatusList = make(map[string]string) // 临时记录 DialStatus:ANSWER NOANSWER
  18. func CallNotify(event map[string]string) {
  19. fmt.Println("=========================================== ")
  20. fmt.Println("event[] = ", event)
  21. fmt.Println("event = ", event["Event"])
  22. fmt.Println("AMIPushUrl = ", configs.PushConfigValue.AMIPushUrl)
  23. fmt.Println("Channel = ", event["Channel"])
  24. /* ===================不这样取callDest,删除 ====================
  25. var callDest string
  26. if event["Channel"] != "" {
  27. callDest = strings.Split(strings.Split(event["Channel"], "/")[1], "-")[0]
  28. fmt.Println("callDest = ", callDest)
  29. }
  30. // * ========================================================= */
  31. // var callId string
  32. var callId = "10000026" // 测试用,每次测试 +1
  33. // event["Exten"] = "123456789" // 测试用
  34. // fmt.Println("Exten = ", event["Exten"])
  35. var zohoUser = "872297346" // 测试用 872297346 873447071 // 后面看是否从数据库中取 t_zoho_user
  36. // 读取vtiger配置文件
  37. confPath := "/etc/asterisk/crm_api.conf"
  38. cfg, err := ini.Load(confPath)
  39. if err != nil {
  40. lfshook.NewLogger().Error(err)
  41. return
  42. }
  43. ZOHO_URL := cfg.Section("general").Key("zohoUrl").String()
  44. if ZOHO_URL == "" {
  45. lfshook.NewLogger().Error("/etc/asterisk/crm_api.conf not set zohoUrl")
  46. return
  47. }
  48. // var getURL string
  49. fmt.Println("Context = ", event["Context"])
  50. // 呼叫发起事件
  51. // if event["Event"] == "DialBegin" && event["Context"] == "macro-stdexten" {
  52. // if event["Event"] == "DialBegin" && strings.Compare(event["Context"], "macro-stdexten") == 0 {
  53. if event["Event"] == "DialBegin" {
  54. /* ===================先放这里测试用 ============================================================
  55. // 记录开始时间
  56. TimestampList[event["Uniqueid"]] = event["Timestamp"]
  57. // StartTimeList[event["Uniqueid"]] = time.Now().Format("2006-01-02 15:04:09")
  58. StartTimeList[event["Uniqueid"]] = time.Now()
  59. /* ===================先放这里测试用 ============================================================
  60. fmt.Printf("Uniqueid=%s\n", event["Uniqueid"])
  61. fmt.Printf("Timestamp=%s\n", event["Timestamp"])
  62. TimestampTmp, err := strconv.Atoi(event["Timestamp"]) // 不要
  63. if err != nil {
  64. fmt.Printf("转换出错: %v\n", err)
  65. return
  66. }
  67. fmt.Printf("TimestampAtoi=%d\n", TimestampTmp)
  68. TimestampTmp002, err := strconv.ParseFloat(event["Timestamp"], 64) // OK
  69. if err != nil {
  70. fmt.Printf("转换出错: %v\n", err)
  71. return
  72. }
  73. fmt.Printf("TimestampParseFloat=%f\n", TimestampTmp002)
  74. // * ===================================================================================== */
  75. // Outgoing Call - Ringing
  76. if event["Context"] == "macro-trunkdial-failover" {
  77. StartTimeList[event["Linkedid"]] = time.Now()
  78. // https://www.zohoapis.com/phonebridge/v3/callnotify?type=dialed&state=ringing&id=10031&from=123456789&to=12300000001
  79. getURL := fmt.Sprintf("%s/phonebridge/v3/callnotify?type=dialed&state=ringing&id=%s&from=%s&to=%s", ZOHO_URL, callId, event["CallerIDNum"], event["DestCallerIDNum"])
  80. if zohoUser != "" {
  81. getURL = fmt.Sprintf("%s&zohouser=%s", getURL, zohoUser)
  82. }
  83. fmt.Println("getURL = ", getURL)
  84. go httpclient.ZohoGet(getURL)
  85. // Incoming Call - Ringing
  86. // if event["Context"] == "macro-stdexten" {
  87. } else if event["Context"] == "macro-stdexten" || event["Context"] == "macro-stdexten-withoutvm" { // 开启语音留言:macro-stdexten 关闭语音留言:macro-stdexten-withoutvm
  88. StartTimeList[event["Linkedid"]] = time.Now()
  89. // if strings.Compare(event["Context"], "macro-stdexten") == 0 { // OK
  90. // https://www.zohoapis.com/phonebridge/v3/callnotify?type=received&state=ringing&id=10033&from=12300000001&to=123456789
  91. // getURL := fmt.Sprintf("%s/phonebridge/v3/callnotify?type=received&state=ringing&id=%s&from=%s&to=%s", ZOHO_URL, callId, event["Exten"], callDest) // 取得from to 可能不准
  92. getURL := fmt.Sprintf("%s/phonebridge/v3/callnotify?type=received&state=ringing&id=%s&from=%s&to=%s", ZOHO_URL, callId, event["CallerIDNum"], event["DestCallerIDNum"])
  93. if zohoUser != "" {
  94. getURL = fmt.Sprintf("%s&zohouser=%s", getURL, zohoUser)
  95. }
  96. fmt.Println("getURL = ", getURL)
  97. go httpclient.ZohoGet(getURL)
  98. }
  99. // 呼叫结束事件
  100. } else if event["Event"] == "DialEnd" {
  101. // 记录呼叫状态
  102. DialStatusList[event["Linkedid"]] = event["DialStatus"]
  103. // Outgoing Call - Unattended
  104. if event["Context"] == "macro-trunkdial-failover" && event["DialStatus"] != "ANSWER" {
  105. startTime := StartTimeList[event["Linkedid"]].Format("2006-01-02 15:04:09")
  106. fmt.Println("startTime: ", startTime)
  107. // https://www.zohoapis.com/phonebridge/v3/callnotify?type=dialed&state=busy&id=10025&from=123456789&to=12300000001&start_time=2024-12-04 15:09:10
  108. getURL := fmt.Sprintf("%s/phonebridge/v3/callnotify?type=dialed&state=busy&id=%s&from=%s&to=%s&start_time=%s", ZOHO_URL, callId, event["CallerIDNum"], event["DestCallerIDNum"], startTime)
  109. if zohoUser != "" {
  110. getURL = fmt.Sprintf("%s&zohouser=%s", getURL, zohoUser)
  111. }
  112. fmt.Println("getURL = ", getURL)
  113. go httpclient.ZohoGet(getURL)
  114. // Incoming Call - Missed
  115. // if event["Context"] == "macro-stdexten" && event["DialStatus"] != "ANSWER" {
  116. } else if (event["Context"] == "macro-stdexten" || event["Context"] == "macro-stdexten-withoutvm") && event["DialStatus"] != "ANSWER" { // 开启语音留言:macro-stdexten 关闭语音留言:macro-stdexten-withoutvm
  117. startTime := StartTimeList[event["Linkedid"]].Format("2006-01-02 15:04:09")
  118. fmt.Println("startTime: ", startTime)
  119. // https://www.zohoapis.com/phonebridge/v3/callnotify?type=received&state=missed&id=10005&from=12300000001&to=123456789&start_time=2024-12-04 15:09:10
  120. getURL := fmt.Sprintf("%s/phonebridge/v3/callnotify?type=received&state=missed&id=%s&from=%s&to=%s&start_time=%s", ZOHO_URL, callId, event["CallerIDNum"], event["DestCallerIDNum"], startTime)
  121. if zohoUser != "" {
  122. getURL = fmt.Sprintf("%s&zohouser=%s", getURL, zohoUser)
  123. }
  124. fmt.Println("getURL = ", getURL)
  125. go httpclient.ZohoGet(getURL)
  126. }
  127. // 呼叫已连接事件
  128. } else if event["Event"] == "BridgeEnter" {
  129. // Outgoing Call - Answered
  130. if event["Context"] == "macro-trunkdial-failover" && event["Priority"] == "1" { // 注意这里选择 Priority:1 的,便于确认 CallerIDNum,ConnectedLineNum
  131. // 记录开始时间
  132. // TimestampList[event["Uniqueid"]] = event["Timestamp"] // error 需要把 Uniqueid 改为 Linkedid
  133. // StartTimeList[event["Uniqueid"]] = time.Now() // error 需要把 Uniqueid 改为 Linkedid
  134. TimestampList[event["Linkedid"]] = event["Timestamp"]
  135. StartTimeList[event["Linkedid"]] = time.Now()
  136. // https: //www.zohoapis.com/phonebridge/v3/callnotify?type=dialed&state=answered&id=10003&from=123456789&to=12300000001
  137. // getURL := fmt.Sprintf("%s/phonebridge/v3/callnotify?type=dialed&state=answered&id=%s&from=%s&to=%s", ZOHO_URL, callId, event["CallerIDNum"], event["ConnectedLineNum"])
  138. getURL := fmt.Sprintf("%s/phonebridge/v3/callnotify?type=dialed&state=answered&id=%s&from=%s&to=%s", ZOHO_URL, callId, event["ConnectedLineNum"], event["CallerIDNum"])
  139. if zohoUser != "" {
  140. getURL = fmt.Sprintf("%s&zohouser=%s", getURL, zohoUser)
  141. }
  142. fmt.Println("getURL = ", getURL)
  143. go httpclient.ZohoGet(getURL)
  144. // Incoming Call - Answered
  145. // if event["Context"] == "macro-stdexten" {
  146. } else if event["Context"] == "macro-stdexten" || event["Context"] == "macro-stdexten-withoutvm" { // 开启语音留言:macro-stdexten 关闭语音留言:macro-stdexten-withoutvm
  147. // 记录开始时间
  148. // TimestampList[event["Uniqueid"]] = event["Timestamp"] // Uniqueid 有时通话也不合适 NG // 都改为 Linkedid
  149. // StartTimeList[event["Uniqueid"]] = time.Now() // Uniqueid 有时通话也不合适 NG // 都改为 Linkedid
  150. TimestampList[event["Linkedid"]] = event["Timestamp"] // 呼入时设置 Uniqueid 不是 Linkedid
  151. StartTimeList[event["Linkedid"]] = time.Now() // 呼入时设置 Uniqueid 不是 Linkedid
  152. // https://www.zohoapis.com/phonebridge/v3/callnotify?type=received&state=answered&id=10023&from=12300000001&to=123456789
  153. getURL := fmt.Sprintf("%s/phonebridge/v3/callnotify?type=received&state=answered&id=%s&from=%s&to=%s", ZOHO_URL, callId, event["CallerIDNum"], event["ConnectedLineNum"])
  154. if zohoUser != "" {
  155. getURL = fmt.Sprintf("%s&zohouser=%s", getURL, zohoUser)
  156. }
  157. fmt.Println("getURL = ", getURL)
  158. go httpclient.ZohoGet(getURL)
  159. }
  160. // 呼叫挂断事件
  161. } else if event["Event"] == "HangupRequest" {
  162. /* ===================先放这里测试用 ============================================================
  163. // 记录结束时间
  164. // TimestampList[event["Uniqueid"]] = event["Timestamp"]
  165. // startTimeStamp := int64(TimestampList[event["Uniqueid"]])
  166. fmt.Println("startTimeStamp Str: ", TimestampList[event["Uniqueid"]])
  167. // keyTmp := event["Uniqueid"]
  168. // fmt.Println("keyTmp: ", keyTmp)
  169. // fmt.Println("startTimeStamp Str: ", TimestampList[keyTmp])
  170. startTimeStamp, err := strconv.ParseFloat(TimestampList[event["Uniqueid"]], 64) // OK
  171. if err != nil {
  172. fmt.Printf("startTimeStamp转换出错: %v\n", err)
  173. return
  174. }
  175. fmt.Printf("startTimeStamp=%f\n", startTimeStamp)
  176. endTimeStamp, err := strconv.ParseFloat(event["Timestamp"], 64) // OK
  177. if err != nil {
  178. fmt.Printf("endTimeStamp转换出错: %v\n", err)
  179. return
  180. }
  181. fmt.Printf("endTimeStamp=%f\n", endTimeStamp)
  182. durationTime := time.Duration(endTimeStamp-startTimeStamp) * time.Second
  183. fmt.Println("durationTime=", durationTime)
  184. // 删除记录时间
  185. // delete(TimestampList, event["Uniqueid"])
  186. // * ===================================================================================== */
  187. // 判断呼叫状态,为 ANSWER 时才推送,否则见以上推送 Outgoing Call - Unattended 或 Incoming Call - Missed
  188. if DialStatusList[event["Linkedid"]] == event["DialStatus"] {
  189. // Outgoing Call - Ended
  190. if event["Context"] == "macro-trunkdial-failover" {
  191. // 获取时间
  192. // durationTime := getDuration(event["Uniqueid"], event["Timestamp"])
  193. durationTime := getDuration(event["Linkedid"], event["Timestamp"])
  194. // /* ===================测试用 ============================================================
  195. // startTime, _ := time.Parse("2006-01-02 15:04:05", TimestampList[event["Uniqueid"]]) // error 1734328213.774410 => 0001-01-01 00:00:00 +0000 UTC
  196. // startTime := StartTimeList[event["Uniqueid"]]
  197. // startTime := StartTimeList[event["Uniqueid"]].Format("2006-01-02 15:04:09") // 存储从string 改为 time.Time
  198. startTime := StartTimeList[event["Linkedid"]].Format("2006-01-02 15:04:09") // 存储从string 改为 time.Time
  199. fmt.Println("startTime: ", startTime)
  200. // durationTime002 := getDuration002(startTime)
  201. // durationTime002 := time.Now().Sub(StartTimeList[event["Uniqueid"]]) // ok durationTime002: 7.78408849s // should use time.Since instead of time.Now().Sub (S1012)
  202. // durationTime002 := time.Since(StartTimeList[event["Uniqueid"]]) // ok durationTime002: 11.611233458s
  203. // fmt.Println("durationTime002: ", durationTime002)
  204. // * ===================================================================================== */
  205. // 删除记录时间
  206. delete(StartTimeList, event["Linkedid"])
  207. // https://www.zohoapis.com/phonebridge/v3/callnotify?type=dailed&state=ended&id=10030&from=123456789&to=12300000001&start_time=2024-12-04 11:32:15&duration=325
  208. // getURL := fmt.Sprintf("%s/phonebridge/v3/callnotify?type=dailed&state=ended&id=%s&from=%s&to=%s&start_time=%s&duration=%d", ZOHO_URL, callId, event["CallerIDNum"], event["ConnectedLineNum"], startTime, durationTime)
  209. getURL := fmt.Sprintf("%s/phonebridge/v3/callnotify?type=dailed&state=ended&id=%s&from=%s&to=%s&start_time=%s&duration=%d", ZOHO_URL, callId, event["ConnectedLineNum"], event["CallerIDNum"], startTime, durationTime)
  210. if zohoUser != "" {
  211. getURL = fmt.Sprintf("%s&zohouser=%s", getURL, zohoUser)
  212. }
  213. fmt.Println("getURL = ", getURL)
  214. go httpclient.ZohoGet(getURL)
  215. // Incoming Call - Ended
  216. // if event["Context"] == "macro-stdexten" { // Context:DialPlan1
  217. } else if event["Context"] == "macro-stdexten" || event["Context"] == "macro-stdexten-withoutvm" { // 开启语音留言:macro-stdexten 关闭语音留言:macro-stdexten-withoutvm
  218. // if event["Context"] != "macro-trunkdial-failover" {
  219. // 还需优化判断,开启语音留言时,主叫挂断才是 macro-stdexten , 被叫挂断是 DialPlan1
  220. // 关闭语音留言时,主叫挂断才是 macro-stdexten-withoutvm , 被叫挂断是 DialPlan1
  221. // 如果 Outgoing Call 只会是 macro-trunkdial-failover 的话,那么和以下判断换一下,else 不判断,都为 Incoming Call 处理
  222. // 获取时间
  223. // durationTime := getDuration(event["Uniqueid"], event["Timestamp"])
  224. // startTime := StartTimeList[event["Uniqueid"]].Format("2006-01-02 15:04:09") // 存储从string 改为 time.Time
  225. durationTime := getDuration(event["Linkedid"], event["Timestamp"])
  226. startTime := StartTimeList[event["Linkedid"]].Format("2006-01-02 15:04:09") // 存储从string 改为 time.Time
  227. fmt.Println("startTime: ", startTime)
  228. // https://www.zohoapis.com/phonebridge/v3/callnotify?type=received&state=ended&id=100&from=12300000001&to=123456789&start_time=2024-12-04 10:32:10&duration=223
  229. getURL := fmt.Sprintf("%s/phonebridge/v3/callnotify?type=received&state=ended&id=%s&from=%s&to=%s&start_time=%s&duration=%d", ZOHO_URL, callId, event["CallerIDNum"], event["ConnectedLineNum"], startTime, durationTime)
  230. // getURL := fmt.Sprintf("%s/phonebridge/v3/callnotify?type=received&state=ended&id=%s&from=%s&to=%s&start_time=%s&duration=%d", ZOHO_URL, callId, event["ConnectedLineNum"], event["CallerIDName"], startTime, durationTime)
  231. if zohoUser != "" {
  232. getURL = fmt.Sprintf("%s&zohouser=%s", getURL, zohoUser)
  233. }
  234. fmt.Println("getURL = ", getURL)
  235. go httpclient.ZohoGet(getURL)
  236. }
  237. }
  238. }
  239. // fmt.Println("getURL = ", getURL)
  240. // 测试验证下上面有没有删除,以防TimestampList越来越大
  241. for k, v := range TimestampList {
  242. fmt.Printf("===Linkedid:%s Timestamp:%s===\n", k, v)
  243. }
  244. }
  245. // 使用事件中event["Timestamp"]的值计算时间间隔
  246. // func getDuration(uniqueid string, timeStamp string) int {
  247. func getDuration(linkedid string, timeStamp string) int { // 都改为 Linkedid
  248. fmt.Println("startTimeStamp Str: ", TimestampList[linkedid])
  249. if TimestampList[linkedid] == "" || timeStamp == "" {
  250. fmt.Printf("linkedid 或 timeStamp 为空\n")
  251. return 9999
  252. }
  253. startTimeStamp, err := strconv.ParseFloat(TimestampList[linkedid], 64)
  254. if err != nil {
  255. fmt.Printf("startTimeStamp转换出错: %v\n", err)
  256. return 9999
  257. }
  258. fmt.Printf("startTimeStamp=%f\n", startTimeStamp)
  259. endTimeStamp, err := strconv.ParseFloat(timeStamp, 64)
  260. if err != nil {
  261. fmt.Printf("endTimeStamp转换出错: %v\n", err)
  262. return 9999
  263. }
  264. fmt.Printf("endTimeStamp=%f\n", endTimeStamp)
  265. durationTime := time.Duration(endTimeStamp-startTimeStamp) * time.Second
  266. // fmt.Println("durationTime=", durationTime) // durationTime= 35s
  267. // fmt.Printf("durationTime=%d\n", durationTime) // durationTime=35000000000
  268. // fmt.Printf("durationTime=%d\n", durationTime.Seconds()) // durationTime=%!d(float64=35)
  269. // fmt.Printf("durationTime=%f\n", durationTime.Seconds()) // durationTime=35.000000
  270. fmt.Printf("durationTime=%d\n", int(durationTime.Seconds())) // durationTime=35
  271. // durationTime001 := time.Duration(endTimeStamp - startTimeStamp)
  272. // fmt.Println("durationTime001=", durationTime001) // durationTime001= 35ns
  273. // durationTime003 := time.Duration(endTimeStamp - startTimeStamp).Seconds()
  274. // fmt.Println("durationTime003=", durationTime003) // durationTime003= 3.5e-08
  275. // 删除记录时间
  276. delete(TimestampList, linkedid)
  277. // return durationTime
  278. return int(durationTime.Seconds())
  279. }
  280. // // 程序中取时间计算间隔多少秒
  281. // func getDuration002(startTime string) time.Duration {
  282. // // durationTime := endTime.Sub(startTime)
  283. // startTime002, err := time.Parse("2006-01-02 15:04:05", startTime)
  284. // if err != nil {
  285. // fmt.Println("Error parsing time:", err)
  286. // return 0
  287. // }
  288. // durationTime := time.Now().Sub(startTime002)
  289. // return durationTime
  290. // }
  291. // @tags PBX-zoho
  292. // @Summary 刷新token
  293. // @Description 刷新token
  294. // @Security ZohoToken
  295. // @Accept json
  296. // @Produce json
  297. // @Router /api/zoho/refresh-token [post]
  298. func RefreshToken() {
  299. fmt.Printf("RefreshToken ............\n")
  300. // 获取配置文件信息
  301. // confPath := "/etc/asterisk/vtiger_api.conf"
  302. confPath := "/etc/asterisk/crm_api.conf"
  303. cfg, err := ini.Load(confPath)
  304. if err != nil {
  305. lfshook.NewLogger().Error(err)
  306. return
  307. }
  308. ZohoAuthUrl := cfg.Section("general").Key("zohoAuthUrl").String()
  309. ZohoRefreshToken := cfg.Section("general").Key("zohoRefreshToken").String()
  310. ZohoClientId := cfg.Section("general").Key("zohoClientId").String()
  311. ZohoClientSecret := cfg.Section("general").Key("zohoClientSecret").String()
  312. if ZohoAuthUrl == "" || ZohoRefreshToken == "" || ZohoClientId == "" || ZohoClientSecret == "" {
  313. lfshook.NewLogger().Error("/etc/asterisk/crm_api.conf not set zohoAuthUrl or zohoRefreshToken or zohoClientId or zohoClientSecret")
  314. return
  315. }
  316. // 创建请求
  317. // https://accounts.zoho.com/oauth/v2/token?refresh_token=1004.86c8c0e3db7bfe9133598825bef28eb9.17a82a3bf3e675c504f478c1b0b5c456
  318. // &client_id=1004.LWJCJZD5O9DB6SZLL5YJEWHT7LH0BV&client_secret=fc3aef43dc58af8a49d3ed597710924200b03f74d0&grant_type=refresh_token
  319. getURL := fmt.Sprintf("%s/oauth/v2/token?refresh_token=%s&client_id=%s&client_secret=%s&grant_type=refresh_token", ZohoAuthUrl, ZohoRefreshToken, ZohoClientId, ZohoClientSecret)
  320. fmt.Printf("getURL = %s\n", getURL)
  321. // data := httpRequest(ctx, "POST", getURL)
  322. // /* =====================================================================================
  323. req, err := http.NewRequest("POST", getURL, nil)
  324. if err != nil {
  325. fmt.Println("创建请求时发生错误:", err)
  326. return
  327. }
  328. // 创建HTTP客户端
  329. client := &http.Client{}
  330. // req.Header.Set("Authorization", "Bearer "+accessToken) // 刷新token时不需要
  331. // 发送请求
  332. resp, err := client.Do(req)
  333. if err != nil {
  334. fmt.Println("发送请求时发生错误:", err)
  335. return
  336. }
  337. defer resp.Body.Close()
  338. // 读取请求后的响应
  339. data, err := ioutil.ReadAll(resp.Body)
  340. if err != nil {
  341. // 读取数据错误
  342. lfshook.NewLogger().Warn("ioutil ReadAll failed :", err.Error())
  343. // api.Error(ctx, http.StatusInternalServerError, err.Error())
  344. return
  345. }
  346. lfshook.NewLogger().Infof("data %+v", string(data))
  347. // * ===================================================================================== */
  348. refreshTokenData := RefreshTokenResp{}
  349. err = json.Unmarshal([]byte(data), &refreshTokenData)
  350. if err != nil {
  351. // 转换数据错误
  352. lfshook.NewLogger().Warn("json unmarshal failed :", err.Error())
  353. // api.Error(ctx, http.StatusInternalServerError, err.Error())
  354. return
  355. }
  356. // 将获取的 access_token 写入文件 crm_api.conf
  357. cfg.Section("general").Key("zohoAccessToken").SetValue(refreshTokenData.AccessToken)
  358. err = cfg.SaveTo(confPath)
  359. if err != nil {
  360. lfshook.NewLogger().Error(err)
  361. // api.Error(ctx, http.StatusInternalServerError, err.Error())
  362. return
  363. }
  364. // 打印请求后的响应
  365. fmt.Printf("data = %+v\n", string(data))
  366. // api.Success(ctx, string(data))
  367. // api.Success(ctx, refreshTokenData)
  368. // return
  369. }
  370. // 每隔55分钟刷新token
  371. func RefreshTokenTicker() {
  372. fmt.Printf("RefreshTokenTicker ............\n")
  373. ticker := time.NewTicker(55 * time.Minute)
  374. defer ticker.Stop()
  375. done := make(chan bool)
  376. // go func() { // 注释掉OK
  377. for {
  378. select {
  379. case <-done:
  380. return
  381. case t := <-ticker.C:
  382. fmt.Println("Tick at", t)
  383. RefreshToken()
  384. }
  385. }
  386. // }()
  387. }