Google BigQuery API PHP Credential - php

I want to implement Google BigQuery API so I can execute query from my PHP code in BigQuery.
First I have installed the client library by following command:
composer require google/cloud
Second I have installed the Google Cloud SDK by following command:
curl https://sdk.cloud.google.com | bash
Then I run this command to create the credential:
gcloud beta auth application-default login
All the process is success and after run credential request I get the following message:
Credentials saved to file:
[/home/some/my/dir/application_default_credentials.json]
These credentials will be used by any library that requests
Application Default Credentials.
Then I want to run this code on PHP:
# Includes the autoloader for libraries installed with composer
require __DIR__ . '/vendor/autoload.php';
# Imports the Google Cloud client library
use Google\Cloud\BigQuery\BigQueryClient;
# Your Google Cloud Platform project ID
$projectId = 'PROJECT ID';
# Instantiates a client
$bigquery = new BigQueryClient([
'projectId' => $projectId
]);
# The name for the new dataset
$datasetName = 'my_new_dataset';
# Creates the new dataset
$dataset = $bigquery->createDataset($datasetName);
echo 'Dataset ' . $dataset->id() . ' created.';
But unfortunately I got following message error:
Fatal error: Uncaught exception 'Google\Cloud\Exception\ServiceException' with message 'Could not load the default credentials
So my question is: whats wrong and what must I do?
Thank you

Default credentials are provided by the Google APIs Client Library for PHP, versions 2.0.0 and newer. To use them, call useApplicationDefaultCredentials:
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
Then, use the credentials to access an API service as follows:
$client->setScopes(['https://www.googleapis.com/auth/books']);
$service = new Google_Service_Books($client);
$results = $service->volumes->listVolumes('Henry David Thoreau');
I am suggesting checking out the link I gave it has much more options and we recommend using service accounts.

Related

AWS dynamodb query from php

