Fatal error code 401 when connecting to Cloud Datastore - php

I am trying to connect to Google Cloud Datastore, using the code below. I have tried to follow these quidelines as well as these. I am using Composer and my code is in a Wordpress plugin. I have put my credentials file in the same folder as the script and it is found.
<?php # -*- coding: utf-8 -*-
/*
* Plugin Name: Cloud Datastore Connection
*/
add_shortcode( 'cd_connect', 'cloud_datastore_connection' );
use Google\Cloud\Core\ServiceBuilder;
use Google\Cloud\Datastore\DatastoreClient;
function cloud_datastore_connection( $attributes )
{
// For Composer
require 'vendor/autoload.php';
// Authenticate using keyfile data
$cloud = new ServiceBuilder([
'keyFile' => json_decode(file_get_contents('/www/.../XXX.json'), true)
]);
$datastore = new DatastoreClient(['projectId' => 'ultunaphotons']);
// Create an entity
$bob = $datastore->entity('Person');
$bob['firstName'] = 'Bob';
$bob['email'] = 'bob#example.com';
$datastore->insert($bob);
// Update the entity
$bob['email'] = 'bobV2#example.com';
$datastore->update($bob);
// testing
print bob['email'];
}
?>
I get this error message:
Fatal error: Uncaught Google\Cloud\Core\Exception\ServiceException: {
"error": { "code": 401, "message": "Request is missing required
authentication credential. Expected OAuth 2 access token, login cookie
or other valid authentication credential. See
https://developers.google.com/identity/sign-in/web/devconsole-project.",
"status": "UNAUTHENTICATED" } } in
/www/.../vendor/google/cloud-core/src/RequestWrapper.php:362
Stack trace: #0
/www/.../vendor/google/cloud-core/src/RequestWrapper.php(206): Google\Cloud\Core\RequestWrapper->convertToGoogleException(Object(GuzzleHttp\Exception\ClientException)) #1 /www/.../vendor/google/cloud-core/src/RestTrait.php(95):
Google\Cloud\Core\RequestWrapper->send(Object(GuzzleHttp\Psr7\Request),
Ar in
/www/.../vendor/google/cloud-core/src/RequestWrapper.php
on line 362
Any ideas what I'm doing wrong?

Related

Google People / Google Contacts API Failed

I'm using this library : https://github.com/rapidwebltd/php-google-people-api
here's my code :
<?php
require_once __DIR__ . '/vendor/autoload.php';
use RapidWeb\GooglePeopleAPI\GooglePeople;
use RapidWeb\GoogleOAuth2Handler\GoogleOAuth2Handler;
$clientId = '***-***.apps.googleusercontent.com';
$clientSecret = '***';
$refreshToken = '';
$scopes = ['https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/contacts',
'https://www.googleapis.com/auth/contacts.readonly'];
$googleOAuth2Handler = new GoogleOAuth2Handler($clientId, $clientSecret, $scopes, $refreshToken);
$people = new GooglePeople($googleOAuth2Handler);
$contacts = $people->all();
print_r($contacts);
?>
and I got this following error :
[fivesta1#sg21 googlecontacts]$ php create_contact.php
Fatal error: Uncaught exception 'Exception' with message '{
"error": {
"code": 401,
"message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
"status": "UNAUTHENTICATED"
}
}
' in /home/fivesta1/public_html/googlecontacts/vendor/rapidwebltd/php-google-people-api/src/GooglePeople.php:63
Stack trace:
#0 /home/fivesta1/public_html/googlecontacts/create_contact.php(16): RapidWeb\GooglePeopleAPI\GooglePeople->all()
#1 {main}
thrown in /home/fivesta1/public_html/googlecontacts/vendor/rapidwebltd/php-google-people-api/src/GooglePeople.php on line 63
what did I miss here? thank you...
I had the same error and it's because your refresh token expires. You have to run the setup again:
php vendor/rapidwebltd/php-google-oauth-2-handler/src/setup.php
And give permission to your Google Account.

TwitterOAuth: Invalid oauth_verifier parameter

I am at the stage of the OAuth flow where I get the OAuth verifier and have to use it to get the permanent token, however I encounter the error "Invalid oauth_verifier parameter".
// I get a valid oauth verifier
$oauth_verifier = filter_input(INPUT_GET, "oauth_verifier");
// I am able to run var_dump($connection) and the response seems valid
$connection = new TwitterOAuth(
$config["consumer_key"],
$config["consumer_secret"],
$_SESSION["oauth_token"],
$_SESSION["oauth_token_secret"]
);
// I believe this is where the problem lies, if I try var_dump($token) nothing shows but my original error message
$token = $connection->oauth(
"oauth/access_token", [
"oauth_verifier" => $oauth_verifier
]
);
$twitter = new TwitterOAuth(
$config["consumer_key"],
$config["consumer_secret"],
$token["oauth_token"],
$token["oauth_token_secret"]
);
The full error message is:
Fatal error: Uncaught Abraham\TwitterOAuth\TwitterOAuthException: Invalid request token. in C:\xampp\htdocs\twitteroauth-master\src\TwitterOAuth.php:158 Stack trace: #0 C:\xampp\htdocs\twitter_callback.php(34): Abraham\TwitterOAuth\TwitterOAuth->oauth('oauth/access_to...', Array) #1 {main} thrown in C:\xampp\htdocs\twitteroauth-master\src\TwitterOAuth.php on line 158
If you are running this on a local server then check your url_callback, its not be in form of google tiny url, it must be in the form of "http://localhost:80/file_name" OR "http://localhots:8080/file_name". If you still have this problem then write your throw statement in try catch block.
e.g.
try {
throw new TwitterOAuthException($result);
}
catch(Exception $e) {
}
If you are running on server in spite of always check your url_callback should not be in the form of google tiny url because new twitter oauth didn't verify your google tiny url.

Facebook App permission settings

I'm trying to post on my Facebook page with PHP.
I have set up the Facebook API (version 4) and collected all the data I need, like AppId, Secret Key, Access Token and now when I try to post on my page like this:
require 'vendor/autoload.php';
define('FACEBOOK_SDK_V4_SRC_DIR', '/vendor/facebook/php-sdk-v4/src/Facebook/');
define("FACEBOOK_CONSUMER_KEY", "{myKey}");
define("FACEBOOK_CONSUMER_SECRET", "{mySecret}");
define("FACEBOOK_ACCESS_KEY", "{myToken}");
Facebook\FacebookSession::setDefaultApplication(FACEBOOK_CONSUMER_KEY, FACEBOOK_CONSUMER_SECRET);
$session = new Facebook\FacebookSession(FACEBOOK_ACCESS_KEY);
$message = array(
"message" => "It works!",
"link" => "http://www.google.de",
//"picture" => "url to picture",
//"name" => "Picture title",
//"description" => "Description",
);
$response = ( new Facebook\FacebookRequest( $session, 'POST', '/{myPageId}/feed', $message ) )->execute()->getGraphObject();
echo $response->getProperty('id');
Unfortunately I get the following error evertime I execute it:
PHP Fatal error: Uncaught exception 'Facebook\FacebookPermissionException' with message '(#200) The user hasn't authorized the application to perform this action' in {myPath}/FacebookRequestException.php:128
Stack trace:
#0 {myPath}/FacebookRequest.php(280): Facebook\FacebookRequestException::create('{"error":{"mess...', Object(stdClass), 403)
#1 {myPath}/test.php(21): Facebook\FacebookRequest->execute()
#2 {main}
thrown in {myPath}/FacebookRequestException.php on line 128
How can I setup the Facebook App that it work correctly?
You have to do the login flow to authorize your app first. https://developers.facebook.com/docs/php/howto/example_facebook_login/4.0.0

AWS Cognito Developer Authentication in PHP

Am trying to implement developer authentication using the PHP SDK but keep getting this error:
Fatal error: Uncaught
Aws\CognitoIdentity\Exception\CognitoIdentityException: AWS Error
Code: AccessDeniedException, Status Code: 400, AWS Request ID:
da162f98-fb50-11e4-937e-0bf2642a4752, AWS Error Type: client, AWS
Error Message: User: arn:aws:iam::256661818246:user/tester is not
authorized to perform:
cognito-identity:GetOpenIdTokenForDeveloperIdentity on resource:
arn:aws:cognito-identity:us-east-1:256661818246:identitypool/us-east-1:69767873-2de2-4cc7-a78f-3d18b5e9bf71,
User-Agent: aws-sdk-php2/2.8.3 Guzzle/3.9.3 curl/7.20.0 PHP/5.3.6
thrown in
/var/www/html/aws/Aws/Common/Exception/NamespaceExceptionFactory.php
on line 91
This is my sample code:
<?php
session_start();
//Include AWS client libs
require (dirname(__DIR__).'/aws/aws-autoloader.php');
use Aws\CognitoIdentity\CognitoIdentityClient;
use Aws\Sts\StsClient;
/* Global Vars */
$aws_region = 'us-east-1';
$aws_key = '<AWS_KEY>';
$aws_secret = '<AWS_SECRET>';
$aws_account_id = '<AWS_ACCOUNT_ID>';
$identity_pool_id = 'us-east-1:xxxx-xxxx-xxxx-xxxx';
//Initialize a Cognito Identity Client using the Factory
$client = CognitoIdentityClient::factory(array('region' => $aws_region, 'key' => $aws_key, 'secret' => $aws_secret));
/* Acquire new Identity */
$identity = $client->getOpenIdTokenForDeveloperIdentity(array('IdentityPoolId' => $identity_pool_id, 'Logins' => array('login.custom.traffic' => 'jkljkasdjk')));
//Obtain Identity from response data structure
$id = $identity->get('IdentityId');
echo "IdentityId: ".$id;
?>
I suspect the error occurs while trying to get the developer Identity. What am I missing?
Reason behind this error is there might be no policy attached to the IAM user 'tester'.
You can attach an already existing policy 'AmazonCognitoDeveloperAuthenticatedIdentities' from IAM console which gives this user access to Cognito APIs including 'getOpenIdTokenForDeveloperIdentity' as well.

Fatal error: Uncaught exception 'Google_Auth_Exception' with message 'Error fetching OAuth2 access token, message: 'invalid_client''

I am developing a mobile application with googleplus login. where I get the access token and send it to my server in order to verify it using Google APIs Client Library for PHP.
When I try to authenticate the token I got a Fatal Error Saying :
Fatal error: Uncaught exception 'Google_Auth_Exception' with message 'Error fetching OAuth2 access token, message: 'invalid_client'' in C:\xxx\vendor\google\apiclient\src\Google\Auth\OAuth2.php:127 Stack trace: #0 C:\xxx\vendor\google\apiclient\src\Google\Client.php(130): Google_Auth_OAuth2->authenticate('ya29.2QBihTdAag...') #1 C:\xxx\index.php(20): Google_Client->authenticate('ya29.2QBihTdAag...') #2 {main} thrown in C:\xxx\vendor\google\apiclient\src\Google\Auth\OAuth2.php on line 127
and here is my PHP code:
<?php
$google_client_id = 'XXXXX.apps.googleusercontent.com';
$google_client_secret = 'XXXXX';
$google_redirect_url = 'xxx';
$google_developer_key = 'XXXXXXXX';
$google_application_name = 'XXXX Login';
$google_application_scope = 'email'; /* I only needed the basic user info */
$google_redirect_uri='';
//include google api files
require_once 'vendor/autoload.php';
$gClient = new Google_Client();
$gClient->setApplicationName($google_application_name);
$gClient->setClientId($google_client_id);
$gClient->setClientSecret($google_client_secret);
$gClient->setRedirectUri($google_redirect_uri);
$gClient->setScopes($google_application_scope);
$gClient->setDeveloperKey($google_developer_key);
$gClient->authenticate("ya29.2QBihTdAagwpH5hHJUg5soIETLspVUgle6VPOT52UYPWkOKyHdUJlpUyvoMKPgkuqIS4PvgXQhfpHw");//Error Happened here
$token = json_decode($gClient->getAccessToken());
$google_oauthV2 = new Google_Service_Oauth2($gClient);
$user_info = $google_oauthV2->userinfo->get();
var_dump(user_info);
die();
?>
For $google_client_secret, instead of 'notasecret' use the value in the "CLIENT SECRET" section of your "Client ID for web application".

Categories