0
votes

I'm using google vision API in one of my PHP script.

Script works well when I'm executing it through the terminal:

php /var/www/html/my_script.php

But when I want to execute it from my browser I'm getting an error 500:

PHP Fatal error: Uncaught Google\Cloud\Core\Exception\ServiceException: {\n "error": {\n
"code": 401,\n "message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",\n "status": "UNAUTHENTICATED"\n }\n}\n

I don't get why the error message suggests me to use OAuth 2, I don't need my user to log to his google account.

My code is the following:

    namespace Google\Cloud\Vision\VisionClient;
    require('vendor/autoload.php');
    use Google\Cloud\Vision\VisionClient;

    $projectId = 'my_project_id';
$path = 'https://tedconfblog.files.wordpress.com/2012/08/back-to-school.jpg';

    $vision = new VisionClient([
        'projectId' => $projectId,
    ]);

    $image = $vision->image(file_get_contents($path), ['WEB_DETECTION']);
    $annotation = $vision->annotate($image);
    $web = $annotation->web();
1
It's not really saying you need OAuth 2, just some type of authentication.Difster
yeah but I'm able to connect through php command line, my python scripts are also able to connect, I just have this issue when I'm executing the php script with my browser @Difsterwoshitom
If you share the code you're using to connect, we can help determine what the issue is. Be sure to redact anything private like project ID or key file data.jdp
I'm just passing my project ID as an argument to the function VisionClientwoshitom

1 Answers

1
votes

Generally speaking, you will need to provide a service account keyfile when constructing a Google Cloud client. The exception to this is if you're running on Compute Engine, or if you have Application Default Credentials setup. Since you're seeing authentication errors, neither of those appear to be the case.

To obtain a service account and keyfile, check out the documentation.

Once you have created a service account and downloaded the json keyfile, you can provide it to the client library constructor:

<?php

use Google\Cloud\Vision\VisionClient;

$vision = new VisionClient([
    'projectId' => $projectId,
    'keyFilePath' => '/path/to/keyfile.json'
]);

Once you provide a valid keyfile, you should be able to make authenticated requests to the Vision API.

To avoid this step, you can setup Application Default Credentials on your server or computer.