package service import ( "github.com/tidwall/gjson" "kefu/lib" "kefu/models" "kefu/tools" "kefu/types" "log" "time" ) func UpdateDouyinAccessToken() { //过期时间开始 expirationStart := time.Now().Add(-72 * time.Hour) // 计算当前时间减两小时的时间 expirationThreshold := time.Now().Add(72 * time.Hour) userDouyins := models.FindUserDouyinRows("expires_in > ? and expires_in < ?", expirationStart, expirationThreshold) clientId := models.FindConfig("DouyinClientKey") clientKey := models.FindConfig("DouyinClientSecret") douyin, _ := lib.NewDouyin(clientId, clientKey) for _, tokens := range userDouyins { jsonStr, _ := douyin.RefeshNewAccessToken(tokens.RefreshToken) log.Println("获取抖音access_token:", jsonStr) openid := gjson.Get(jsonStr, "data.open_id").String() access_token := gjson.Get(jsonStr, "data.access_token").String() expiresInt := gjson.Get(jsonStr, "data.expires_in").Int() expiresInInt := tools.Now() + expiresInt if openid == "" || access_token == "" { continue } userDouyin := models.User_douyin{ AccessToken: access_token, ExpiresIn: types.Time{tools.IntToTime(expiresInInt - 3600)}, } userDouyin.SaveUserDouyin("open_id = ?", openid) log.Println("更新抖音access_token:", jsonStr) } //刷新refreshToken userReDouyins := models.FindUserDouyinRows("refresh_expires_in > ? and refresh_expires_in < ?", expirationStart, expirationThreshold) for _, tokens := range userReDouyins { jsonStr, _ := douyin.RenewRefreshToken(tokens.RefreshToken) refresh_token := gjson.Get(jsonStr, "data.refresh_token").String() log.Println("获取抖音refresh_token:", jsonStr) expiresInt := gjson.Get(jsonStr, "data.expires_in").Int() expiresInInt := tools.Now() + expiresInt if refresh_token == "" { continue } userDouyin := models.User_douyin{ RefreshToken: refresh_token, RefreshExpiresIn: types.Time{tools.IntToTime(expiresInInt - 3600)}, } userDouyin.SaveUserDouyin("refresh_token = ?", tokens.RefreshToken) log.Println("更新抖音refresh_token:", jsonStr) } }