API-Google
view release on metacpan or search on metacpan
lib/API/Google.pm view on Meta::CPAN
$tx = $self->{ua}->build_tx(uc $http_method => $params->{route} => $headers);
} elsif (($http_method eq 'post') && $params->{payload}) {
$tx = $self->{ua}->build_tx(uc $http_method => $params->{route} => $headers => json => $params->{payload})
} else {
die 'wrong http_method on no payload if using POST';
}
return $tx;
}
sub api_query {
my ($self, $params, $payload) = @_;
warn "api_query() params : ".Dumper $params if $self->{debug};
$payload = { payload => $payload };
%$params = (%$params, %$payload);
my $tx = $self->build_http_transaction($params);
my $res = $self->{ua}->start($tx)->res->json;
# for future:
# if ( grep { $_->{message} eq 'Invalid Credentials' && $_->{reason} eq 'authError'} @{$res->{error}{errors}} ) { ... }
warn "First api_query() result : ".Dumper $res if $self->{debug};
if (defined $res->{error}) { # token expired error handling
my $attempt = 1;
while ($res->{error}{message} eq 'Invalid Credentials') {
if ($attempt == $self->{max_refresh_attempts}) {
last;
}
warn "Seems like access_token was expired. Attemptimg update it automatically ..." if $self->{debug};
$self->refresh_access_token_silent($params->{user});
$tx = $self->build_http_transaction($params);
$res = $self->{ua}->start($tx)->res->json;
$attempt++;
}
if ($attempt > 1) {
warn "access_token was automatically refreshed";
}
}
return $res;
};
1;
__END__
=pod
=encoding UTF-8
=head1 NAME
API::Google - Perl library for easy access to Google services via their API
=head1 VERSION
version 0.12
=head1 SYNOPSIS
use API::Google;
my $gapi = API::Google->new({ tokensfile => 'config.json' });
$gapi->refresh_access_token_silent('someuser@gmail.com');
$gapi->api_query({
method => 'post',
route => 'https://www.googleapis.com/calendar/v3/calendars/'.$calendar_id.'/events',
user => 'someuser@gmail.com'
}, $json_payload_if_post);
=head1 CONFIGURATION
config.json must be structured like:
{ "gapi":
{
"client_id": "001122334455-abcdefghijklmnopqrstuvwxyz012345.apps.googleusercontent.com",
"client_secret": "1ayL76NlEKjj85eZOipFZkyM",
"tokens": {
"email_1@gmail.com": {
"refresh_token": "1/cI5jWSVnsUyCbasCQpDmz8uhQyfnWWphxvb1ST3oTHE",
"access_token": "ya29.Ci-KA8aJYEAyZoxkMsYbbU9H_zj2t9-7u1aKUtrOtak3pDhJvCEPIdkW-xg2lRQdrA"
},
"email_2@gmail.com": {
"access_token": "ya29.Ci-KAzT9JpaPriZ-ugON4FnANBXZexTZOz-E6U4M-hjplbIcMYpTbo0AmGV__tV5FA",
"refresh_token": "1/_37lsRFSRaUJkAAAuJIRXRUueft5eLWaIsJ0lkJmEMU"
}
}
}
}
=head1 SUBROUTINES/METHODS
=head2 refresh_access_token_silent
Get new access token for user from Google API server and store it in jsonfile
=head2 build_headers
Keep access_token in headers always actual
$gapi->build_http_transactio($user);
=head2 build_http_transaction
$gapi->build_http_transaction({
user => 'someuser@gmail.com',
method => 'post',
( run in 1.435 second using v1.01-cache-2.11-cpan-0bd6704ced7 )