[英]How to access users calendar list and events from google api using access token and refresh token
I already have obtained users access token from google api using oAuth2. 我已经使用oAuth2从Google api获取用户访问令牌。 Now i want to use this token to get user events/calendars.
现在,我想使用此令牌获取用户事件/日历。 I have tried following code but it is not working.
我试过下面的代码,但是不起作用。
Can anyone here help me with this please. 请问有人可以帮我这个忙。 Thanks
谢谢
var urlBuilder = new System.Text.StringBuilder();
urlBuilder.Append("https://");
urlBuilder.Append("www.googleapis.com");
urlBuilder.Append("/calendar/v3/users/me/calendarList");
urlBuilder.Append("?minAccessRole=reader");
var httpWebRequest = HttpWebRequest.Create(urlBuilder.ToString()) as HttpWebRequest;
httpWebRequest.CookieContainer = new CookieContainer();
httpWebRequest.Headers["Authorization"] string.Format("Bearer {0}", data.access_token);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream eventResponseStream = response.GetResponseStream();
StreamReader eventResponseStreamReader = new StreamReader(responseStream);
string eventsStr = eventResponseStreamReader.ReadToEnd();
I have found solution using Google.Apis.Calendar.v3
, i am posting it here so may help someone else. 我已经找到了使用
Google.Apis.Calendar.v3
解决方案,我将其发布在这里,所以可能会对其他人有所帮助。 Following is the code to get the events list when you have refresh token of a user: 以下是当您具有用户的刷新令牌时获取事件列表的代码:
First get new access token using the refresh token: 首先使用刷新令牌获取新的访问令牌:
string postString = "client_id=yourclientid";
postString += "&client_secret=youclientsecret&refresh_token=userrefreshtoken";
postString += "&grant_type=refresh_token";
string url = "https://www.googleapis.com/oauth2/v4/token";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url.ToString());
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
UTF8Encoding utfenc = new UTF8Encoding();
byte[] bytes = utfenc.GetBytes(postString);
Stream os = null;
request.ContentLength = bytes.Length;
os = request.GetRequestStream();
os.Write(bytes, 0, bytes.Length);
GoogleToken token = new GoogleToken();
HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse();
Stream responseStream = webResponse.GetResponseStream();
StreamReader responseStreamReader = new StreamReader(responseStream);
string result = responseStreamReader.ReadToEnd();
JavaScriptSerializer serializer = new JavaScriptSerializer();
token = serializer.Deserialize<GoogleToken>(result);
Then use the toke and refresh token to create credentials. 然后使用令牌和刷新令牌创建凭据。
var flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = new ClientSecrets
{
ClientId = yourclientid,
ClientSecret = yourclientsecret
},
Scopes = new[] { CalendarService.Scope.Calendar }
});
var credential = new UserCredential(flow, Environment.UserName, new TokenResponse
{
AccessToken = token.access_token,
RefreshToken = userrefreshtoke
});
CalendarService service = new CalendarService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "application name",
});
var list = service.CalendarList.List().Execute().Items;
foreach (var c in list)
{
var events = service.Events.List(c.Id).Execute().Items.Where(i => i.Start.DateTime >= DateTime.Now).ToList();
foreach (var e in events)
{
}
}
GoogleToken class: GoogleToken类:
public class GoogleToken
{
public string access_token { get; set; }
public string token_type { get; set; }
public string expires_in { get; set; }
}
According to the .NET Quickstart sample provided by Google you'll be needing to download a client_secret.json which is part of the authentication process. 根据Google提供的.NET Quickstart示例 ,您需要下载client_secret.json ,这是身份验证过程的一部分。 Check the whole process in the link.
在链接中检查整个过程。
Here' a snippet for feching events in .NET: 这是用于在.NET中缓存事件的代码段:
// List events.
Events events = request.Execute();
Console.WriteLine("Upcoming events:");
if (events.Items != null && events.Items.Count > 0)
{
foreach (var eventItem in events.Items)
{
string when = eventItem.Start.DateTime.ToString();
if (String.IsNullOrEmpty(when))
{
when = eventItem.Start.Date;
}
Console.WriteLine("{0} ({1})", eventItem.Summary, when);
}
}
else
{
Console.WriteLine("No upcoming events found.");
}
Console.Read();
You can also read more of oAuth related guides in .NET here . 您也可以在.NET中阅读更多与oAuth相关的指南。
For more info on retrieving Calendar lists and events, read this guide . 有关检索日历列表和事件的更多信息,请阅读本指南 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.