Service Account for google sheets returns not found - service

I am trying to read a spreadsheet using a service account (I cannot use OAuth, which works, since the process will be running on a server to periodically check sheet data)
I tried several approaches. If I follow the example using oauth I can see the sheet values. However, I need the run the script without any GUI on the background.
I have found this tutorial https://github.com/juampynr/google-spreadsheet-reader
I have created a projec, service account, added viewer role, shared the spreadsheet with the service account email. Generated the key.
It seems that the test program can connect to the google services but the moment it request the spreadsheet the end result is "404 not found".
require 'vendor/autoload.php';
$service_account_file = '/secrets/readsheetmar2019-08b737d1c1cb._portfolio_test.json';
$spreadsheet_id = '1TAWybckPrnWlQxBZh0ScDsFOvftwi2dvTBNGarSdY30';
$spreadsheet_range = '';
putenv('GOOGLE_APPLICATION_CREDENTIALS=' . $service_account_file);
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->addScope(Google_Service_Sheets::SPREADSHEETS_READONLY);
$client->fetchAccessTokenWithAssertion();
$service = new Google_Service_Sheets($client);
//added by me
if ($client->isAccessTokenExpired()) {
print "expired\n";
}else{
print "not expired\n";
}
$result = $service->spreadsheets_values->get($spreadsheet_id, $spreadsheet_range);
var_dump($result->getValues());
Error:PHP Fatal error: Uncaught exception 'Google_Service_Exception' with message '
Error 404 (Not Found)!!1

When the access token retrieved by OAuth2 is used, the Spreadsheet of $spreadsheet_id = '1TAWybckPrnWlQxBZh0ScDsFOvftwi2dvTBNGarSdY30'; can retrieve the values.
When the access token retrieved by Service Account is used, Error 404 (Not Found)!!1 is returned.
If my understanding is correct, please confirm the following points.
Confirmation points:
As a test run, please set the range $spreadsheet_range = '';.
For example, it's $spreadsheet_range = 'Sheet1'.
If the error message of The caller does not have permission is returned, please confirm as follows.
Whether the Spreadsheet of 1TAWybckPrnWlQxBZh0ScDsFOvftwi2dvTBNGarSdY30 is sharing the email of Service Account.
If you didn't share the Service Account to the Spreadsheet, please share the email of client_email in the file of readsheetmar2019-08b737d1c1cb._portfolio_test.json to the Spreadsheet you want to access.
If the error message of Google Sheets API has not been used in project ### before or it is disabled. is returned, please enable Sheets API.
If this was not the solution for your issue, I apologize.

Related

Flutter App + Google Calendar API : events.insert not returning 'conferenceData'

