Skip to content

Instantly share code, notes, and snippets.

@aanoaa
Created July 29, 2015 09:26
Show Gist options
  • Save aanoaa/46ac93f3633c57b57fe7 to your computer and use it in GitHub Desktop.
Save aanoaa/46ac93f3633c57b57fe7 to your computer and use it in GitHub Desktop.
google calendar quickAdd
use strict;
use warnings;
use Crypt::OpenSSL::RSA ();
use HTTP::Tiny;
use JSON;
use MIME::Base64 'encode_base64url';
use Path::Tiny;
sub encode_jwt {
my ( $claims, $secret ) = @_;
my $header = encode_base64url( encode_json( { alg => 'RS256', typ => 'JWT' } ) );
$claims = encode_base64url( encode_json($claims) );
my $input = join '.', $header, $claims;
my $private_key = Crypt::OpenSSL::RSA->new_private_key($secret);
$private_key->use_sha256_hash;
my $signature = encode_base64url( $private_key->sign($input) );
return join '.', $input, $signature;
}
my $ISSUER = '[email protected]'; # client_email
my $SCOPE = 'https://www.googleapis.com/auth/calendar';
my $AUDIENCE = 'https://www.googleapis.com/oauth2/v3/token';
my $GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:jwt-bearer';
my $private_key = decode_json( path('private.json')->slurp );
my $private_key_string = $private_key->{private_key};
my $time = time;
my $jwt = encode_jwt( { iss => $ISSUER, scope => $SCOPE, aud => $AUDIENCE, exp => $time + 3600, iat => $time },
$private_key_string );
my $http = HTTP::Tiny->new;
my $res = $http->post_form( "https://www.googleapis.com/oauth2/v3/token",
{ grant_type => $GRANT_TYPE, assertion => $jwt } );
die "$res->{status}: $res->{reason}\n$res->{content}" unless $res->{success};
print "Got access_token successfully\n";
my $authorized = decode_json( $res->{content} );
my $token = $authorized->{access_token};
my $token_type = $authorized->{token_type};
$res = $http->post_form(
"https://www.googleapis.com/calendar/v3/calendars/:calendarId/events/quickAdd",
{ text => 'test' },
{ headers => { authorization => "$token_type $token" } }
);
die "$res->{status}: $res->{reason}\n$res->{content}" unless $res->{success};
print "$res->{content}\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment