Guest User

perl-google-sheets-get-all-values

a guest
Jul 5th, 2022
154
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 2.22 KB | None | 0 0
  1. #! /usr/bin/env perl
  2.  
  3. use feature qw(say);
  4. use strict;
  5. use warnings;
  6. use WWW::Google::Cloud::Auth::ServiceAccount;
  7. use LWP::UserAgent;
  8. use URI;
  9. use URI::Encode;
  10. use HTTP::Request;
  11. use Mojolicious::Lite;
  12. use Data::Dumper;
  13. use JSON;
  14. use experimental qw(declared_refs refaliasing signatures);
  15.  
  16. {
  17.     my @scopes = ('https://www.googleapis.com/auth/spreadsheets',
  18.                   'https://www.googleapis.com/auth/drive');
  19.     my $auth =  WWW::Google::Cloud::Auth::ServiceAccount->new(
  20.         credentials_path => 'credentials.json',
  21.         scope => join " ", @scopes
  22.     );
  23.  
  24.     get '/' => sub {
  25.         my $c = shift;
  26.         my $token = $auth->get_token();
  27.         my $sheet_id = '1FPyDuIPPzwUeLNpLbdI-RzfouKcm-2duOJ9Jio-Z-Qw';
  28.         my ($return_code, $matrix) = read_spreadsheet($token, $sheet_id);
  29.         app->log->debug(app->dumper( { matrix => $matrix } ));
  30.         $c->render(template => 'index', return_code => $return_code);
  31.     };
  32.     app->start;
  33. }
  34.  
  35. sub read_spreadsheet($token, $id) {
  36.     my $encoder = URI::Encode->new();
  37.     my $value_range = $encoder->encode("'Sheet1'");
  38.     my $url = sprintf 'https://sheets.googleapis.com/v4/spreadsheets/%s/values/%s', $id, $value_range;
  39.     my $result = send_google_drive_get_request($url, $token);
  40.     my $status_line = $result->status_line;
  41.     if (!$result->is_success) {
  42.         return $status_line;
  43.     }
  44.     my $result_hash = decode_json( $result->content );
  45.     app->log->debug(app->dumper( $result_hash ));
  46.     return $status_line, $result_hash->{values};
  47. }
  48.  
  49. sub send_google_drive_get_request( $url, $token ) {
  50.     my @headers = get_headers($token);
  51.     my $req = HTTP::Request->new('GET', $url, \@headers);
  52.     my $ua = LWP::UserAgent->new();
  53.     my $res = $ua->request($req);
  54.     return $res;
  55. }
  56.  
  57. sub get_headers($token) {
  58.     return
  59.         'User-Agent'      => 'Mozilla/8.0',
  60.         'Accept-Encoding' => 'gzip, deflate',
  61.         'Accept'          => '*/*',
  62.         'Connection'      => 'keep-alive',
  63.         "Authorization"   => "Bearer $token";
  64. }
  65.  
  66. __DATA__
  67.  
  68. @@ index.html.ep
  69. <!DOCTYPE html>
  70. <html>
  71.   <head><title>Testing access to google sheets...</title></head>
  72.   <body>
  73.     <h1>Return code = <%= $return_code %></h1>
  74.   </body>
  75. </html>
  76.  
Advertisement
Add Comment
Please, Sign In to add comment