Showing posts with label OAuth2. Show all posts
Showing posts with label OAuth2. Show all posts

AdSense Account Stats UWP App Released

Introducing AdSenseAccountStats App

For all those AdSense account owners with Windows mobiles or tablets out there, I recently released a new UWP app that may come in handy. This simple app will allow you to quickly and easily check up on your AdSense performance.

Watch your monetization efforts pay off and your earnings grow

After logging in with your AdSense account and authorising the app for read-only access, you can easily see metrics such as:
  • Earnings Clicks, Cost Per Click
  • Page Views, Click Through Rate and RPM
  • Coverage

Code components that make it work

The app simply leverages Google APIs, specifically the AdSense Management API v1.4, and Google OAuth v2 for authentication of the user.  Basically, all calls to the AdSense APIs have to be authenticated or else they won't work.

So the first problem was to tackle Google OAuth v2 for a UWP app.  There are complexities around the Google provided libraries and support for UWP, and I have touched on these in another blog post.

OAuth v2 Authentication

The following code snippet deals with authentication successfully:

            UserCredential credential;
            try
            {
                using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
                {
                    credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                        GoogleClientSecrets.Load(stream).Secrets,
                        new[] { AdSenseService.Scope.AdsenseReadonly },
                        "user",
                        CancellationToken.None,
                        new PasswordVaultDataStore()
                        );
                }
            }
            catch (UwpCodeReceiver.AuthenticateException ex)
            {
                // Login failed or authorisation not granted
                credential = null;
                await LoginFailed(ex);
            }
            catch (Exception ex)
            {
                credential = null;
                await SomethingWrong(ex);
            }

Creating a client service for your API calls

Once the user has logged on and authenticated their AdSense account, and granted permissions to the app so it can access the user's AdSense details, you then create a client service to use for your API calls.  Pass the credential object created by the code above to the http initializer.

            var adSenseService = new AdSenseService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = "AdSense Accounts Stats",
            });

Setting up and executing an API request

After the user has logged on and allowed access for the app, the next piece is to construct a valid API request, execute it and handle the response in a meaningful way.  This can be achieved along the following lines:

            var earningsRequest = adSenseService.Reports.Generate(startString, endString);
            earningsRequest.Dimension = dimensionString;
            earningsRequest.UseTimezoneReporting = true;
            earningsRequest.Metric = new List<string>{ "earnings","page_views","individual_ad_impressions","clicks",
                                                "page_views_ctr","individual_ad_impressions_ctr",
                                                "page_views_rpm","individual_ad_impressions_rpm","cost_per_click",
                                                "ad_requests_coverage" };

            var earningsResponse = await earningsRequest.ExecuteAsync();

Once you have that response object, you can use it in any way you see fit, for example use its member items as a list source etc.

Hope you enjoyed this post and if you like go grab the app from the Microsoft Store.

Cheers

MB



Google OAuth2 for UWP C# XAML Apps Example

I have previously posted on consuming Google YouTube APIs in UWP C# XAML apps, showing how to consume Google APIs using the API key technique for authentication.

That technique works well, but has its drawbacks.  Mainly, you can't access any of the non-public user specific information that the APIs expose.  In other words, to get to the juicy bits you need to make authenticated Google API calls.  To do that, you need to work out Google OAuth2 authorisation flows.

Now, that's easier said than done if you are a part time hack like myself, and not a serious developer.  Through lack of skill I need to rely on the dotnet API libraries that Google kindly provides.  There are a good number of blog posts out there that detail the API key method, but not many that have a working example for using Google OAuth2 as per Google's developers API reference samples..

This is where this post kicks in.  But it also comes with a disclaimer (see below).  The following code snippet is an actual working example for a Google API OAuth2 authentication flow.  It uses the Google provided libraries which can readily be downloaded from Nuget and implemented in your project in Visual Studio.  Just use the Nuget Package Manager and search available packages for Google.Apis.

The magic sauce here is that the good folk at Google have fixed the OAuth flow for UWP C# only in a beta release of their dotnet libraries.  Specifically version 1.31.0 beta 01.  In the package manager, make sure to tick the box to include pre-releases, or else you won't get the beta on the list of available packages.


And here is the disclaimer... the mainstream release - currently up to 1.32.0 - does NOT work.  The code will build but fail at run time.

Enough said.  Following is the example code that will manage your Google OAuth2 authentication flow for you.  It prompts the user to log in with a Google account, authorise our example App, access the user's AdSense account, grab a list of payments for the account and finally display the results as the items source on a XAML ListView. Sounds tough?  Not really, just a few lines of code 😃

Of course, instead of accessing the AdSense Management API we could access the YouTube Data API or any of the other Google APIs presumably. I have only tested AdSense and YouTube, though.

     private async void PopulateAdsenseList()
     {
         UserCredential credential;
         using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
         {
             credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                 GoogleClientSecrets.Load(stream).Secrets,
                 new[] { AdSenseService.Scope.AdsenseReadonly },
                 "user",
                 CancellationToken.None
                 );
         }
         var adSenseService = new AdSenseService(new BaseClientService.Initializer()
         {
             HttpClientInitializer = credential,
             ApplicationName = "Your App Name",
         });
         var myPayments = adSenseService.Payments.List().Execute();
         MyList.ItemsSource = myPayments.Items;
     }

Of course you will have to have a XAML page with a ListView (in this case called "MyList") to display the retrieved list of payments.

Just remember, don't be tempted to upgrade your Google.Api Nuget packages.  Stick with the 1.31.0. beta 01 release, or your code will break!  We'll have to wait until the devs at Google fix the libraries properly for UWP support.

Hopefully the above makes sense and you enjoyed reading this post.  If you have any questions or comments, why not drop me a line via email or comment below.

Cheers

MB


Most Popular Posts