【发布时间】:2015-01-17 13:27:16
【问题描述】:
我的应用程序正在使用带有 OAuth 的 Google API Calendar V3,效果很好。它会在第一时间征求用户的同意。使用日历服务很容易创建、修改和删除日历事件。 到目前为止,一切都很好!
现在我想询问用户添加和修改联系人数据的权限。通过添加以下字符串“https://www.google.com/m8/feeds/”,还会要求用户获得联系人访问权限批准。 这似乎有效。 但是,我找不到基于通过上述过程收到的 UserCredential 创建 ContactsService 的方法。 如何将 UserCredential 与 ContactsService 一起使用?
我阅读了所有带有标签的问题:Google-contact 和 Google-api-dotnet-client。 我确实检查了 API V3 上的文档,发现为日历、驱动器和一堆其他 API 创建了服务,但没有为联系人创建服务? 我错过了什么?
这是我用来请求许可和启动日历服务的代码片段。
using Google.Contacts;
using Google.GData.Contacts;
using Google.GData.Client;
using Google.GData.Extensions;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Calendar;
using Google.Apis.Calendar.v3;
using Google.Apis.Calendar.v3.Data;
using System.Threading;
using Google.Apis.Services;
namespace MY
{
class GoogleContact
{
static public void start_service()
{
UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets
{
ClientId = "clientID",
ClientSecret = "clientsecret",
},
new[] { CalendarService.Scope.Calendar, "https://www.google.com/m8/feeds/" }, // This will ask the client for concent on calendar and contatcs
"user",
CancellationToken.None).Result;
// Create the calendar service.
CalendarService cal_service = new CalendarService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Calendar API Sample",
});
// How do I use the found credential to create a ContactsService????
ContactsService service = new ContactsService("APP_NAME");
}
感谢您对我必须采取的后续步骤的任何反馈?
得到反馈后更新:
为了使用联系人数据,我添加了以下代码片段。
// Get the tokens from the FileDataStore
var token = new FileDataStore("Google.Apis.Auth")
.GetAsync<TokenResponse>("user");
OAuth2Parameters parameters = new OAuth2Parameters
{
ClientId = mSecrets.ClientId,
ClientSecret = mSecrets.ClientSecret,
// Note: AccessToken is valid only for 60 minutes
AccessToken = token.Result.AccessToken,
RefreshToken = token.Result.RefreshToken
};
RequestSettings settings = new RequestSettings(
"Contact API Sample", parameters);
ContactsRequest cr = new ContactsRequest(settings);
Feed<Contact> f = cr.GetContacts();
// The AccessCode is automatically updated after expiration!
foreach (Contact c in f.Entries)
{
Console.WriteLine(c.Name.FullName);
}
首先,我从 FileDataStore 读回访问令牌和刷新令牌。
然后我使用刚刚读取的令牌设置 OAuth2Parameters。
现在,我可以构造一个新的 ContactsService 和一个 ContactsRequest。
令我惊讶的是,在 ContactsService 到期后,访问令牌也会自动更新。
【问题讨论】:
标签: c# oauth gdata google-contacts-api google-api-dotnet-client