I am following this github code as an example to create a google calendar event in a workspace calendar using a service account.
I followed various examples on how to authenticate and connect using a service account and now I am able to create an event and it shows up in the workspace calendar as well successfully.
However, the event that is returned does not have the 'conferenceData' from which I could fetch the 'conferenceId' to create the google meet link.
Below is the insert code that I use, which works but does not return the said conference data.
await calendar.events.insert(event, calendarId,
conferenceDataVersion: 1, sendUpdates: "none")
.then((value) {
print("Event Status: ${value.status}");
if (value.status == "confirmed") {
print(value.toJson().toString());
String joiningLink;
String eventId;
eventId = value.id;
joiningLink = "https://meet.google.com/${value.conferenceData?.conferenceId}";
print('Event added to Google Calendar : $joiningLink');
}
}
});
Here's the output I get printed to the console:
I/flutter ( 2934): Event Status: confirmed
I/flutter ( 2934): {created: 2022-07-26T16:12:20.000Z, creator: Instance of 'EventCreator', description: xxxx-desc, end: Instance of 'EventDateTime', etag: "3317703881666000", eventType: default, htmlLink: https://www.google.com/calendar/event?eid=djc1b2gyY3RzZ2p1YWGo4aWtmdWIydG5pZ3R2aGNvNEBn, iCalUID: v75oh2ctsgjuahtircv#google.com, id: v75oh2ctv7itndnc, kind: calendar#event, location: Google Meet, organizer: Instance of 'EventOrganizer', reminders: Instance of 'EventReminders', sequence: 0, start: Instance of 'EventDateTime', status: confirmed, summary: xxxxxxx, updated: 2022-07-26T16:12:20.833Z}
I/flutter ( 2934): Event added to Google Calendar : https://meet.google.com/null
Any suggestions on how to get the conferenceData and hence the conferenceId?
*** EDIT ****
Something else turned up while I was digging around:
While it doesn't matter for my use case, but google api won't allow me to add attendees - even if it is the service account email id.
Error creating event DetailedApiRequestError(status: 403, message:
Service accounts cannot invite attendees without Domain-Wide
Delegation of Authority.)
I don't understand, domain-wide delegation is already done for this account and that is why I am able to authenticate and create a calendar event in the first place.
Is my understanding wrong?
I found this answer that could get you in the right direction. You need to add the conferenceData.createRequest values in the insert() method in order to get a Google Meet link from the new event.
About the error related to Domain-Wide Delegation:
It is expected to get this error when the service account is not impersonating any user in the Google Workspace organization, you can review this section from Google Developers under "Delegate domain wide authority" and try to update the code in order to impersonate a different user. Looking around I found here that the optional argument that you could when using a service account in your case is impersonatedUser.

uber_rides.errors.UberIllegalState: Bad Request. Missing state parameter

I'm trying to just retrieve all my receipts amount from my Uber account and dump into excel.
I installed uber_riders and trying to do that. I have no intention of creating a website or any other business purpose. My mere purpose is just fetch trips bills and dump to excel sheet.
So in my code.
from uber_rides.auth import AuthorizationCodeGrant
auth_flow = AuthorizationCodeGrant(
"xxx",
"partner.trips",
"xxx",
"http://localhost/redirect_uri"
)
print auth_flow
auth_url = auth_flow.get_authorization_url()
session = auth_flow.get_session("http://localhost/redirect_uri")
So what should i fill in the redirect_uri ? I believe i don't need it. Can someone help me on what to do with this. I currently get uber_rides.errors.UberIllegalState: Bad Request. Missing state parameter.
I was also facing the same problem, after spending some time thinking, I found this solution:
Execute till this statement as it is:
auth_url = auth_flow.get_authorization_url()
After executing this instruction copy the auth_url and paste it into a browser.
If everything is fine, you would get to your redirected link with two parameters, 'code' and 'state', now copy this complete url along with the parameters, and use it for the get_session()
session = auth_flow.get_session(<new_url_here>)

Google Analytics Error code 403 Insufficient Permission Perl

before posting I make sure to check other similar threads.
but none has the same problem as mine.
the closest two would be:
Google Analytics PHP API "(403) Insufficient Permission"
and Google Analytics API - inconsistent error "insufficientPermissions' (403)
but there is no specific answer/solution to that thread.
and found this Python Google Analytics Management API throws error 403 Forbidden but I dont really know/understand if this is related to my issue..perhaps someone can enlighten me?
I have 2 clients, A & B. Both claimed has granted me the access to Read & Analyse
I succeed extracting data from A, but failed on B.
I believe, I have both GA Profile ID correct and no coding error (since A succeed).
To confirm that I dont use wrong GA profile ID, GA Profile ID would be 9876543 from the example below
/a12345w654321p9876543/
The error code is 403, insufficient permission for this profile.
GA error: 403 Forbidden {"error":{"errors":[{"domain":"global","reason":"insufficientPermissions","message":"User does not have sufficient permissions for this profile."}],"code":403,"message":"User does not have sufficient permissions for this profile."}} at ./ga_pp_yest.pl line 90.
Then, I tried to give access to the same account on my own website (for testing purpose).
I go to Property level and give permission Read & Analyse. (even tried changing to Account Level with Edit permission)
I still get the same error.
some of my code:
my $analytics = Net::Google::Analytics->new;
# Authenticate
my $oauth = Net::Google::Analytics::OAuth2->new(
client_id => $client_id,
client_secret => $client_secret,
);
my $token = $oauth->refresh_access_token($refresh_token);
$analytics->token($token);
$req = $analytics->new_request(
start_date => "$startDate",
end_date => "$startDate",
ids => "ga:$profile_id",
dimensions => "ga:pagePath,ga:date,ga:hour,ga:channelGrouping,ga:deviceCategory,ga:region,ga:city",
metrics => "ga:entrances",
max_results => "1000",
);
$res = $analytics->retrieve($req);
die( "GA error: " . $res->error_message ) if !$res->is_success;
I checked the token, it gave me 1 hour of access. using this link https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=accessToken
any help is greatly appreciated.
thank you very much

Accessing Firebase with 'user authentication' active using Powershell

I have created a client side app using JavaScript connected to a Firebase database where a user can login and save/edit some data stored Firebase. 'Email and Password' authentication is used as https://www.firebase.com/docs/web/guide/login/password.html
I subsequently wanted to write a Powershell script which would be setup with 'Task Scheduler' to run 1x per day, read each users data and execute some business logic.
I incorrectly expected to be able to whitelist my Server IP to get full access rights to the DB.
If I understood it correctly I need to use 'Custom authentication' using 'JSON Web Tokens (JWTs)', but there are no helper libraries available for Powershell. Had a look at this section https://www.firebase.com/docs/web/guide/login/custom.html#section-tokens-without-helpers but it's not clear to me what needs to be done to get the token.
Can someone give me some pointers or sample code on how to get JWT to work with Firebase/Powershell, or some alternate ways I can get full access to the BD using Powershell?
Thanks in advance
Quintus
I did something that might help you ...
#region TokenGenerator
function TokenGeneretor($secret){
$asm = [Reflection.Assembly]::LoadFile("D:\Firebase\FirebaseTokenGenerator.dll")
$tokenGenerator = [Firebase.TokenGenerator]::new("$secret")
$authPayload = New-Object "System.Collections.Generic.Dictionary``2[System.String,System.Object]"
$authPayload.Add('uid', '1')
$authPayload.Add('some', 'arbitrary')
$authPayload.Add('data', 'here')
$Option = [Firebase.TokenOptions]::new(((Get-Date).AddHours(1)),$null,$true)
$token = $tokenGenerator.CreateToken($authPayload, $Option)
return $token
}
#endregion
TokenGeneretor -secret "123"
The DLL mentioned is the code compiled from https://github.com/firebase/firebase-token-generator-dotNet. Just open the project in Visual Studio and have it compiled. It will play the DLL in the project's DEBUG folder.

Facebook Credits Example on App Engine?

Are there any examples of using facebook credits on Google App Engine?
I found this blog post , but it's not complete
http://blog.suinova.com/2011/01/integrating-facebook-credits-api-into.html
I got the sample runwithfriends example working on the App Engine, tried to expand it with Credits, no luck so far.
Also searched for the FB developer forums, got nothing.
Any resources you can point me to?
What's not working:
1) When I click on the "pay with Facebook" button, I get an "Application Error" , without any error code.
-Checked the javascript console
-Checked the fb app settings
-Tried on local server and production server
2) The callback.py isn't complete, because i could not parse the signed request (no code available in py for me to learn from)
3) What I basically did was to add code from Suinova Designs (link above) to the existing Run With Friends app code. Didn't turn out as expected.
my code so far:
//payment_page.html
<html>
<table>
<tr><th>Name</th><th>Price</th><th> </th></tr>
<tr><td>Something to buy</td><td>10 FC</td><td><a href="" onclick="return buyit();">
<img src="http://www.facebook.com/connect/button.php?app_id=215638625132268&feature=payments&type=light_l" />
</a></td></tr>
</table>
// javascript
function buyit(){
FB.ui({
method:'pay',
purchase_type:'item',
order_info:{
item_id:'myitem',
title:'Something to buy',
price:2,
description:'Whatever',
image_url:'http://www.facebook.com/images/gifts/21.png',
product_url:'http://www.facebook.com/images/gifts/21.png'}
},
function(resp){
if(resp.order_id) window.top.location='http://apps.facebook.com/runwithfriends trial'; else alert(resp.error_message);
});
return false;
}
//callback.py
class FacebookPaymentRequest(webapp.RequestHandler):
def post(self):
signed_request = parse_signed_request(self.request.get('signed_request'),conf.FACEBOOK_APP_SECRET)
payload = signed_request['credits'] #credits:{buyer:int,order_id:int,order_info:{},receiver:int}
order_id = payload['order_id']
method = web.request.get('method')
return_data = {'method':method}
if method == 'payments_get_items':
order_info = payload['order_info'] #order_info:{item_id:'',title:'',description:'',price:0,image_url:'',product_url:''}
item = simplejson.loads(order_info) #needs to convert JSON string to dict
#check item,price,etc and reply
return_data['content'] = [item]
elif method == 'payments_status_update':
status = payload['status']
return_data['content'] = {'status':'settled','order_id':order_id}
if status == 'placed':
#just return settled status to Facebook, this may be called twice
order_details = simplejson.loads(payload['order_details'])
#check and log here
elif status == 'settled':
order_details = simplejson.loads(payload['order_details'])
#order_details:{order_id:0,buyer:0,app:0,receiver:0,amount:0,update_time:0,time_placed:0,data:'',items:[{}],status:'placed'}
buyer = order_details['buyer']
item = order_details['items'][0]
#now save this transaction into our database
else:
#may be refunded, canceled, log the activity here
return_data['content']['status'] = status
self.response.out.write(simplejson.dumps(return_data))
Your python code looks fairly normal so I would guess that you are simply having trouble with your authorization. Depending upon how you authorize (a process a fair amount more complicated that the credits system), you are likely being given a signed request that is only partially authorized... meaning you are authorized to access only certain parts of facebook, but generally not authorized to access the active/logged-in user (i.e. me).
You can verify this by determining if you signed_request is a full 80+ characters (as opposed to around 40). Generally I try to authenticate by deciphering the profile (signed_request), if that fails then I try to use a previously stored cookie, then if that fails I try to relogin the user. I determine failure by placing try/except around my calls to get a "me" object through the GraphAPI.