我的应用程序使用 Google API Calendar V3 和 OAuth,效果非常好。它会在第一时间征求用户的同意。使用日历服务可以轻松创建、修改和删除日历事件。
到目前为止,一切都很好!
现在我想请求用户允许添加和修改联系人数据。通过添加以下字符串“https://www.google.com/m8/feeds/ 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 的访问令牌在过期后也会自动更新。