Skip to content

Instantly share code, notes, and snippets.

@mash
Created December 27, 2012 10:39
Show Gist options
  • Save mash/4387258 to your computer and use it in GitHub Desktop.
Save mash/4387258 to your computer and use it in GitHub Desktop.
package Net::Admob;
use Mouse;
use LWP::UserAgent;
use JSON::XS;
use URI;
our $VERSION = 0.01;
has [ qw/email password client_key/ ] => ( is => 'rw', required => 1, );
has debug => ( is => 'rw' );
has site_id => ( is => 'rw', isa => 'Str' ); # can be set after new
has token => ( is => 'rw', isa => 'Str', lazy => 1, builder => '_fetch_token' );
has ua => ( is => 'rw', lazy => 1,
default => sub {
return LWP::UserAgent->new( agent => (__PACKAGE__ . "/$VERSION" ) );
});
has json_parser => ( is => 'rw', isa => 'CodeRef', lazy => 1,
default => sub {
my $json = JSON::XS->new;
return sub { $json->decode( shift ); };
});
use constant ENDPOINT_LOGIN => 'https://api.admob.com/v2/auth/login';
use constant ENDPOINT_STATS => 'http://api.admob.com/v2/site/stats';
no Mouse;
sub _fetch_token {
my ($self) = @_;
my $res = $self->ua->post( ENDPOINT_LOGIN, [
email => $self->email,
password => $self->password,
client_key => $self->client_key,
]);
warn ENDPOINT_LOGIN.": ".$res->content if $self->debug;
die $res->status_line unless $res->is_success;
my $obj = $self->json_parser->( $res->content );
return $obj->{ data }{ token };
}
sub revenue_between {
my ($self, $start_date, $end_date) = @_;
my $uri = URI->new( ENDPOINT_STATS );
$uri->query_form({
client_key => $self->client_key,
token => $self->token,
'site_id[]' => $self->site_id,
start_date => $start_date,
end_date => $end_date,
});
my $res = $self->ua->get( "$uri" );
warn "$uri: ".$res->content if $self->debug;
die $res->status_line unless $res->is_success;
my $obj = $self->json_parser->( $res->content );
return $obj->{ data }[ 0 ]{ revenue };
}
1;
__END__
=head1 NAME
Net::Admob - admob api client
=head1 SYNOPSIS
use Net::Admob
my $admob = Net::Admob->new(
email => 'email',
password => 'password',
client_key => 'client_key',
debug => 1, # or 0
);
$admob->site_id( 'site_id' );
warn $admob->revenue_between( $start_date => $end_date );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment