0
  1. Im using Google Analytics API to show google analytics data, but I am getting invalid credential error at the line AccountFeed accountFeed = service.Query(query);
  2. Is gmail username and password and Google Analytics credentials same ?
  3. what credentials have to pass in AccountFeed accountFeed = service.Query(query);

Code:

public partial class _Default : System.Web.UI.Page
{
    Int32 _intVisists = 0;
    Int32 _intPageViewVisit = 0;
    protected void Page_Load(object sender, EventArgs e)
    {
        RefreshFeed();
}
private void RefreshFeed()
{

    string userName = "xyz@gmail.com";
    string passWord = "xyz";
    string gkey = "AIzaSfafaG_JUzUqkKsPd0-mPBZO4GrDF1hbbbb";
     string dataFeedUrl = "https://www.google.com/analytics/feeds/data" + gkey;


    AccountQuery query = new AccountQuery();

    AnalyticsService service = new AnalyticsService(AnalyticsService.GAnalyticsService);
    if (!string.IsNullOrEmpty(userName))
    {
        service.setUserCredentials(userName, passWord);
    }
    string str = "";
    AccountFeed accountFeed = service.Query(query);
    foreach (AccountEntry entry in accountFeed.Entries)
    {
        str = entry.ProfileId.Value;
    }


    DataQuery query1 = new DataQuery(dataFeedUrl);

    query1.Ids = str;
    query1.Metrics = "ga:visits,ga:bounces";
    query1.Sort = "ga:visits";
    query1.GAStartDate = DateTime.Now.AddMonths(-1).AddDays(-2).ToString("yyyy-MM-dd");
    query1.GAEndDate = DateTime.Now.AddDays(-3).ToString("yyyy-MM-dd");
    query1.StartIndex = 1;

    int cnt = 0;
    double incntDone = 0.0;
    DataFeed dataFeed11 = service.Query(query1);
    foreach (DataEntry entry in dataFeed11.Entries)
    {
        string st = entry.Title.Text;
        string ss = entry.Metrics[0].Value;


        string _str = DisplayPercentage(double.Parse(entry.Metrics[1].Value) / int.Parse(entry.Metrics[0].Value));
        double incnt = double.Parse(entry.Metrics[1].Value) / double.Parse(entry.Metrics[0].Value);
        incntDone = Math.Round(incnt * 100, 2);
        cnt = cnt + int.Parse(ss);

    }
    Response.Write("Bounce Rate : " + incntDone + "<br/>");


    query1.Ids = str;
    query1.Metrics = "ga:pageviews";
    query1.Sort = "ga:pageviews";
    query1.GAStartDate = DateTime.Now.AddMonths(-1).AddDays(-2).ToString("yyyy-MM-dd");
    query1.GAEndDate = DateTime.Now.AddDays(-3).ToString("yyyy-MM-dd");

    DataFeed dataFeedpageviews = service.Query(query1);
    foreach (DataEntry entry in dataFeedpageviews.Entries)
    {
        string st = entry.Title.Text;
        string ss = entry.Metrics[0].Value;
        _intPageViewVisit = Int32.Parse(ss);
        Response.Write("<br/>");
        Response.Write("Total PageView : " + ss);
        Response.Write("<br/>");
    }


    query1.Ids = str;
    query1.Metrics = "ga:visits";//visitors
    query1.Sort = "ga:visits";
    query1.GAStartDate = DateTime.Now.AddMonths(-1).AddDays(-2).ToString("yyyy-MM-dd");
    query1.GAEndDate = DateTime.Now.AddDays(-3).ToString("yyyy-MM-dd");
    query1.StartIndex = 1;
    DataFeed dataFeedVisits = service.Query(query1);
    foreach (DataEntry entry in dataFeedVisits.Entries)
    {
        string st = entry.Title.Text;
        string ss = entry.Metrics[0].Value;
        _intVisists = Int32.Parse(ss);
        Response.Write("<br/>");
        Response.Write("Total Visits : " + ss);
        Response.Write("<br/>");
    }

enter image description here

Linda Lawton - DaImTo
  • 106,405
  • 32
  • 180
  • 449

1 Answers1

2
  1. invalid credential error means that you are not authenticating correctly. Google Analytics API requires either Oauth2 or a service account Authentication. You appear to be trying to login using a Login and Password, this is called Client login which does not work with the Google Analytics API
  2. No Gmail username are not valid Google Analytics Credentials.
  3. You should be passing it a valid UserCredential

Login Example:

/// <summary>
        /// Authenticate to Google Using Oauth2
        /// Documentation https://developers.google.com/accounts/docs/OAuth2
        /// </summary>
        /// <param name="clientId">From Google Developer console https://console.developers.google.com</param>
        /// <param name="clientSecret">From Google Developer console https://console.developers.google.com</param>
        /// <param name="userName">A string used to identify a user.</param>
        /// <returns></returns>
        public static AnalyticsService AuthenticateOauth(string clientId, string clientSecret, string userName)
        {

            string[] scopes = new string[] { AnalyticsService.Scope.Analytics,  // view and manage your analytics data
                                             AnalyticsService.Scope.AnalyticsEdit,  // edit management actives
                                             AnalyticsService.Scope.AnalyticsManageUsers,   // manage users
                                             AnalyticsService.Scope.AnalyticsReadonly};     // View analytics data

            try
            {
                // here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
                UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = clientId, ClientSecret = clientSecret }
                                                                                             , scopes
                                                                                             , userName
                                                                                             , CancellationToken.None
                                                                                             , new FileDataStore("Daimto.GoogleAnalytics.Auth.Store")).Result;

                AnalyticsService service = new AnalyticsService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Analytics API Sample",
                });
                return service;
            }
            catch (Exception ex)
            {

                Console.WriteLine(ex.InnerException);
                return null;

            }

        }

Code ripped from the Google Analytics .net sample project

Linda Lawton - DaImTo
  • 106,405
  • 32
  • 180
  • 449
  • lol. i was reading your blog just now on analytics api and the original question was confusing me. you need a service account right? – naveen Mar 02 '15 at 12:40
  • That hunk of code is for Oauth2. I am still not 100% sure what the person asking the question is trying to do. It may be better that they go with a service account. – Linda Lawton - DaImTo Mar 02 '15 at 12:42
  • i have seen some code written where one access google api with his gmail credentials. I am searching for it. is that still possible in v3? – naveen Mar 02 '15 at 12:44
  • Not if you are using V3 of the api. I wouldn't bother with that code at all At the end of April Google shuts down client login. Anyone still using it at that time will be up a creak with out credentials. – Linda Lawton - DaImTo Mar 02 '15 at 12:45
  • I am asking doubts on another person question. last one. so, client login is what Kikkiri's program is trying to do and even if works now, it wont be working in a month? – naveen Mar 02 '15 at 12:48
  • You are correct, but I honestly don't think it will work. Google .net client lib supports V3 of the Analytics API not V2 and V3 doesn't support client login. – Linda Lawton - DaImTo Mar 02 '15 at 12:50