facebook google oauth Uncaught exception - php

I integrated both google and facebook oauth in my application .
First I initiated the class for google like this
$client = new Google_Client();
$client->setApplicationName("urmk google login");
$oauth2 = new Google_Oauth2Service($client);
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
return;
}
Google login process is working fine and i am able to get user info too. But
Then I integrated facebook oauth
FacebookSession::setDefaultApplication('APP_ID', 'APP_SECRET');
$helper = new FacebookRedirectLoginHelper('http://example.com/');
$loginUrl = $helper->getLoginUrl();
try {
$session = $helper->getSessionFromRedirect();
} catch(FacebookRequestException $ex) {
// When Facebook returns an error
} catch(\Exception $ex) {
// When validation fails or other local issues
}
if ($session) {
// Logged in
$user = $facebook->getUser();
if ($user) {
try {
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl();
}
}
It successfully takes me to user account where it ask for the user permission, but while redirecting to my SITE it throws an error saying
Fatal error: Uncaught exception 'Google_AuthException' with message
'Error fetching OAuth2 access token, message: 'invalid_grant'' in
C:\xampp\htdocs\urmk\lib\src\auth\Google_OAuth2.php:113 Stack trace:
#0 C:\xampp\htdocs\urmk\lib\src\Google_Client.php(131):
Google_OAuth2->authenticate(Array, 'AQASSzhhLhYIYxI...') #1
C:\xampp\htdocs\urmk\index.php(66):
Google_Client->authenticate('AQASSzhhLhYIYxI...') #2 {main} thrown in
C:\xampp\htdocs\urmk\lib\src\auth\Google_OAuth2.php on line 113**
And again if i change the if (isset($_GET['code'])) to if (isset($_GET['something else'])) . It works fine. So how to resolve this error. Any help would be appreciated.

I believe the problem is that you have parameters in the 'authenticate' function call. From what I saw in the Google code for 'Google_OAuth2.php', it calls it itself. You will need to make sure that you set the variables. Check out the code below.
Also make sure you are using the correct version of the Google code... Online vs. Installed. I read that Installed version is Native.
if(isset($_GET['code']))
{
$client->authenticate();
$_SESSION['access_token'] = $client->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}
You can set the access token by...
if(isset($_SESSION['access_token']))
{
$client->setAccessToken($_SESSION['access_token']);
}
If all else fails then read this document...
http://25labs.com/tutorial-implementing-google-api-using-oauth-2-0-in-php/
Also, catch the exception so you can at least get one or the other as a successful authentication rather than erroring out all together.

Related

Uncaught Google_Auth_Exception: Error fetching OAuth2 access token, message: 'invalid_client: Unauthorized'

can someone help me because I get an error when trying to link my APP with Google Calendar.
I get the error :
Fatal error: Uncaught Google_Auth_Exception: Error fetching OAuth2 access token, message: 'invalid_client: Unauthorized' in /web/htdocs/www.assiweb.cloud/home/MyProject/Google/Auth/OAuth2.php:132
Stack trace:
#0 /web/htdocs/www.assiweb.cloud/home/MyProject/Google/Client.php(128): Google_Auth_OAuth2->authenticate('4/0AX4XfWiN-UCy...', false)
#1 /web/htdocs/www.assiweb.cloud/home/MyProject/includes/Calendar.php(24): Google_Client->authenticate('4/0AX4XfWiN-UCy...').
the code on Client when I am getting error is:
public function authenticate($code, $crossClient )
{
$this->authenticated = true;
return $this->getAuth()->authenticate($code, $crossClient);
}
and the code where I am getting error in Calendar.php (line 24 ) is:
$client->authenticate($_GET['code'],true);
These lines of code are not written by me,but i have to resolve this problem and i not know much from Google OAuth,,can someone help me how to resolve it or give me a full working code how to link my app with google account for using then the calendar.
It sounds like your not properly applying your authorization to the client. Try checking this.
Oauth2callback.php
require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/Oauth2Authentication.php';
// Start a session to persist credentials.
session_start();
// Handle authorization flow from the server.
if (! isset($_GET['code'])) {
$client = buildClient();
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
$client = buildClient();
$client->authenticate($_GET['code']); // Exchange the authencation code for a refresh token and access token.
// Add access token and refresh token to seession.
$_SESSION['access_token'] = $client->getAccessToken();
$_SESSION['refresh_token'] = $client->getRefreshToken();
//Redirect back to main script
$redirect_uri = str_replace("oauth2callback.php",$_SESSION['mainScript'],$client->getRedirectUri());
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
Oauth2Authentication.php
function getOauth2Client() {
try {
$client = buildClient();
// Set the refresh token on the client.
if (isset($_SESSION['refresh_token']) && $_SESSION['refresh_token']) {
$client->refreshToken($_SESSION['refresh_token']);
}
// If the user has already authorized this app then get an access token
// else redirect to ask the user to authorize access to Google Analytics.
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
// Set the access token on the client.
$client->setAccessToken($_SESSION['access_token']);
// Refresh the access token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
$client->setAccessToken($client->getAccessToken());
$_SESSION['access_token'] = $client->getAccessToken();
}
return $client;
} else {
// We do not have access request access.
header('Location: ' . filter_var( $client->getRedirectUri(), FILTER_SANITIZE_URL));
}
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}

Facebook Ad API PHP : Invalid OAuth access token

I am working on the Facebook Ads API and I am totally new for this. I am getting an error to fetch the Ads account. The error is Invalid OAuth access token. After getting this error I came to google and searched a lot like
First Link Another one another one. But didn't find any solution so I decided to come to Stackoverflow so this question is not duplicate
Here is the code how I used the Facebook Ads API
public function login() {
$helper = $this->facebook->getRedirectLoginHelper();
$this->request->session()->write('fb_access_token', false);
$access_token = $this->request->session()->read('fb_access_token');
if ($access_token) {
echo "You are logged in!";
} else {
$permissions = ['email', 'ads_management', 'pages_show_list', 'publish_pages', 'manage_pages', 'ads_read'];
$loginUrl = $helper->getLoginUrl('http://localhost/FacebookManager/Adsmanagement/authenticate', $permissions);
echo 'Log in with Facebook';
}
}
public function authenticate() {
if (isset($_GET['state'])) {
$helper = $this->facebook->getRedirectLoginHelper();
$helper->getPersistentDataHandler()->set('state', $_GET['state']);
$accessToken = $helper->getAccessToken();
if($accessToken) {
echo "got the token";
$this->request->session()->write('fb_access_token', $accessToken);
//echo $accessToken;
$oAuth2Client = $this->facebook->getOAuth2Client();
$longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
$this->facebook->setDefaultAccessToken($longLivedAccessToken);
}
}
}
And I am getting the adaccount like this
public function getAdsAccount() {
$accesstoken = $this->request->session()->read('fb_access_token');
//$accesstoken = "AQwfmuNgKZCZCiZBuhAMGB8xZBty5dgNR7J9ZBO2ZCDl1SWYxnBLn9ahIn5FQTWxkJ0FPKbemeG0vUAwPsZCN2FFxOFey9BQr8CZBW07IwlZB0FK81SH8ozOil2GllR35BCyxQGhQ7JrtuCdNE6kjEOU0FZCAZDZD";
Api::init(
$this->app_id, // App ID
$this->appsecret,
$accesstoken // Your user access token
);
//*****************
$account = new AdAccount('****************');
$contracts = $account->read();
echo "<pre>"; print_r($contracts->getData());
}
So I am using a developer account, Trying to fetch this with the facebook test user from the APP dashboard-> Roles->Test User. I am setting the proper permissions etc. Don't know where I am wrong.
Update
Now the issue is if I create access token from Graph Explorar It works but if i create with SDK its giving me the error "invalid aouth Tokan"
Please help me. Thanks in advance.
Hello #manoj Kumar Please check with below URL with administrator login for app debug your AccessToken.
https://developers.facebook.com/tools/explorer/
Please check below code from facebook PHP SDK for getting the valid access token with permission ads_management.
require_once __DIR__ . '/vendor/autoload.php';
use Facebook\Facebook;
use Facebook\Exceptions\FacebookResponseException;
use Facebook\Exceptions\FacebookSDKException;
// Init PHP Sessions
session_start();
$fb = new Facebook([
'app_id' => '{your-app-id}',
'app_secret' => '{your-app-secret}',
]);
$helper = $fb->getRedirectLoginHelper();
if (!isset($_SESSION['facebook_access_token'])) {
$_SESSION['facebook_access_token'] = null;
}
if (!$_SESSION['facebook_access_token']) {
$helper = $fb->getRedirectLoginHelper();
try {
$_SESSION['facebook_access_token'] = (string) $helper->getAccessToken();
} catch(FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
}
if ($_SESSION['facebook_access_token']) {
echo "You are logged in!";
} else {
$permissions = ['ads_management'];
$loginUrl = $helper->getLoginUrl('http://localhost:8888/marketing-api/', $permissions);
echo 'Log in with Facebook';
}
After that, You have to get AdAccount so use below code
use FacebookAds\Object\AdUser;
// Add after Api::init()
$me = new AdUser('me');
$my_adaccount = $me->getAdAccounts()->current();
It was actually my mistake. Facebook API return us an protect object. If you print the variable it will display it as string.
<?php
echo $longLivedAccessToken;
var_dump($longLivedAccessToken);
?>
The output is something like
I tried $longLivedAccessToken->getValue();
$oAuth2Client = $this->facebook->getOAuth2Client();
$longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
$accesstoken = $longLivedAccessToken->getValue();
$this->request->session()->write('fb_access_token', $accesstoken);
$this->facebook->setDefaultAccessToken($longLivedAccessToken);

error on listing all files using google drive api in php

I am working on google drive api by using PHP. I am facing an error while using this drive api. I am using google api client library "google/apiclient ^2.0". I am trying to user login with google authentication and view all files available in drive for this purpose, i am using this library but it's showing error:
Notice: Undefined property: Google_Client::$files in
/Applications/XAMPP/xamppfiles/htdocs/google_app/index.php on line 31
Fatal error: Uncaught Error: Call to a member function listFiles() on
null in /Applications/XAMPP/xamppfiles/htdocs/google_app/index.php:31
Stack trace: #0
/Applications/XAMPP/xamppfiles/htdocs/google_app/index.php(55):
retrieveAllFiles(Object(Google_Client)) #1 {main} thrown in
/Applications/XAMPP/xamppfiles/htdocs/google_app/index.php on line 31
include_once 'vendor/autoload.php';
function retrieveAllFiles($service) {
$result = array();
$pageToken = NULL;
do {
try {
$parameters = array();
if ($pageToken) {
$parameters['pageToken'] = $pageToken;
}
$files = $service->files->listFiles($parameters);
$result = array_merge($result, $files->getItems());
$pageToken = $files->getNextPageToken();
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
$pageToken = NULL;
}
} while ($pageToken);
return $result;
}
$client = new Google_Client();
$client->setAuthConfig('client_secrets.json');
$client->setAccessType("offline"); // offline access
//$client->setIncludeGrantedScopes(true); // incremental auth
$client->addScope(Google_Service_Drive::DRIVE_METADATA_READONLY);
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
$client->setRedirectUri($redirect_uri);
if (isset($_GET['code'])) {
$token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
}
$service = new Google_service_Device();
echo retrieveAllFiles($service );
Actually i am trying to retrieve all files in my google drive with my file id and after that set status auto publish of specific files. Please help me to get rid of this error.
Thanks in advance.
"Daily limit for unauthenticated Use Exceeded"
Means that you are making a request without properly authenticating your script. there is probably something up with your fetchAccessTokenWithAuthCode.
You might consider something long these lines
function getOauth2Client() {
try {
$client = buildClient();
// Set the refresh token on the client.
if (isset($_SESSION['refresh_token']) && $_SESSION['refresh_token']) {
$client->refreshToken($_SESSION['refresh_token']);
}
// If the user has already authorized this app then get an access token
// else redirect to ask the user to authorize access to Google Analytics.
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
// Set the access token on the client.
$client->setAccessToken($_SESSION['access_token']);
// Refresh the access token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
$client->setAccessToken($client->getAccessToken());
$_SESSION['access_token'] = $client->getAccessToken();
}
return $client;
} else {
// We do not have access request access.
header('Location: ' . filter_var( $client->getRedirectUri(), FILTER_SANITIZE_URL));
}
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}
Code ripped from my sample project oauth2php
Undefined property Google_Client
Means you havent properly declared the google client
Uncaught Error: Call to a member function listFiles() on null in
what happens if you remove $parameters and just call $service->files->listFiles();

'Invalid OAuth access token' while getting adAccount detail.

I am using FB Ads API, following steps described in documentation and created my PHP file as bellow. It gives me
Fatal error: Uncaught exception 'FacebookAds\Http\Exception\AuthorizationException' with message 'Invalid OAuth access token.' in /project/root/vendor/facebook/php-ads-sdk/src/FacebookAds/Http/Exception/RequestException.php on line 137
and
FacebookAds\Http\Exception\AuthorizationException: Invalid OAuth access token. in /project/root/vendor/facebook/php-ads-sdk/src/FacebookAds/Http/Exception/RequestException.php on line 137
My PHP code snippet is
<?php
require_once DIR . '/vendor/autoload.php';
use Facebook\Facebook;
use Facebook\Exceptions\FacebookResponseException;
use Facebook\Exceptions\FacebookSDKException;
use FacebookAds\Api;
use FacebookAds\Object\AdUser;
// Init PHP Sessions
session_start();
$fb = new Facebook([
'app_id' => 'your-app-id',
'app_secret' => 'your-app-secret',
]);
$helper = $fb->getRedirectLoginHelper();
if (!isset($_SESSION['facebook_access_token'])) {
$_SESSION['facebook_access_token'] = null;
}
if (!$_SESSION['facebook_access_token']) {
$helper = $fb->getRedirectLoginHelper();
try {
$_SESSION['facebook_access_token'] = (string) $helper->getAccessToken();
} catch (FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch (FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
}
if ($_SESSION['facebook_access_token']) {
echo "You are logged in!";
$app = Api::init(
'your-app-id', // App ID
'your-app-secret', $_SESSION['facebook_access_token'] // Your user access token
);
$me = new AdUser('me');
$my_adaccount = $me->getAdAccounts()->current();
print_r($my_adaccount->getData());
} else {
$permissions = ['ads_management'];
$loginUrl = $helper->getLoginUrl('http://localhost:8888/marketing-api/', $permissions);
echo 'Log in with Facebook';
}
You should also check that the access token you have has not expired as this will also cause an authentication exception to be thrown. This access token object has the function isExpired which you can use to test this.
You can extend the access token by using Oauth2Client and calling getLongLivedAccessToken.
$long_lived_token =
$fb->getOauth2Client()->getLongLivedAccessToken($access_token);
If you want to see why the token has become invalid, you can use the Developer Debug Tool:
https://developers.facebook.com/tools/debug/

USING OAUTH2 TO GET USER CONTACT LIST

I am trying to access a users contact list using google Oauth2 but seem to be running into an error insufficient permision. My code is as below
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Google extends CI_Controller {
public function __construct() {
parent::__construct();
}
public function index() {
require_once 'google-api-php-client/autoload.php'; // or wherever
autoload.php is located
$client = new Google_Client();
$scriptUri = "http://localhost/tcaller/google/";
$client = new Google_Client();
$client->setAccessType('online'); // default: offline
$client->setApplicationName('Tcaller');
$client->setClientId('******');
$client->setClientSecret('****');
$client->setRedirectUri($scriptUri);
$client->setDeveloperKey('******'); // API key
$client->setScopes(array('https://www.google.com/m8/feeds' , 'https://www.googleapis.com/auth/contacts.readonly'));
$plus = new Google_Service_Plus($client);
if (isset($_GET['logout'])) { // logout: destroy token
$this->session->unset_userdata("token");
die('Logged out.');
}
if (isset($_GET['code'])) { // we received the positive auth callback, get the token and store it in session
$client->authenticate($_GET['code']);
$tokenArr = array('token' => $client->getAccessToken());
$this->session->set_userdata($tokenArr);//gets valid access token
$redirect = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']; //set into session storage
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
if ($this->session->userdata('token')) { // extract token from session and configure client
$token = $this->session->userdata('token');
$client->setAccessToken($token);
try {
$me = $plus->people->get('me');
print_r($me);
} catch (apiServiceException $e) {
// Handle exception. You can also catch Exception here.
// You can also get the error code from $e->getCode();
echo 'error';
}
}
if (!$client->getAccessToken()) { // auth call to google
$authUrl = $client->createAuthUrl();
header("Location: ".$authUrl);
die();
}
}
}
?>
I am getting the error
Fatal error: Uncaught exception 'Google_Service_Exception' with
message 'Error calling GET
https://www.googleapis.com/plus/v1/people/me?key=%2A%2A%2A%2A%2A%2A:
(403) Insufficient Permission' in
C:\xampp\htdocs\tcaller\application\controllers\google-api-php-client\src\Google\Http\REST.php:111
Stack trace: #0
C:\xampp\htdocs\tcaller\application\controllers\google-api-php-client\src\Google\Http\REST.php(63):
Google_Http_REST::decodeHttpResponse(Object(Google_Http_Request),
Object(Google_Client)) #1 [internal function]:
Google_Http_REST::doExecute(Object(Google_Client),
Object(Google_Http_Request)) #2
C:\xampp\htdocs\tcaller\application\controllers\google-api-php-client\src\Google\Task\Runner.php(172):
call_user_func_array(Array, Array) #3
C:\xampp\htdocs\tcaller\application\controllers\google-api-php-client\src\Google\Http\REST.php(47):
Google_Task_Runner->run() #4
C:\xampp\htdocs\tcaller\application\controllers\google-api-php-client\src\Google\Client.php(564):
Google_Http_REST::execute(Object(Google_Client), Object(Google_H in
C:\xampp\htdocs\tcaller\application\controllers\google-api-php-client\src\Google\Http\REST.php
on line 111
Am i missing something
You should not need to use a separate API key and call $client->setDeveloperKey() as you're obtaining and using an OAuth 2.0 access token already with a client secret. Moreover, it seems that that is incorrect and/or not associated with the same project. So please try with that call removed.

Categories