Skip to content
Advertisement

How to use Google Drive PHP Api with service account

I’ve written a series of functions to do things in Google Drive like copy folders, copy documents, get document content, etc. All of them work when I am authenticating as a particular user using OAuth. Now I have switched over to a service account to authenticate as my app, and the functions are no longer working. For intsance when I try to copy a doc, I get “File not found error” referring to the origin doc I want to copy. Again, works fine if I use OAuth. I have followed the google examples for authenticating as a service account but its not seeming to work.

Here is my code to getClient using service account:

JavaScript

And here is my copy document function

JavaScript

This returns error:

JavaScript

Again, if I use the below as my getClient function, then copy folder works just fine.

JavaScript

What is the proper way to auth as a service account???

Advertisement

Answer

From your question, I could understand that your script works. About your issue, I thought that in your situation, the following point might be the reason of your current issue.

  • The file of $origin = $originId; might be put in Google Drive of your email account.
  • And you might be trying to copy the file using the service account.

In this case, the service account cannot directly see the file on your Google Drive. Because the Drive of the service account is different from your Drive. When you want to copy the file on your Drive using the service account, for example, please share the file with the email of the service account. By this, the service account can see it and copy the file. If you can share a folder with the service account, the files in the folder can be also seen by the service account.

As the additional information, if your will use the service account to impersonate their regular account, please check domain-wide delegation as mentioned by Iamblichus’s comment.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement