2

我有一堆密钥:客户端 ID、客户端密码、API 密钥

但是所有文档都显示了使用人工交互的身份验证。

如何在没有用户交互的情况下使用点网库与 Google API v3 和 AnalyticsService 进行交互?如果我只使用 API 密钥,我会得到“需要 Google.Apis.Requests.RequestError 登录”

我在任何地方都找不到这样做的样本。

编辑:这是一个谷歌分析帐户,我可以完全访问它,用户名,密码,客户端 ID,客户端密码,api/开发者密钥,一切。我只想让实用程序每天在没有我的情况下下载数据。

4

1 回答 1

3

这是我的工作代码,这是我通过批处理文件进程调用的控制台应用程序。我不是 .Net 开发人员,所以这段代码可能并不完美,如果您看到任何需要改进的地方,请告诉我!错误处理是最小的,因为我不希望一次失败杀死批次

我正在使用注册表来存储访问令牌和过期时间在应用程序文件夹中还有 privatekey.p12 文件该帐户是用户而不是配置文件上的管理员。

还张贴在这里https://groups.google.com/forum/?fromgroups=#!topic/google-analytics-data-export-api/quIN0vX-psw

命令行调用示例:C:\DW\GoogleAnalyticsNicheSites\GoogleAnalyticsNicheSites.exe "ga:XXXX9049" "2012-04-01" "2012-04-01" "ga:visitors,ga:newVisits,ga:visits,ga:bounces ,ga:pageviews" "ga:date,ga:medium" "XXXXXXXXXXXXXXXXXXXXXXXXXXXX-privatekey.p12" "XXXXX...@developer.gserviceaccount.com" "RegKey" > C:\Data\NicheSites\ga_58589049_moneyjobs.com_20120401.txt"

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using DotNetOpenAuth.OAuth2;
using Google.Apis.Analytics.v3;
using Google.Apis.Analytics.v3.Data;
using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;
using Microsoft.Win32;
using Newtonsoft.Json;


namespace ConsoleApplication5
{
    class Program
    {
        public static string access_token = "";
        public static string expire_time = string.Empty;
        public static string profileId = string.Empty;
        public static string metrics = string.Empty;
        public static string dimensions = string.Empty;
        public static string startDate = string.Empty;
        public static string endDate = string.Empty;
        public static string privatekeyFile = string.Empty;
        public static string loginEmail = string.Empty;
        public static string regKeyName = string.Empty;

        static void Main(string[] args)
        {

            profileId = args[0];
            startDate = args[1];
            endDate = args[2];
            metrics = args[3];
            dimensions = args[4];
            privatekeyFile = args[5];
            loginEmail = args[6];
            regKeyName = args[7];

            try
            {
                // certificate
                string path = System.Reflection.Assembly.GetExecutingAssembly().CodeBase;
                var directory = System.IO.Path.GetDirectoryName(path).Remove(0, 6);
                var certificate = new X509Certificate2(directory + "\\" + privatekeyFile , "notasecret");

                try
                {
                    expire_time = (string)Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Wow6432Node\CB\" + regKeyName).GetValue("ExpireTime").ToString();
                }
                catch (Exception e)
                {
                    RegistryKey key;
                    key = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\CB\" + regKeyName);
                    key.SetValue("OAuthToken", "");
                    key.Close();
                }

                try
                {
                    access_token = (string)Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Wow6432Node\CB\" + regKeyName).GetValue("OAuthToken").ToString();
                }
                catch (Exception e)
                {
                    RegistryKey key;
                    key = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\CB\" + regKeyName);
                    key.SetValue("ExpireTime", DateTime.UtcNow.AddSeconds(3500).ToString("MM/dd/yyyy HH:mm:ss"));
                    key.Close();
                }

                if (expire_time == null || expire_time.Length < 4)
                {
                    expire_time = "01/01/2000";
                }

                var ExpireDateTime = Convert.ToDateTime(expire_time);
                var ExpireTimeNow = DateTime.UtcNow;
                TimeSpan span = ExpireDateTime - ExpireTimeNow;
                double iExpireLeft = span.TotalSeconds;

                if (iExpireLeft < 60)
                {

                    // header
                    var header = new { typ = "JWT", alg = "RS256" };

                    // claimset
                    var times = GetExpiryAndIssueDate();
                    var claimset = new
                    {
                        iss = loginEmail,
                        scope = "https://www.googleapis.com/auth/analytics.readonly",
                        aud = "https://accounts.google.com/o/oauth2/token",
                        iat = times[0],
                        exp = times[1],
                    };

                    // encoded header
                    var headerSerialized = JsonConvert.SerializeObject(header);
                    var headerBytes = Encoding.UTF8.GetBytes(headerSerialized);
                    var headerEncoded = Base64UrlEncode(headerBytes);

                    // encoded claimset
                    var claimsetSerialized = JsonConvert.SerializeObject(claimset);
                    var claimsetBytes = Encoding.UTF8.GetBytes(claimsetSerialized);
                    var claimsetEncoded = Base64UrlEncode(claimsetBytes);

                    // input
                    var input = headerEncoded + "." + claimsetEncoded;
                    var inputBytes = Encoding.UTF8.GetBytes(input);

                    // signiture
                    var rsa = certificate.PrivateKey as RSACryptoServiceProvider;
                    var cspParam = new CspParameters
                    {
                        KeyContainerName = rsa.CspKeyContainerInfo.KeyContainerName,
                        KeyNumber = rsa.CspKeyContainerInfo.KeyNumber == KeyNumber.Exchange ? 1 : 2
                    };
                    var aescsp = new RSACryptoServiceProvider(cspParam) { PersistKeyInCsp = false };
                    var signatureBytes = aescsp.SignData(inputBytes, "SHA256");
                    var signatureEncoded = Base64UrlEncode(signatureBytes);

                    // jwt
                    var jwt = headerEncoded + "." + claimsetEncoded + "." + signatureEncoded;

                    var client = new HttpClient();
                    var uri = "https://accounts.google.com/o/oauth2/token";
                    var post = new Dictionary<string, string>
                {
                    {"assertion", jwt},
                    {"grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer"}
                };
                    var content = new FormUrlEncodedContent(post);
                    var result = client.PostAsync(uri, content).Result;

                    RootObject values = JsonConvert.DeserializeObject<RootObject>(result.Content.ReadAsStringAsync().Result);
                    access_token = values.access_token;

                    RegistryKey key;
                    key = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\CB\" + regKeyName);
                    key.SetValue("OAuthToken", access_token);
                    key.Close();

                    key = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\CB\" + regKeyName);
                    key.SetValue("ExpireTime", DateTime.UtcNow.AddSeconds(3500).ToString("MM/dd/yyyy HH:mm:ss"));
                    key.Close();
                }


                // Create the service.
                var service = new AnalyticsService();
                ListAnalytics(service);
            }
            catch (Exception e)
            {
                Console.WriteLine(profileId + ": " + e.Message + " " + e.Source + " " + e.StackTrace);
            }
        }