I have a react application and i'm trying to use aws dynamodb, i installed the php sdk but i don't know how to query my db.
I copied the tutorial here and i changed the endpoint to: "https://dynamodb.us-west-2.amazonaws.com".
I get this error: {"__type":"com.amazon.coral.service#UnrecognizedClientException","message":"The security token included in the request is invalid."}. I guess i have to add a security token somewhere, i don't know where and neither where to find it.
Any suggestion?
Based on your error, i think you need to check your aws secret key and access key. You can try to install aws cli then create user access programmatically from aws console from this link
Then you can try your source code after that.
The following code example shows how to get an item from a DynamoDB table.
// '/path/to/aws-autoloader.php' to import AWS SDKs.
require 'vendor/autoload.php';
use Aws\DynamoDb\DynamoDbClient;
use Aws\Exception\AwsException;
use Aws\DynamoDb\Exception\DynamoDbException;
// Create an SDK class used to share configuration across clients.
$sdk = new Aws\Sdk([
'region' => 'us-west-2',
'version' => 'latest'
]);
// Use an Aws\Sdk class to create the dynamoDbClient object.
$dynamoDbClient = $sdk->createDynamoDb();
try {
$dynamoDbClient->getItem([
'Key' => [
'id' => [
'N' => 1,
],
],
'TableName' => 'products',
]);
} catch (DynamoDbException $e) {
// Catch a DynamoDb-specific exception.
echo $e->getMessage();
} catch (AwsException $e) {
// This catches the more generic AwsException. You can grab information
// from the exception using methods of the exception object.
echo $e->getAwsRequestId() . "\n";
echo $e->getAwsErrorType() . "\n";
echo $e->getAwsErrorCode() . "\n";
// This dumps any modeled response data, if supported by the service
// Specific members can be accessed directly (e.g. $e['MemberName'])
var_dump($e->toArray());
}
Notice that we did not explicitly provide credentials to the client. That’s because the SDK should detect the credentials from environment variables (via AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY), an AWS credentials INI file in your HOME directory, AWS Identity and Access Management (IAM) instance profile credentials, or credential providers.
If we don’t provide a credentials option, the SDK attempts to load credentials from your environment in the following order:
Load credentials from environment variables.
Load credentials from a credentials .ini file.
Load credentials from IAM role.
We can also directly create the service-specific client object like below:
$dynamoDbClient = new DynamoDbClient(
[
'region' => 'us-west-2',
'version' => 'latest',
]
But AWS highly recommended that you use the Sdk class to create clients if you’re using multiple client instances in your application. As per AWS docs:-
The Sdk class automatically uses the same HTTP client for each SDK
client, allowing SDK clients for different services to perform
nonblocking HTTP requests. If the SDK clients don’t use the same
HTTP client, then HTTP requests sent by the SDK client might block
promise orchestration between services.
You can refer to the AWS document pages:-
AWS SDK PHP - BASIC USAGE
AWS SDK PHP - DynamoDB Examples
AWS SDK PHP - Configuration guide
AWS SDK PHP - APIs
I hope this helps.

Calling google sheets api throws errors localhost currently unable to handle this request. HTTP ERROR 500

First of all sorry for bad english. I am using Google Sheets API for my web project and I am following Google Sheets API documentation. OAuth 2.0 flow is going well and I am getting access token but when control reach the $response = $service->spreadsheets_values->get($spreadsheetId,$range); it shows localhost is currently unable to handle this request. HTTP ERROR 500. I am also using ngrok to expose my localhost to google
require_once APPPATH."third_party/googleClientLibrary/vendor/autoload.php";
session_start();
$client = new Google_Client();
$client->setAuthConfig(APPPATH."third_party/googleClientLibrary/client_secret.json");
$client->setScopes(Google_Service_Sheets::SPREADSHEETS_READONLY);
$client->setAccessType('offline');
$client->authenticate($_GET['code']);
$_SESSION['access_token']= $client->getAccessToken();
if (isset($_SESSION['access_token']))
{
$client->setAccessToken($_SESSION['access_token']);
$service = new Google_Service_Sheets($client);
$spreadsheetId = '1Wr_6u4fO7NNWHeYsdTm0S-z9UU3NtPMdwIhkrSAfEpA';
$range = 'Test-sheet!A:E';
$response = $service->spreadsheets_values->get($spreadsheetId,$range);
$values = $response->getValues();
}`
I was using php client library realease 2.4.1 and some functions of this library requires php version 7 . My php version is 5 so i used older release of client library

Google API PHP error 500

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();
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.

Amazon S3 basic action doesn't work

I'm trying to use Amazon S3 to store my images.
What I've done so far is installing the AWS SDK via PEAR (link: http://docs.aws.amazon.com/aws-sdk-php-2/guide/latest/installation.html)
Then I've gone to the second step, creating a client:
<?php
// Include the SDK using the Composer autoloader
require 'vendor/autoload.php';
use Aws\S3\S3Client;
// Instantiate the S3 client with your AWS credentials and desired AWS region
$client = S3Client::factory(array(
'key' => 'your-aws-access-key-id',
'secret' => 'your-aws-secret-access-key',
));
My keys are set correctly ... .
Then I want to test all this by creating a bucket like this:
$bucket = 'my-bucket';
try{
$result = $client->createBucket(array(
'Bucket' => $bucket
));
// Wait until the bucket is created
$client->waitUntil('BucketExists', array('Bucket' => $bucket));
}
catch(Exception $e){
var_dump($e->getMessage());
}
But I always get this error:
The requested bucket name is not available. The bucket namespace is shared by all users of the system. Please select a different name and try again.
I think my SDK isn't properly installed ... Can anyone help me with this? I'm using vagrant so I installed the AWS SDK in my root folder with this command:
sudo pear -D auto_discover=1 install pear.amazonwebservices.com/sdk
I got the message that is was installed ok.
I've also did a var_dump of my $client. The link to my response: http://pastebin.com/KqkEiKGs
Don't now if you're something with it ... (My keys are hidden)
Your error message says it - you are trying to use the name that is not unique for your bucket, you should use some more unique names. And, yes, bucket names must be unique across all of Amazon S3 (not only your account).
You can read more about it here.

HTTP 500 (Internal Server Error) when using google api php client on a remote server

I followed THIS TUTORIAL to upload a file on Google Drive with php, directly from a REMOTE SERVER: so I create new API Project from Google API Console, enable Drive API and Drive SDK services, request OAuth Client ID and Client Secret, and write them in a script, then upload it together with Google APIs Client Library for PHP folder to http://www.MYSERVER.com/script1.php, to retrieve Auth code:
<?php
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';
$drive = new Google_Client();
$drive->setClientId('XXX'); // HERE I WRITE MY Client ID
$drive->setClientSecret('XXX'); // HERE I WRITE MY Client Secret
$drive->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');
$drive->setScopes(array('https://www.googleapis.com/auth/drive'));
$gdrive = new Google_DriveService($drive);
$url = $drive->createAuthUrl();
$authorizationCode = trim(fgets(STDIN));
$token = $drive->authenticate($authorizationCode);
?>
When I visit http://www.MYSERVER.com/script1.php it run perfectly, so I allow authorization and get the Auth code that I can write in a second script. Then I upload it to http://www.MYSERVER.com/script2.php, who looks like:
<?php
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';
$drive = new Google_Client();
$drive->setClientId('X'); // HERE I WRITE MY Client ID
$drive->setClientSecret('X'); // HERE I WRITE MY Client Secret
$drive->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');
$drive->setScopes(array('https://www.googleapis.com/auth/drive'));
$gdrive = new Google_DriveService($drive);
$_GET['code']= 'X/XXX'; // HERE I WRITE AUTH CODE RETRIEVED AFTER RUNNING REMOTE script.php
file_put_contents('token.json', $drive->authenticate());
$drive->setAccessToken(file_get_contents('token.json'));
$doc = new Google_DriveFile();
$doc->setTitle('Test Drive');
$doc->setDescription('Document');
$doc->setMimeType('text/plain');
$content = file_get_contents('drive.txt');
$output = $gdrive->files->insert($doc, array(
'data' => $content,
'mimeType' => 'text/plain',
));
print_r($output);
?>
Well, now I can upload in the same folder of MYSERVER a token.json empty file (writable) and a simple drive.txt (file to upload in my Drive), but when I finally visit http://www.MYSERVER.com/script2.php browser gives everytime a HTTP 500 (Internal Server Error) and obv no file is uploaded in my Google Drive: there are errors in the steps, or some issue with the scripts? Please help me to resolve this!
EDIT:
MYSERVER error log is full of:
PHP Fatal error: Uncaught exception 'Google_AuthException' with message 'Error fetching OAuth2 access token, message: 'invalid_grant'' in /var/www/vhosts/.../gdrive/google-api-php-client/src/auth/Google_OAuth2.php:113
Stack trace:
#0 /var/www/vhosts/.../gdrive/google-api-php-client/src/Google_Client.php(131): Google_OAuth2->authenticate(Array, NULL)
#1 /var/www/vhosts/.../gdrive/sample2.php(23): Google_Client->authenticate()
#2 {main}
thrown in /var/www/vhosts/.../gdrive/google-api-php-client/src/auth/Google_OAuth2.php on line 113
it seems that you cannot get new access token because your old one has not expired yet, that is what's this code is telling you :
'Google_AuthException' with message 'Error fetching OAuth2 access token, message: 'invalid_grant'
You must get the access token ONCE, save it somewhere and use it until it expires, you can not get new access token each time you try to query something
to revoke your first access token go to Google API Console and you will find it under Client ID for installed applications
Best Regards

Categories