Use Google Analytics API to show information in C#

后端 未结 7 1407
难免孤独
难免孤独 2020-12-02 05:07

I been looking for a good solution all day but google evolve so fast that I can\'t find something working. What I want to do is that, I have a Web app that has an admin sect

7条回答
  •  孤城傲影
    2020-12-02 05:57

    Hope google will provide proper documentation someday. Here I am listing all the steps to integrate google analytics server side authentication in ASP.NET C#.

    Step 1: Create a project in google console

    Goto the link https://console.developers.google.com/iam-admin/projects and create a project by clicking on "Create Project" button and provide project name in the pop up window and submit it.

    Step 2: Create credentials and service account

    After creation of the project, you will be redirected to "API Manager" page. Click on credentials and press "Create Credentials" button. select "service account key" from dropdown you will be redirected to next page. In the service account drop down, select "New service account". Fill in the service account name and download the p12 key. It will have p12 extension. you will get a popup having a password "notasecret" which is default and your private key will be downloaded.

    Step 3: Create 0auth client ID

    click on the "create credentials" dropdown and select "0auth client ID" you will be redirected to "0auth consent screen" tab. provide a random name in the project name textbox. select application type as "Web application" and click create button. Copy the generated client ID in a notepad.

    Step 4: Enable the APIs

    On the left side click on the "Overview" tab and select "Enabled APIs" from the horizontal tab. In the search bar search for "Analytics API" click on the dropdown and press "Enable" button. Now again search for "Analytics Reporting V4" and enable it.

    Step 5: Install nuget packages

    In visual studio, Go to Tools > Nuget Package Manager > Package Manager Console. Copy paste the below code in the console to install the nuget packages.

    Install-Package Google.Apis.Analytics.v3

    Install-Package DotNetOpenAuth.Core -Version 4.3.4.13329

    The above two packages are Google analytics and DotNetOpenAuth nuget packages.

    Step 6: Provide 'View and Analyze' permission to service account

    Go to google analytics account and click on "Admin" tab and select "User Management" from left menus,select a domain of which you want to access analytics data and insert the service account email id under it and select "Read and Analyze" permission from the dropdown. Service account email id looks like ex: googleanalytics@googleanalytics.iam.gserviceaccount.com.

    Working Code

    FRONT END CODE:

    Copy and paste the below analytics embed script in your front end or else you can get this code from google analytics documentation page also.

     
    

    Paste the below code in the body tag of your front end page.

     
    

    You can also get your View ID from https://ga-dev-tools.appspot.com/account-explorer/

    BACK END CODE:

     using System;
        using System.Linq;
        using System.Collections.Generic;
        using System.Collections.Specialized;
        using System.Web.Script.Serialization;
        using System.Net;
        using System.Text;
        using Google.Apis.Analytics.v3;
        using Google.Apis.Analytics.v3.Data;
        using Google.Apis.Services;
        using System.Security.Cryptography.X509Certificates;
        using Google.Apis.Auth.OAuth2;
        using Google.Apis.Util;
        using DotNetOpenAuth.OAuth2;
        using System.Security.Cryptography;
    
        namespace googleAnalytics
        {
            public partial class api : System.Web.UI.Page
            {
                public const string SCOPE_ANALYTICS_READONLY = "https://www.googleapis.com/auth/analytics.readonly";
    
                string ServiceAccountUser = "googleanalytics@googleanalytics.iam.gserviceaccount.com"; //service account email ID
                string keyFile = @"D:\key.p12"; //file link to downloaded key with p12 extension
                protected void Page_Load(object sender, EventArgs e)
                {
    
                   string Token = Convert.ToString(GetAccessToken(ServiceAccountUser, keyFile, SCOPE_ANALYTICS_READONLY));
    
                   accessToken.Value = Token;
    
                    var certificate = new X509Certificate2(keyFile, "notasecret", X509KeyStorageFlags.Exportable);
    
                    var credentials = new ServiceAccountCredential(
    
                        new ServiceAccountCredential.Initializer(ServiceAccountUser)
                        {
                            Scopes = new[] { AnalyticsService.Scope.AnalyticsReadonly }
                        }.FromCertificate(certificate));
    
                    var service = new AnalyticsService(new BaseClientService.Initializer()
                    {
                        HttpClientInitializer = credentials,
                        ApplicationName = "Google Analytics API"
                    });
    
                    string profileId = "ga:53861036";
                    string startDate = "2016-04-01";
                    string endDate = "2016-04-30";
                    string metrics = "ga:sessions,ga:users,ga:pageviews,ga:bounceRate,ga:visits";
    
                    DataResource.GaResource.GetRequest request = service.Data.Ga.Get(profileId, startDate, endDate, metrics);
    
    
                    GaData data = request.Execute();
                    List ColumnName = new List();
                    foreach (var h in data.ColumnHeaders)
                    {
                        ColumnName.Add(h.Name);
                    }
    
    
                    List values = new List();
                    foreach (var row in data.Rows)
                    {
                        foreach (var item in row)
                        {
                            values.Add(Convert.ToDouble(item));
                        }
    
                    }
                    values[3] = Math.Truncate(100 * values[3]) / 100;
    
                    txtSession.Text = values[0].ToString();
                    txtUsers.Text = values[1].ToString();
                    txtPageViews.Text = values[2].ToString();
                    txtBounceRate.Text = values[3].ToString();
                    txtVisits.Text = values[4].ToString();
    
                }
    
    
             public static dynamic GetAccessToken(string clientIdEMail, string keyFilePath, string scope)
            {
                // certificate
                var certificate = new X509Certificate2(keyFilePath, "notasecret");
    
                // header
                var header = new { typ = "JWT", alg = "RS256" };
    
                // claimset
                var times = GetExpiryAndIssueDate();
                var claimset = new
                {
                    iss = clientIdEMail,
                    scope = scope,
                    aud = "https://accounts.google.com/o/oauth2/token",
                    iat = times[0],
                    exp = times[1],
                };
    
                JavaScriptSerializer ser = new JavaScriptSerializer();
    
                // encoded header
                var headerSerialized = ser.Serialize(header);
                var headerBytes = Encoding.UTF8.GetBytes(headerSerialized);
                var headerEncoded = Convert.ToBase64String(headerBytes);
    
                // encoded claimset
                var claimsetSerialized = ser.Serialize(claimset);
                var claimsetBytes = Encoding.UTF8.GetBytes(claimsetSerialized);
                var claimsetEncoded = Convert.ToBase64String(claimsetBytes);
    
                // input
                var input = headerEncoded + "." + claimsetEncoded;
                var inputBytes = Encoding.UTF8.GetBytes(input);
    
                // signature
                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 = Convert.ToBase64String(signatureBytes);
    
                // jwt
                var jwt = headerEncoded + "." + claimsetEncoded + "." + signatureEncoded;
    
                var client = new WebClient();
                client.Encoding = Encoding.UTF8;
                var uri = "https://accounts.google.com/o/oauth2/token";
                var content = new NameValueCollection();
    
                content["assertion"] = jwt;
                content["grant_type"] = "urn:ietf:params:oauth:grant-type:jwt-bearer";
    
                string response = Encoding.UTF8.GetString(client.UploadValues(uri, "POST", content));
    
    
                var result = ser.Deserialize(response);
    
                object pulledObject = null;
    
                string token = "access_token";
                if (result.ContainsKey(token))
                {
                    pulledObject = result[token];
                }
    
    
                //return result;
                return pulledObject;
            }
    
            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 };
            }
    
            }
        }
    

提交回复
热议问题