I'm trying to build a simple project in which the google plus profile data will be saved or will get updated into the database. I'm unable to figure the way out of invalid character URI problem. I'm getting invalid character URI as response from google.
How can I solve this problem of invalid URI?
I have attached the image of the error at the end of this post.
Login Controller class code is:
public function index() {
// Include the google api php libraries
include_once APPPATH."libraries/google-api-php-client/Google_Client.php";
include_once APPPATH."libraries/google-api-php-client/contrib/Google_Oauth2Service.php";
// Google Project API Credentials
$clientId = 'My Client ID';
$clientSecret = 'My Secret here';
$redirectUrl = 'https://example.com/index.php?login/index/';
// Google Client Configuration
$gClient = new Google_Client();
$gClient->setApplicationName('Login to Application');
$gClient->setClientId($clientId);
$gClient->setClientSecret($clientSecret);
$gClient->setRedirectUri($redirectUrl);
$google_oauthV2 = new Google_Oauth2Service($gClient);
if (isset($_REQUEST['code'])) {
$gClient->authenticate();
$this->session->set_userdata('token', $gClient->getAccessToken());
redirect($redirectUrl);
}
$token = $this->session->userdata('token');
if (!empty($token)) {
$gClient->setAccessToken($token);
}
if ($gClient->getAccessToken()) {
$userProfile = $google_oauthV2->userinfo->get();
// Preparing data for database insertion
$userData['oauth_provider'] = 'google';
$userData['oauth_uid'] = $userProfile['id'];
$userData['first_name'] = $userProfile['given_name'];
$userData['last_name'] = $userProfile['family_name'];
$userData['email'] = $userProfile['email'];
$userData['gender'] = $userProfile['gender'];
$userData['locale'] = $userProfile['locale'];
$userData['profile_url'] = $userProfile['link'];
$userData['picture_url'] = $userProfile['picture'];
// Insert or update user data
$userID = $this->user->checkUser($userData);
if(!empty($userID)){
$data['userData'] = $userData;
$this->session->set_userdata('userData',$userData);
} else {
$data['userData'] = array();
}
} else {
$data['authUrl'] = $gClient->createAuthUrl();
}
$this->load->view('backend/login',$data);
}
The image of the error :
I am unable to tackle the problem. Please suggest me how can I avoid this.
Related
I am working with google api(Rest Api) in php, I just want whenever
any user send "access_token/token" then i want to validate and get userinfo,How can i do this ?
I tried with following code but not working for me,showing me always url in my postman,Where i am wrong ?
<?php
$google_client->authenticate($_GET['code']);
$client = new Google_Client();
$google_client = new Google_Client();
$google_client->setClientId('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com'); //Define your ClientID
$google_client->setClientSecret('xxxxxxxxxxxxxxxxxxxxx'); //Define your Client Secret Key
$google_client->setRedirectUri('xxxxxxxxxxxx'); //Define your Redirect Uri
$google_client->addScope('email');
$google_client->addScope('profile');
$objOAuthService = new Google_Service_Oauth2($google_client);
$getAccesToken = $google_client->getAccessToken();
$getRefreshToken = $google_client->getRefreshToken();
$google_client->setAccessToken($token['access_token']);
$objOAuthService = new Google_Service_Oauth2($google_client);
if($google_client->getAccessToken()) {
$userData = $objOAuthService->userinfo->get();
if(!empty($userData))
{
$outputjson['user_data'] = $userData;
$outputjson['access_token'] = $google_client->getAccessToken();
}else{
$outputjson['login_url'] = $google_client->createAuthUrl();
}
}
I got a warning email from Google reminding me of Google+'s EOL which is supposed to break my current "Login with Google", but I am unsure what exactly should I change.
Let me show you my (simplified) login code:
google-login.php
new class {
public function __construct() {
$state = mt_rand();
$client = new Google_Client();
$client->setApplicationName(Config::Google['app_name']);
$client->setClientId(Config::Google['id']);
$client->setClientSecret(Config::Google['secret']);
$client->setRedirectUri(sprintf('https://%s/members/google-callback.php', $_SERVER['HTTP_HOST']));
$client->setScopes(['profile', 'email']);
$client->setState($state);
$_SESSION['state'] = $state;
$url = $client->createAuthUrl(); // $url = https://accounts.google.com/o/oauth2/auth?response_type=code&access_type=online&client_id=CLIENT_ID.apps.googleusercontent.com&redirect_uri=https%3A%2F%2Fread2me.online%2Fmembers%2Fgoogle-callback.php&state=1588245f23f2a&scope=profile%20email&approval_prompt=auto
header ("location: $url");
}
};
google-callback.php
new class {
private $newUser = false;
public function __construct() {
if (!isset($_GET['state']) || $_GET['state'] != $_SESSION['state'])
die('State mismatch.');
$client = new Google_Client();
$client->setApplicationName(Config::Google['app_name']);
$client->setClientId(Config::Google['id']);
$client->setClientSecret(Config::Google['secret']);
$client->setRedirectUri(sprintf('https://%s/members/google-callback.php', $_SERVER['HTTP_HOST']));
$client->setScopes(['profile', 'email']);
$plus = new Google_Service_Plus($client);
if (isset($_GET['code'])) {
$client->fetchAccessTokenWithAuthCode($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if (!$client->getAccessToken() || $client->isAccessTokenExpired()) {
$state = mt_rand();
$client->setState($state);
$_SESSION['state'] = $state;
$url = $client->createAuthUrl();
header ("location: $url");
}
try {
$me = $plus->people->get('me');
} catch (Google_Exception $e) {
\Rollbar::report_message($e->getMessage());
print_r($e->getMessage());
return;
}
$accessToken = $client->getAccessToken()['access_token'];
$email = $me->getEmails()[0]->getValue();
$name = $me->getDisplayName();
$avatar = $me->getImage()->getUrl();
$id = $me->getId();
if ($this->isEmailInSystem($email) === false) {
$this->newUser = true;
$this->addUser($email, $name, 'google', $accessToken, $id, $avatar);
}
header ("location: " . '/');
}
};
Now, I'm going through at what seems to be the up-to-date Sign In guide for PHP, but I am not sure what to change - any ideas?
Thanks
The best migration is to move from the Plus API to the People API, which provides access to the user's profile in a similar (tho not quite identical) way.
You would replace the creation of the $plus object with a new Goolge_Service_PeopleService object. Something like
$people = new Google_Service_PeopleService( $client );
Getting the profile is more involved since you need to specify which fields from the profile you want to get. But you might do it something like
$profile = $people->people->get(
'people/me',
array('personFields' => 'names,emailAddresses,photos')
);
The first parameter needs to be "people/me" to specify that you're requesting the authorized user's profile.
The second is an array of query parameters. You need to specify the "personFields" that you want from the list of what is available (scroll down on this page till you see the description of the available fields) and specify this as a comma separated list in a string. In my example above, I illustrate getting the name, email addresses, and photos. But consult the list and experiment.
The exact fields you get from the result in $profile will be different than those you got from $plus, but they should match the fields you requested. Check the values and exactly how they're structured.
I ran into the same issue as Google+ APIs shutting down on March 7, 2019.
Make sure Google People API is enable in your google console
I used google-api-php-client Library.
Once you have an access token here is code to get the person object using people API
$accessToken = 'REPLACE_WITH_ACCESS_TOKEN';
$clientId = 'REPLACE_WITH_CLIENT_ID';
$clientSecret = 'REPLACE_WITH_CLIENT_SECRET';
$developerKey = 'REPLACE_WITH_DEVELOPER_KEY';
$client = new Google_Client();
$client->setApplicationName("Application Name");
$client->setClientId($clientId . '.apps.googleusercontent.com');
$client->setClientSecret($clientSecret);
$client->setDeveloperKey($developerKey);
$client->setScopes(['https://www.googleapis.com/auth/userinfo.email','https://www.googleapis.com/auth/userinfo.profile']);
$client->setAccessToken($accessToken);
$guzzleClient = new \GuzzleHttp\Client(array( 'curl' => array( CURLOPT_SSL_VERIFYPEER => false, ), ));
$client->setHttpClient($guzzleClient);
$people = new Google_Service_PeopleService( $client );
if ($client->getAccessToken()) {
try {
$me = $people->people->get(
'people/me',
array('personFields' => 'emailAddresses,names,photos')
);
$id = preg_replace('/[^0-9]/', '', $me->getResourceName());
$email = $me->getEmailAddresses()[0]->value;
$name = $me->getNames()[0]->displayName;
$avtar = $me->getPhotos()[0]->getUrl();
} catch (Google_Exception $e) {
// error
echo $e->getMessage();
}
}
I also disabled Google+ API to make sure the application is not using it anymore anywhere.
With latest version of Google API PHP Client you can fetch profile details from Google_Client object itself.
$token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
$attributes = $client->verifyIdToken($token['id_token'], GOOGLE_CLIENT_ID);
print_r($attributes);
Refer this article.
Obviously, the lines
$plus = new Google_Service_Plus($client);
and
$me = $plus->people->get('me');
You need to use google email API, see https://developers.google.com/gmail/api/quickstart/php , so the first line will be
$service = new Google_Service_Gmail($client);
and second ... hmmm ... not sure there WILL be any avatar after removing of google plus ...
I am using dialogflow php client library for accessing v2 rest api of dialogflow. I can call detectIntent and other stuffs and it is working. But some times i should need to search for a specific trainingPhrase and if not present then add new training phrase for detected intent. How could i do this using php client library? I am tired of searching on this. Please help me. Any answers will be appreciated. The function I'm using to getIntent with the some text is as below,
function detect_intent_texts($projectId, $text, $sessionId, $languageCode = 'en-US')
{
global $common;
// new session
$test = array('credentials' => 'key_file.json');
$sessionsClient = new SessionsClient($test);
$session = $sessionsClient->sessionName($projectId, $sessionId ?: uniqid());
//printf('Session path: %s' . PHP_EOL, $session);
// create text input
$textInput = new TextInput();
$textInput->setText($text);
$textInput->setLanguageCode($languageCode);
// create query input
$queryInput = new QueryInput();
$queryInput->setText($textInput);
// get response and relevant info
$response = $sessionsClient->detectIntent($session, $queryInput);
$queryResult = $response->getQueryResult();
$queryText = $queryResult->getQueryText();
$intent = $queryResult->getIntent();
$displayName = $intent->getDisplayName();
$common->write_to_log("intent displayName : ".$displayName);
if($displayName == "Default Fallback Intent")
{
$result = json_encode(array("result"=>false));
$common->write_to_log("No matching intent found");
}
else
{
$confidence = $queryResult->getIntentDetectionConfidence();
$fulfilmentText = $queryResult->getFulfillmentText();
$common->write_to_log("intent response : ".$fulfilmentText);
$result = json_encode(array("result"=>true,"message"=>$fulfilmentText));
}
echo $result;
$sessionsClient->close();
}
When I attempt to connect to QBO via the Consolibyte package I downloaded I get an error.
Error Code: internal_error
Message: Error getting application from request token
You can contact us for further assistance. Error
Id:ixnkryec2iu513ef45f3f5xv-12940655
I have set up the config.php file as directed in the instructions and even got to the point of authorizing the application with Quickbooks but now when I navigate to the page it indicates that I am not logged in and when I click the "Connect to QuickBooks" button on the index.php page I get the error above. I'm not familiar enough with the process to know where to start troubleshooting this problem and any help would be greatly appreciated.
Link: http://production.technology-architects.com/unleashed_new/quickbook/docs/partner_platform/example_app_ipp_v3/
example_app_ipp_v3/config.php code
require_once dirname(__FILE__) . '/../../../QuickBooks.php';
$token = 'f5ddd229b1d19b4153b8218b08b97897050f';
$oauth_consumer_key = 'qyprdYvvyNLq1om6FSw0xLebctZEAz';
$oauth_consumer_secret = 'KCLYZRgZ4LnHUB35AzvylxnH6c8CDCyjhva8I9Gp';
$sandbox = true; // When you're using development tokens
$quickbooks_oauth_url = 'http://production.technology-architects.com/unleashed_new/quickbook/docs/partner_platform/example_app_ipp_v3/oauth.php';
$quickbooks_success_url = 'http://production.technology-architects.com/unleashed_new/quickbook/docs/partner_platform/example_app_ipp_v3/success.php';
$quickbooks_menu_url = 'http://production.technology-architects.com/unleashed_new/quickbook/docs/partner_platform/example_app_ipp_v3/menu.php';
$dsn = 'mysqli://myusername:mypassword#localhost/databasename';
$encryption_key = 'bcde1234';
$the_username = 'DO_NOT_CHANGE_MEddd';
$the_tenant = 'sdfaswrqwerqwr';
if (!QuickBooks_Utilities::initialized($dsn)){
QuickBooks_Utilities::initialize($dsn);
}
$IntuitAnywhere = new QuickBooks_IPP_IntuitAnywhere($dsn, $encryption_key, $oauth_consumer_key, $oauth_consumer_secret, $quickbooks_oauth_url, $quickbooks_success_url);
if ($IntuitAnywhere->check($the_username, $the_tenant) and $IntuitAnywhere->test($the_username, $the_tenant)){
$quickbooks_is_connected = true;
$IPP = new QuickBooks_IPP($dsn);
$creds = $IntuitAnywhere->load($the_username, $the_tenant);
$IPP->authMode(
QuickBooks_IPP::AUTHMODE_OAUTH,
$the_username,
$creds);
if ($sandbox){
$IPP->sandbox(true);
}
$realm = $creds['qb_realm'];
$Context = $IPP->context();
$CompanyInfoService = new QuickBooks_IPP_Service_CompanyInfo();
$quickbooks_CompanyInfo = $CompanyInfoService->get($Context, $realm);
} else {
$quickbooks_is_connected = false;
}
None of the tokens or OAuth credentials you have in your code match what you have in the screenshot.
Fix your tokens and OAuth values.
$token = 'f5ddd229b1d19b4153b8218b08b97897050f';
$oauth_consumer_key = 'qyprdYvvyNLq1om6FSw0xLebctZEAz';
$oauth_consumer_secret = 'KCLYZRgZ4LnHUB35AzvylxnH6c8CDCyjhva8I9Gp';
I successfully setup twitteroauth and posted a message. Now, when I try to post again, and every time AFTER THE FIRST successful message post, I get an error Your credentials do not allow access to this resource. (code 220);
Here's my code:';
$message = 'Test';
$apiKey = Ranger_Application_Util::getConfig('twitter_app_api_key');
$apiSecret = Ranger_Application_Util::getConfig('twitter_app_api_secret');
$consumerToken = Ranger_Application_Util::getStorageData('twitter_oauth_token');
$consumerSecret = Ranger_Application_Util::getStorageData('twitter_oauth_secret');
$twitterOauthVerifier = Ranger_Application_Util::getStorageData('twitter_oauth_verifier');
$_SESSIOM['oauth_token'] = $consumerToken;
$_SESSION['oauth_token_secret'] = $consumerSecret;
require_once 'twitter/twitteroauth.php';
$connection = new TwitterOAuth($apiKey,$apiSecret,$consumerToken,$consumerSecret);
$connection->host = "https://api.twitter.com/1.1/";
$accessToken = $connection->getAccessToken($twitterOauthVerifier);
$_SESSION['access_token'] = $accessToken;
$parameters = array('status' => $message);
$status = $connection->post('statuses/update',$parameters);
Core::dump($status);
die();
The data I retrieve from getStorageData is values stored in the database that pertain to that specific user.
Unless you are storing the information from $accessToken to your database in a piece of code you have not posted, I believe the issue may be that you are getting the access token after your initial connection, but not using the permanent access information from the access token when trying to post to the connection. So any future requests will not be using the permanent credentials and are therefore rejected. Try something like this:
$message = 'Test';
$apiKey = Ranger_Application_Util::getConfig('twitter_app_api_key');
$apiSecret = Ranger_Application_Util::getConfig('twitter_app_api_secret');
$twitterOauthVerifier = Ranger_Application_Util::getStorageData('twitter_oauth_verifier');
require_once 'twitter/twitteroauth.php';
$hasAccessToken = (
array_key_exists('oauth_token', $_SESSION) &&
array_key_exists('oauth_token_secret', $_SESSION));
if ($hasAccessToken)
{
$consumerToken = $_SESSION['oauth_token'];
$consumerSecret = $_SESSION['oauth_token_secret'];
}
else
{
$consumerToken = Ranger_Application_Util::getStorageData('twitter_oauth_token');
$consumerSecret = Ranger_Application_Util::getStorageData('twitter_oauth_secret');
$connection = new TwitterOAuth($apiKey, $apiSecret, $consumerToken, $consumerSecret);
$connection->host = "https://api.twitter.com/1.1/";
$accessToken = $connection->getAccessToken($twitterOauthVerifier);
$consumerToken = $accessToken['oauth_token'];
$consumerSecret = $accessToken['oauth_token_secret'];
$_SESSION['oauth_token'] = $consumerToken;
$_SESSION['oauth_token_secret'] = $consumerSecret;
}
$connection = new TwitterOAuth($apiKey, $apiSecret, $consumerToken, $consumerSecret);
$connection->host = "https://api.twitter.com/1.1/";
$parameters = array('status' => $message);
$status = $connection->post('statuses/update', $parameters);
Core::dump($status);
die();
You may want to store the oauth token information in your database after receiving it from getAccessToken() rather than using sessions. Maybe you have a method like Ranger_Application_Util::setStorageData('twitter_oauth_token', $consumerToken)?
This
$_SESSIOM['oauth_token'] = $consumerToken;
^
should be
$_SESSION['oauth_token'] = $consumerToken;