I am trying to retrieve a new access token with my refresh token. Before I run a script to retrieve a new access token I want to check if my access token is still valid.
I am trying to do this with exceptions:
try
{
// Connect
$session = new SoapClient("../webservices/session.asmx?wsdl", array('trace' => 1));
$result = $session->AccessTokenLogon($accessTokenparams);
}
catch (SoapFault $e)
{
// Check if AcccessToken returns TokenInvalid
if ($result->AccessTokenLogonResult == "TokenInvalid")
{
// AccessToken is not valid anymore
// ..
// Run script to get new access token
// ..
// $_SESSION["access_token"] = $access_token;
}
else
{
// AccessToken is valid
echo "AccessToken is valid";
}
}
finally
{
// Run script with valid AccessToken
global $result, $session;
$cluster = $result->cluster;
$qq = new domDocument();
$qq->loadXML($session->__getLastResponse());
$newurl = $cluster . '/webservices/processxml.asmx?wsdl';
try
{
$client = new SoapClient($newurl);
$header = new SoapHeader('http://www.website.com/', 'Header', array('AccessToken' =>$_SESSION["access_token"]));
}
catch (SoapFault $e)
{
echo $e->getMessage();
}
try
{
echo '<br /><br />XML Result:<br /><br />';
$xml = ""; // XML request
$result = $client->__soapCall('ProcessXmlString', array(array('xmlRequest'=>$xml)), null, $header);
}
catch (SoapFault $e)
{
echo $e->getMessage();
}
}
With a valid access token the script is working. The XML request is posted to the webservice.
The script is not working when the accesstoken is not valid anymore. The script stores the new accesstoken in the session: $_SESSION["access_token"] = $access_token; but is not running the 'finally' part after retrieving a new accesstoken.
Does someone know how I can fix this and run the 'finally' after retrieving a new accesstoken?
Related
I use Facebook PHP SDK and trying to send token-id from one page to another. I use this code - http://www.krizna.com/demo/login-with-facebook-using-php/. I use
$helper = new FacebookRedirectLoginHelper('http://www.krizna.com/fbconfig.php' );
I have tried sending value like this :
$helper = new FacebookRedirectLoginHelper('http://www.krizna.com/fbconfig.php?value='.$value );
but I do not get value in fbconfig.php file when I try:
$value = $_GET['value'];
I have also used session for sending values but it does not work. How can I send value to FacebookRedirectLoginHelper (fbconfig.php)?
fbconfig.php
<?php
session_start();
$value = $_GET['value_new'];
$fb = new \Facebook\Facebook([
'app_id' => $config->facebook->app_id,
'app_secret' => $config->facebook->app_secret
]);
$helper = $fb->getRedirectLoginHelper();
try {
if ($access_token = $helper->getAccessToken()) {
try {
// Returns a `Facebook\FacebookResponse` object with the requested fields
$response = $fb->get('/me?fields=name,id,email,picture', $access_token);
$user = $response->getGraphUser();
$fbid = $user->getId(); // To Get Facebook ID
$fbfullname = $user->getName(); // To Get Facebook full name
$femail = $graphObject->getEmail();// To Get Facebook email ID
$_SESSION['FBID'] = $fbid;
$_SESSION['FULLNAME'] = $fbfullname;
$_SESSION['EMAIL'] = $femail;
//Then do whatever you want with that data
$value = $_SESSION['value'];
header("Location: index.php?value_new=$value");
} catch (\Facebook\Exceptions\FacebookResponseException $e) {
error_log('Graph returned an error: ' . $e->getMessage());
} catch (\Facebook\Exceptions\FacebookSDKException $e) {
error_log('Facebook SDK returned an error: ' . $e->getMessage());
}
}
} catch (\Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
error_log('Graph returned an error: ' . $e->getMessage());
} catch (\Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
error_log('Facebook SDK returned an error: ' . $e->getMessage());
}
index.php
<?php if (isset($_SESSION['FBID'])): ?><!-- After user login -->
<div class="container">
<h1>value <?php $value_new = $_GET['value_new']; echo $value_new; ?></h1>
</div>
<? endif ?>
You should not be trying to pass the facebook Access Token via the query string / $_GET[] superglobal. What you should be using is what facebook recommends, which is the $_SESSION[] superglobal.
Since you are trying to pass the access token from one page to another, lets call the access token on the first page $access_token. To pass it to another page do the following:
page 1:
<?php
session_start(); //the very top of your document
// ... other code ...
$_SESSION['access_token'] = $access_token;
// ... other code ...
?>
page 2:
<?php
session_start(); //the very top of your document
// ... other code ...
$access_token = $_SESSION['access_token'];
// ... other code ...
?>
That should work, let me know if it works for you.
This answer is using the Facebook PHP SDK v5.1.2, and is adapted from the method I have working in my own projects. It also assumes composer autoloading is being used.
Login Page
session_start();
$fb = new \Facebook\Facebook([
'app_id' => $config->facebook->app_id, //Change these to yours
'app_secret' => $config->facebook->app_secret
]);
$helper = $fb->getRedirectLoginHelper();
$permissions = ['email'];
$this->view->facebook_url = $helper->getLoginUrl('http://www.krizna.com/fbconfig.php', $permissions);
fbconfig.php (or whatever you want your redirect page to be)
session_start();
$fb = new \Facebook\Facebook([
'app_id' => $config->facebook->app_id,
'app_secret' => $config->facebook->app_secret
]);
$helper = $fb->getRedirectLoginHelper();
try {
if ($access_token = $helper->getAccessToken()) {
try {
// Returns a `Facebook\FacebookResponse` object with the requested fields
$response = $fb->get('/me?fields=name,id,email,picture', $access_token);
$user = $response->getGraphUser();
$fbid = $user->getId(); // To Get Facebook ID
$fbfullname = $user->getName(); // To Get Facebook full name
$femail = $graphObject->getEmail(); // To Get Facebook email ID
$_SESSION['FBID'] = $fbid;
$_SESSION['FULLNAME'] = $fbfullname;
$_SESSION['EMAIL'] = $femail;
//Then do whatever you want with that data
} catch(\Facebook\Exceptions\FacebookResponseException $e) {
error_log('Graph returned an error: ' . $e->getMessage());
} catch(\Facebook\Exceptions\FacebookSDKException $e) {
error_log('Facebook SDK returned an error: ' . $e->getMessage());
}
}
} catch (\Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
error_log('Graph returned an error: ' . $e->getMessage());
} catch (\Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
error_log('Facebook SDK returned an error: ' . $e->getMessage());
}
Hopefully that gives you a hand up. I don't doubt that my code has been adapted from previous StackOverflow answers or tutorials.
I am trying integration with SalesForce using SOAP webservice.
I can build a connection with PHP and SOAP after that if I'm trying to call my method that is authenticate user, I am not getting any data, I'm getting blank.
Below is the code
define("USERNAME", "xxxxxxxxxxx");
define("PASSWORD", "xxxxxxxxxxx");
define("SECURITY_TOKEN", "xxxxxxxxxxx");
require_once ('soapclient/SforcePartnerClient.php');
require_once ('soapclient/SforceHeaderOptions.php');
// Login
$sfdc = new SforcePartnerClient();
$SoapClient = $sfdc->createConnection('soapclient/PartnerWSDL.xml');
$loginResult = false;
$loginResult = $sfdc->login('USERNAME', 'PASSWORD' . 'SECURITY_TOKEN');
// Define constants for the web service. We'll use these later
$parsedURL = parse_url($sfdc->getLocation());
define ("_SFDC_SERVER_", substr($parsedURL['host'],0,strpos($parsedURL['host'], '.')));
define ("_WS_NAME_", 'CustomerPortalServices');
define ("_WS_WSDL_", _WS_NAME_ . '.xml');
define ("_WS_ENDPOINT_", 'https://' . _SFDC_SERVER_ . '.salesforce.com/services/wsdl/class/' . _WS_NAME_);
//echo _WS_ENDPOINT_;
define ("_WS_NAMESPACE_", 'http://soap.sforce.com/schemas/class/' . _WS_NAME_);
// SOAP Client for Web Service
$client = new SoapClient('http://localhost/SFDC/soapclient/CustomerPortalServices_WSDL.xml');
$sforce_header = new SoapHeader(_WS_NAMESPACE_, "SessionHeader", array("sessionId" => $sfdc->getSessionId()));
$client->__setSoapHeaders(array($sforce_header));
// username and password sent from Form
echo $myusername=addslashes($_POST['login_username']);
echo $mypassword=addslashes($_POST['login_password']);
try {
// call the web service via post
$wsParams=array(
'username'=>'abc#gmail.com',
'password'=>'mypassword'
);
print_r($wsParams);
$response = $client->authenticateUser($wsParams);
// dump the response to the browser
print_r($response);
//header("location: index.php");
// this is really bad.
} catch (Exception $e) {
global $errors;
$errors = $e->faultstring;
echo "Ooop! Error: <b>" . $errors . "</b>";
die;
}
This is the method i am calling
global class CustomerPortalServicesNew {
webService static Summary authenticateUserNew(String uname,String passwd) {
System.debug('##'+'Entered in the authenticateUser');
List<contact> checkConList = new List<Contact>([select id,Email, Password__c, AccountId from contact where Email =:uname]);
System.debug('##'+'contact '+checkConList);
for(contact c:checkConList){
system.debug('##'+'Iterating in contactList'+checkConList);
if(c.Password__c==passwd){
system.debug('##'+c.AccountId);
return getAccountSummary(c.AccountId);
}
else{
system.debug('##'+'password has not matched');
return null;
}
}
system.debug('##'+'class finished');
return null;
}
I am getting response like this
object(stdClass)[8]
public 'result' =>
object(stdClass)[9]
not getting data
I think you need to print:
print_r($response->result);
If it's not working, try a var_dump($response)
I have used the following code to authenticate a user (it is based off of googles examples of a services account on github):
<?php
//API INFORMATION
$client_id='xx-x.apps.googleusercontent.com';
$client_email='xx-xx#developer.gserviceaccount.com';
$client_key='xx';
$cert_loc='directory/google-api-bushbase-privatekey.p12';
//SET THE APP SCROPES
$scopes=array(
'https://www.googleapis.com/auth/plus.login',
'https://www.googleapis.com/auth/plus.me',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile'
);
//GET ASSERTION CREDENTIALS
if(($key=file_get_contents($cert_loc))!==false){
//GOT GOOGLE CERTIFICATE
try{
$auth= new Google_Auth_AssertionCredentials($client_email,$scopes,$key);
}catch (Exception $e){
echo $error;
echo 'Unable to get authenticate with Google servers</div>';
//RETURN FALSE
return false;
}
}else{
echo $error;
echo 'Unable to get Google certificate</div>';
//RETURN FALSE
return false;
}
//GOOGLE CONNECTION OBJECT
try {
$connection = new Google_Client();
$connection->setApplicationName("Bush Base");
$connection->setAssertionCredentials($auth);
//CHECK TO SEE IF TOKEN IS EXPIRED VIA SESSION
if (isset($_SESSION['service_token'])) {
$connection->setAccessToken($_SESSION['service_token']);
}
if($connection->getAuth()->isAccessTokenExpired()){
//TOKEN IS EXPIRED SO RESET WITH ASSERTION CRED
$connection->getAuth()->refreshTokenWithAssertion($auth);
}
//GET THE TOKEN VALUE
$_SESSION['service_token']=$connection->getAccessToken();
$connection->setAccessToken($_SESSION['service_token']);
//THE CONNECTION WAS NOT SUCCESSFUL
}catch (Exception $e){
echo $error;
echo 'Unable to connect with Google database</div>';
//RETURN FALSE
return false;
}
//CREATE THE NEW GOOGLE SERVICES OBJECT
try{
$info =new Google_Service_Plus($connection);
}catch (Exception $e){
echo $error;
echo 'Unable to conntect to google services</div>';
//RETURN FALSE
return false;
}
try{
//GET THE USER INFO
$data= $info->people->get('me');
echo "<pre>";
print_r($data);
echo "</pre>";
}
I am trying to get the information for the user account 103283326808099970387 but some how i am authenticated as user 111631880133159328429.
If i go to https://plus.google.com/111631880133159328429, I get a 404 error.
i am using the below code to connect to salesforce using php
require_once ('SforcePartnerClient.php');
require_once ('SforceHeaderOptions.php');
require_once ('SforceMetadataClient.php');
$mySforceConnection = new SforcePartnerClient();
$mySforceConnection->createConnection("cniRegistration.wsdl");
$loginResult = $mySforceConnection->login("username", "password.token");
$queryOptions = new QueryOptions(200);
try {
$sObject = new stdclass();
$sObject->Name = 'Smith';
$sObject->Phone = '510-555-5555';
$sObject->fieldsToNull = NULL;
echo "**** Creating the following:\r\n";
$createResponse = $mySforceConnection->create($sObject, 'Account');
$ids = array();
foreach ($createResponse as $createResult) {
print_r($createResult);
array_push($ids, $createResult->id);
}
} catch (Exception $e) {
echo $e->faultstring;
}
But the above code is connect to salesforce database.
But is not executing the create commands. it's giving me the below error message
Creating the following: Element {}item invalid at this location
can any one suggest me to overcome the above problem
MAK, in your sample code SessionHeader and Endpoint setup calls are missing
$mySforceConnection->setEndpoint($location);
$mySforceConnection->setSessionHeader($sessionId);
after setting up those, if you still see an issue, check the namespace urn
$mySforceConnection->getNamespace
It should match targetNamespace value in your wsdl
the value of $mySforceConnection should point to the xml file of the partner.wsdl.xml.
E.g $SoapClient = $sfdc->createConnection("soapclient/partner.wsdl.xml");
Try adding the snippet code below to reference the WSDL.
$sfdc = new SforcePartnerClient();
// create a connection using the partner wsdl
$SoapClient = $sfdc->createConnection("soapclient/partner.wsdl.xml");
$loginResult = false;
try {
// log in with username, password and security token if required
$loginResult = $sfdc->login($sfdcUsername, $sfdcPassword.$sfdcToken);
}
catch (Exception $e) {
global $errors;
$errors = $e->faultstring;
echo "Fatal Login Error <b>" . $errors . "</b>";
die;
}
// setup the SOAP client modify the headers
$parsedURL = parse_url($sfdc->getLocation());
define ("_SFDC_SERVER_", substr($parsedURL['host'],0,strpos($parsedURL['host'], '.')));
define ("_SALESFORCE_URL_", "https://test.salesforce.com");
define ("_WS_NAME_", "WebService_WDSL_Name_Here");
define ("_WS_WSDL_", "soapclient/" . _WS_NAME_ . ".wsdl");
define ("_WS_ENDPOINT_", 'https://' . _SFDC_SERVER_ . '.salesforce.com/services/wsdl/class/' . _WS_NAME_);
define ("_WS_NAMESPACE_", 'http://soap.sforce.com/schemas/class/' . _WS_NAME_);
$urlLink = '';
try {
$client = new SoapClient(_WS_WSDL_);
$sforce_header = new SoapHeader(_WS_NAMESPACE_, "SessionHeader", array("sessionId" => $sfdc->getSessionId()));
$client->__setSoapHeaders(array($sforce_header));
} catch ( Exception $e ) {
die( 'Error<br/>' . $e->__toString() );
}
Please check the link on Tech Thought for more details on the error.
I am trying to integrate facebook for my canvas app. When i run app from facebook with following code
// init app with app id (APPID) and secret (SECRET)
FacebookSession::setDefaultApplication('xx','xx');
$helper = new FacebookCanvasLoginHelper();
try {
$data = array('oauth_token' => 'token');
$data['algorithm'] = 'HMAC-SHA256';
$data['issued_at'] = time();
$base64data = base64_encode(json_encode($data));
$rawSig = hash_hmac('sha256', $base64data, 'app_Secret', true);
$sig = base64_encode($rawSig);
$signedRequest = $sig.'.'.$base64data;
$_GET['signed_request'] = $signedRequest;
$session = $helper->getSession();
} catch(FacebookRequestException $ex) {
echo $ex;
} catch(\Exception $ex) {
echo $ex;
}
The entire page just turns blank white because of $_GET['signed_request'] = $signedRequest;.
What should I do to get login. If i just do $session = $helper->getSession(); instead of Get i get invalid signed paramters oAuth data missing.
Your PHP should be:
$helper = new FacebookCanvasLoginHelper();
try {
$session = $helper->getSession();
if($session){
try {
$facebook_profile = (new FacebookRequest(
$session, 'GET', '/me'
))->execute()->getGraphObject(GraphUser::className());
echo $facebook_profile->getName;
} catch(FacebookRequestException $e) {
}
}
} catch(FacebookRequestException $ex) {
echo $ex;
} catch(\Exception $ex) {
$facebookLoginHtml = "window.top.location = 'https://www.facebook.com/dialog/oauth?client_id={your_app_id}&redirect_uri={your_app_canvas_url}';";
}
And then somewhere in your HTML:
<script>
<?php if(isset($facebookLoginHtml)){ echo $facebookLoginHtml; } ?>
</script>
If you want to ask for extra permission, add the scope parameter in the URL like this:
$facebookLoginHtml = "window.top.location = 'https://www.facebook.com/dialog/oauth?client_id={your_app_id}&redirect_uri={your_app_canvas_url}&scope=publish_actions';";
That will redirect the page to the login page, and then come back to your canvas app with the proper permission.
This shouldn't work like this as it's using Javascript with the PHP SDK. It's a bug that is being addressed by Facebook which you can follow here:
https://developers.facebook.com/bugs/722275367815777
I'll edit the answer if that bug ever gets resolved.
Thanks guys!
My approach:
<?php
session_start();
require ({your_php_sdk_path} . 'autoload.php');
use Facebook\FacebookCanvasLoginHelper;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\GraphUser;
FacebookSession::setDefaultApplication({your_app_id},{your_app_secret});
$helper = new FacebookCanvasLoginHelper();
try {
$session = $helper->getSession();
}catch(FacebookRequestException $ex) {
// When Facebook returns an error
} catch(\Exception $ex) {
// When validation fails or other local issues
}
if (!is_null($session)) {
// Logged in
try {
//Get user name
$user_profile = (new FacebookRequest(
$session, 'GET', '/me'
))->execute()->getGraphObject(GraphUser::className());
$user_profile_name = $user_profile->getName();
//Get user picture
$request = new FacebookRequest(
$session,
'GET',
'/me/picture',
array (
'redirect' => false,
'height' => '135',
'width' => '135',
)
);
$response = $request->execute();
$graphObject = $response->getGraphObject();
$user_profile_picture = $graphObject->getProperty('url');
} catch(FacebookRequestException $e) {
// When Facebook returns an error
} catch(Exception $e) {
// When validation fails or other local issues
}
}else{
//First time -> ask for authorization
$helper = new FacebookRedirectLoginHelper({your_canvas_url});
$login_url = $helper->getLoginUrl();
}
?>
And in your html put a javascript:
<script type="text/javascript">
if($login_url != null){
top.location.href = $login_url;
}
</script>
<?php
// init app with app id (APPID) and secret (SECRET)
FacebookSession::setDefaultApplication('*********','*********' );
$helper = new FacebookCanvasLoginHelper();
try {
$session = $helper->getSession();
} catch(FacebookRequestException $ex) {
// When Facebook returns an error
} catch(Exception $ex) {
// When validation fails or other local issues
}
if($session) {
// graph api request for user data
$request = new FacebookRequest( $session, 'GET', '/me' );
$response = $request->execute();
// get response
$graphObject = $response->getGraphObject();
// print data
echo '<pre>' . print_r( $graphObject, 1 ) . '</pre>';
}
else {
// show login url
echo 'Login';
}
?>