Skip to content

Instantly share code, notes, and snippets.

@comewalk
Created August 29, 2012 16:42
Show Gist options
  • Select an option

  • Save comewalk/3515429 to your computer and use it in GitHub Desktop.

Select an option

Save comewalk/3515429 to your computer and use it in GitHub Desktop.
DFA Reporting API sample. Although I don't know that this script gets right results. Because I don't have my DFA account.
#!/usr/env/perl
use strict;
use warnings;
use feature qw/say/;
use FindBin;
use Google::API::Client;
use OAuth2::Client;
my $client = Google::API::Client->new;
my $service = $client->build('dfareporting', 'v1');
$service->{auth_doc}{oauth2}{scopes}{'https://www.googleapis.com/auth/devstorage.read_only'} = '';
my $auth_driver = OAuth2::Client->new({
auth_uri => 'https://accounts.google.com/o/oauth2/auth',
token_uri => 'https://accounts.google.com/o/oauth2/token',
client_id => '<YOUR CLIENT ID>',
client_secret => '<YOUR CLIENT SECRET>',
redirect_uri => 'urn:ietf:wg:oauth:2.0:oob',
auth_doc => $service->{auth_doc},
});
my $dat_file = "$FindBin::Bin/token.dat";
my $access_token = _get_or_restore_token($dat_file, $auth_driver);
# dfareporting.userProfiles.list
my $users = $service
->userProfiles
->list
->execute({ auth_driver => $auth_driver });
for my $user (@{$users->{items}}) {
my $profile_id = $user->{profileId};
# dfareporting.userProfiles.get
my $profile = $service
->userProfiles
->get(profileId => $profile_id)
->execute({ auth_driver => $auth_driver });
# dfareporting.reports.list
my $reports = $service
->reports
->list(profileId => $profile_id)
->execute({ auth_driver => $auth_driver });
for my $item (@{$reports->{items}}) {
my $report_id = $item->{id};
# dfareporting.reports.get
my $report = $service
->reports
->get(profileId => $profile_id, reportId => $report_id)
->execute({ auth_driver => $auth_driver });
# dfareporting.reports.run
my $result = $service
->reports
->run(profileId => $profile_id, reportId => $report_id)
->execute({ auth_driver => $auth_driver });
}
}
_store_token($dat_file, $auth_driver);
sub _get_or_restore_token {
my ($file, $auth_driver) = @_;
my $access_token;
if (-f $file) {
open my $fh, '<', $file;
if ($fh) {
local $/;
require JSON;
$access_token = JSON->new->decode(<$fh>);
close $fh;
}
$auth_driver->token_obj($access_token);
} else {
my $auth_url = $auth_driver->authorize_uri;
say 'Go to the following link in your browser:';
say $auth_url;
say 'Enter verification code:';
my $code = <STDIN>;
chomp $code;
$access_token = $auth_driver->exchange($code);
}
return $access_token;
}
sub _store_token {
my ($file, $auth_driver) = @_;
my $access_token = $auth_driver->token_obj;
open my $fh, '>', $file;
if ($fh) {
require JSON;
print $fh JSON->new->encode($access_token);
close $fh;
}
}
__END__
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment