我每隔1.5分鐘執行一次我的C#應用程序的Google應用程序腳本。應用程序腳本在電子表格之間移動內容,並編輯表單。我也使用Drive API。谷歌應用程序腳本執行API服務授權每小時失敗一次
我的腳本長時間運行良好,除了每小時收到5分鐘的授權錯誤。
這裏是我的代碼,處理授權:
class Authentication
{
public static ScriptService ScriptsAuthenticateOauth(UserCredential credential)
{
try
{
ScriptService service = new ScriptService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "MyApp",
});
return service;
}
catch (Exception ex)
{
Console.WriteLine(DateTime.Now.ToString("HH:mm") + ": An authentication error occurred: " + ex.InnerException);
return null;
}
}
public static UserCredential getCredential(string clientId, string clientSecret, string userName)
{
string[] scopes = new string[] { DriveService.Scope.Drive, // view and manage your files and documents
DriveService.Scope.DriveAppdata, // view and manage its own configuration data
DriveService.Scope.DriveAppsReadonly, // view your drive apps
DriveService.Scope.DriveFile, // view and manage files created by this app
DriveService.Scope.DriveMetadataReadonly, // view metadata for files
DriveService.Scope.DriveReadonly, // view files and documents on your drive
DriveService.Scope.DriveScripts, // modify your app scripts
ScriptService.Scope.Drive,
"https://www.googleapis.com/auth/spreadsheets",
"https://spreadsheets.google.com/feeds",
"https://docs.google.com/feeds"};
return GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = clientId, ClientSecret = clientSecret }
, scopes
, userName
, CancellationToken.None
, new FileDataStore("Google.Sheet.Sync.Auth.Store")).Result;
}
public static DriveService DriveAuthenticateOauth(UserCredential credential)
{
try
{
DriveService service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "MyApp",
});
// Console.WriteLine("Auth success");
return service;
}
catch (Exception ex)
{
// Console.WriteLine(ex.InnerException);
Console.WriteLine(DateTime.Now.ToString("HH:mm") + ": An authentication error occurred: " + ex.InnerException);
return null;
}
}
}
我讓我的服務是這樣的:
var credential = Authentication.getCredential(CLIENT_ID, CLIENT_SECRET, Environment.UserName);
DriveService driveService = Authentication.DriveAuthenticateOauth(credential);
ScriptService scriptService = Authentication.ScriptsAuthenticateOauth(credential);
但圍繞小時結束時,應用程序腳本調用引發以下錯誤:
Script error message: Authorization is required to perform that action.
要清楚的是,它在所有其他時間都能正常工作,而不是在那5分鐘內n一小時結束。我在我的開發人員控制檯上以及在應用腳本編輯器中的Resources> Advanced Google services ...下激活了Google Drive API。
那麼是怎麼回事?這可以解決嗎?
似乎你傳遞了一個過期的訪問令牌。如果是這樣,請閱讀oauth2以及如何處理刷新和訪問令牌。 –