        private static IAuthorizationState GetAuthorization(NativeApplicationClient arg)
        {
            IAuthorizationState state = new AuthorizationState(new[] { "https://www.googleapis.com/auth/analytics.readonly" });
            state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);
            state.AccessToken = access_token;
            string authCode = access_token;
            arg.RefreshToken(state); 
            return state;
        }

        private static void ListAnalytics(AnalyticsService service)
        {
            try
            {
                var iCount = 1;
                var iStartIndex = 1;

                while (iCount > 0 )
                {
                    var response = service.Data.Ga.Get(profileId, startDate, endDate, metrics);
                    response.Dimensions = dimensions;
                    response.MaxResults = 10000;
                    response.StartIndex = iStartIndex;
                    response.Oauth_token = access_token;
                    GaData report = response.Fetch();

                    Console.Write("ids|");

                    for (int i = 0; i <= report.ColumnHeaders.Count - 2; i++)
                    {
                        Console.Write(report.ColumnHeaders[i].Name.ToString() + "|");
                    }

                    Console.WriteLine(report.ColumnHeaders[report.ColumnHeaders.Count - 1].Name.ToString());

                    if (null != report.Rows.Count)
                    {
                        for (int i = 0; i < report.Rows.Count; i++)
                        {

                            IList<string> row = report.Rows[i];
                            Console.Write(profileId + "|");

                            for (int x = 0; x <= row.Count - 2; x++)
                            {
                                Console.Write(row[x].ToString() + "|");
                            }
                            Console.WriteLine(row[row.Count - 1].ToString());
                        }
                        //Console.ReadLine();
                        iCount = report.Rows.Count < 10000 ? 0 : 1;
                    }
                    else 
                    { 
                        iCount = 0;
                    }
                    iStartIndex += 10000;
                }
            }
            catch (Exception ex)
            {

            }
        }

                                    private static int[] GetExpiryAndIssueDate()
    {
        var utc0 = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
        var issueTime = DateTime.UtcNow;

        var iat = (int)issueTime.Subtract(utc0).TotalSeconds;
        var exp = (int)issueTime.AddMinutes(55).Subtract(utc0).TotalSeconds;

        return new[] { iat, exp };
    }

                                    private static string Base64UrlEncode(byte[] input)
    {
        var output = Convert.ToBase64String(input);
        output = output.Split('=')[0]; // Remove any trailing '='s
        output = output.Replace('+', '-'); // 62nd char of encoding
        output = output.Replace('/', '_'); // 63rd char of encoding
        return output;
    }

                            public class RootObject
    {
        public string access_token { get; set; }
        public string token_type { get; set; }
        public int expires_in { get; set; }
    }

        //public static Google.Apis.Authentication.IAuthenticator UseSavedAuthorization()
        //{

        //    var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description);
        //    provider.ClientIdentifier = "XXXXXXXXXXXXXXXXX-6ogef1100hmt92k8frqaprhfr38b4oaq.apps.googleusercontent.com";
        //    provider.ClientSecret = "XXXXXXXXXXXXXXXXXXXXXX";

        //    AuthenticatorFactory.GetInstance().RegisterAuthenticator(() => new OAuth2Authenticator(provider, GetAuthentication));

        //    OAuth2Authenticator<NativeApplicationClient> auth = new OAuth2Authenticator<NativeApplicationClient>(provider, getState);

        //    auth.LoadAccessToken();

        //    return auth;
        //}

        //public static IAuthorizationState getState(NativeApplicationClient arg)
        //{
        //    IAuthorizationState state = new AuthorizationState(new[] { AnalyticsService.Scopes.AnalyticsReadonly.ToString() });
        //    state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);

        //    state.RefreshToken = access_token;        
        //    arg.RefreshToken(state); 

        //    return state; 
        //}

    }
}
于 2012-09-26T13:52:42.250 回答