Retrieve users/company information - intuit-partner-platform

On connecting to Quickbook within our app we are able to get access token and realmid but on trying to implement Get App Now we couldn't get any information after redirecting to our openid url. What I have tried so far is
define('OAUTH_CONSUMER_KEY', $consumerkey);
define('OAUTH_CONSUMER_SECRET', $consumersecret);
define('OAUTH_URL', 'https://oauth.intuit.com/');
define('APPCENTER_URL', 'https://appcenter.intuit.com/');
define('OAUTH_REQUEST_URL', OAUTH_URL . 'oauth/v1/get_request_token');
define('OAUTH_ACCESS_URL', OAUTH_URL . 'oauth/v1/get_access_token');
define('OAUTH_AUTHORISE_URL', APPCENTER_URL . 'Connect/Begin');
define('OAUTH_CURRENT_USER', APPCENTER_URL . 'api/v1/user/current');
try{
$oauth = new OAuth(OAUTH_CONSUMER_KEY,OAUTH_CONSUMER_SECRET,OAUTH_SIG_METHOD_HMACSHA1,OAUTH_AUTH_TYPE_URI);
$oauth->enableDebug();
$request_token = $oauth->getRequestToken(OAUTH_CURRENT_USER,CALLBACK_URL);
echo '<pre>';
print_r($_POST);
print_r($_GET);
print_r($_REQUEST);
print_r($_SESSION);
echo $request_token;
print_r($request_token);
echo '</pre>';
} catch(OAuthException $e) {
pr($e);
}
I can't get any valuable information on the above code, I maybe doing it wrong and expecting that there would be realmid and access token once the authorization is done and quickbooks redirect to our openid url. Any information would be appreciated.
Please note I really don't have knowledge about this as this is my first time using quickbooks api and related technologies.
Updated
<?php
require 'openid.php';
try {
# Change 'localhost' to your domain name.
$openid = new LightOpenID($_SERVER["HTTP_HOST"]);
if(!$openid->mode) {
if(isset($_GET['login'])) {
$openid->identity = 'https://openid.intuit.com/OpenId/Provider';//'https://www.google.com/accounts/o8/id';
$openid->required = array(
'contact/email',
'namePerson/first',
'namePerson/last'
);
header('Location: ' . $openid->authUrl());
}
?>
<form action="?login" method="post">
<button>Login with Google</button>
</form>
<?php
} elseif($openid->mode == 'cancel') {
echo 'User has canceled authentication!';
} else {
echo 'User ' . ($openid->validate() ? $openid->identity . ' has ' : 'has not ') . 'logged in.';
}
} catch(ErrorException $e) {
echo $e->getMessage();
}
When the form above gets submitted it results into No OpenID Server found at https://openid.intuit.com/OpenId/Provider

Related

Facebook login: url cannot be loaded

I have the following code and get the following error (it is in Dutch):
Graph returned an error: URL kan niet worden geladen: Het domein van deze URL is niet toegevoegd aan de domeinen van deze app. Voeg alle domeinen en subdomeinen van je app toe aan het veld Appdomeinen in de instellingen van je app om deze URL te kunnen laden.
What may be wrong?
ini_set('display_errors', true);
$host = "m.****.com"; // Your Sub domain
$host2 = "www.m.****.com"; // Your Sub domain
if ($_SERVER['HTTP_HOST'] == $host || $_SERVER['HTTP_HOST'] == $host2) {
$root_doc = $_SERVER['DOCUMENT_ROOT'];
$root_doc = str_replace("/m","",$root_doc);
} else {
$root_doc = $_SERVER['DOCUMENT_ROOT'];
}
include_once("$root_doc/php-graph-sdk-5.x/src/Facebook/autoload.php");
//require_once __DIR__ . '/vendor/autoload.php'; // change path as needed
$fb = new \Facebook\Facebook([
'app_id' => '*****',
'app_secret' => '****',
'default_graph_version' => 'v2.10',
//'default_access_token' => '{access-token}', // optional
]);
// Use one of the helper classes to get a Facebook\Authentication\AccessToken entity.
// $helper = $fb->getRedirectLoginHelper();
// $helper = $fb->getJavaScriptHelper();
// $helper = $fb->getCanvasHelper();
// $helper = $fb->getPageTabHelper();
//BEGIN
$helper = $fb->getRedirectLoginHelper();
//$helper = $fb->getRedirectLoginHelper();
if (isset($_GET['state'])) {
$helper->getPersistentDataHandler()->set('state', $_GET['state']);
}
try {
$accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
if (! isset($accessToken)) {
if ($helper->getError()) {
header('HTTP/1.0 401 Unauthorized');
echo "Error: " . $helper->getError() . "\n";
echo "Error Code: " . $helper->getErrorCode() . "\n";
echo "Error Reason: " . $helper->getErrorReason() . "\n";
echo "Error Description: " . $helper->getErrorDescription() . "\n";
} else {
header('HTTP/1.0 400 Bad Request');
echo 'Bad request';
}
exit;
}
// Logged in
echo '<h3>Access Token</h3>';
var_dump($accessToken->getValue());
// The OAuth 2.0 client handler helps us manage access tokens
$oAuth2Client = $fb->getOAuth2Client();
// Get the access token metadata from /debug_token
$tokenMetadata = $oAuth2Client->debugToken($accessToken);
//echo '<h3>Metadata</h3>';
//var_dump($tokenMetadata);
// Validation (these will throw FacebookSDKException's when they fail)
$tokenMetadata->validateAppId("152670682069405");
// If you know the user ID this access token belongs to, you can validate it here
//$tokenMetadata->validateUserId('123');
$tokenMetadata->validateExpiration();
if (! $accessToken->isLongLived()) {
// Exchanges a short-lived access token for a long-lived one
try {
$accessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
} catch (Facebook\Exceptions\FacebookSDKException $e) {
echo "<p>Error getting long-lived access token: " . $e->getMessage() . "</p>\n\n";
exit;
}
echo '<h3>Long-lived</h3>';
var_dump($accessToken->getValue());
}
$_SESSION['fb_access_token'] = (string) $accessToken;
//END
try {
// Get the \Facebook\GraphNodes\GraphUser object for the current user.
// If you provided a 'default_access_token', the '{access-token}' is optional.
$response = $fb->get('/me', '{access-token}');
} catch(\Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(\Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
$me = $response->getGraphUser();
echo 'Logged in as ' . $me->getName();
I hope i will get an answer.
Regards,
Jeroen
Translated from Dutch to English:
URL can not be loaded: The domain of this URL has not been added to the domains of this app. Add all domains and subdomains of your app to the App domains field in your app's settings to load this URL.

header location is not working, im stuck in the same page

hey all i have this code, the query works totally fine but the header no please help , this is my code i appreciate it
<?php
if (isset($_POST['login'])){
$username=$_POST['username'];
$pass=$_POST['password'];
$hashedpass=md5($pass);
$query="SELECT username, password FROM users WHERE username='$username' AND password='$hashedpass'";
echo $query;
$run=mysqli_query($con, $query);
$rows=mysqli_num_rows($run);
if ($rows > 0){
$_SESSION['username'] = $username;
header('Location: index.php');
exit();
}
}
?>
Username
Password
Try writing complete uri and delete exit
header('Location: http://www.domain/index.php');

Code to access Facebook Graph API with PHP SDK not working when reloading page

I'm writing some code to get the Facebook pages administered by a Facebook user, using Facebook Graph API. My code asks for authorization of the user and gets a token that enables it to get this information, which is then stored in a session. The problem is that if I reload the page, the stored token is unset and I will not be able to get the Facebook pages administered by the Facebook user.
The token is apparently revoked via the 'validateExpiration()' function when the page is reloaded.
What am I missing?
Here is my code:
session_start();
// Load the Facebook PHP SDK
require_once __DIR__ . '/facebook-sdk-v5/autoload.php';
define('APP_ID', 'xxxxxxxxxxxxxxxx');
define('APP_SECRET', 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
$fb = new Facebook\Facebook([
'app_id' => APP_ID,
'app_secret' => APP_SECRET,
'default_graph_version' => 'v2.7'
]);
if(isset($_SESSION['fb_access_token'])) {
echo '$_SESSION["fb_access_token"] = ' . $_SESSION['fb_access_token'] . '<br>';
// Create a new AccessToken object from its string code. Needed?
$accessToken = new Facebook\Authentication\AccessToken($_SESSION['fb_access_token']);
$expirationDate = $accessToken->getExpiresAt();
echo 'Token expires at: ' . var_dump($expirationDate) . '<br>'; // Returns null!
// verifies the validity and expiration of the token
$oAuth2Client = $fb->getOAuth2Client();
$tokenMetadata = $oAuth2Client->debugToken($accessToken);
try {
echo 'Validating token<br>';
$tokenMetadata->validateAppId(APP_ID);
$tokenMetadata->validateExpiration(); // This apparently throws an exception
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'I will now unset the token<br>';
unset($accessToken);
unset($_SESSION['fb_access_token']);
}
if(!isset($accessToken)){
echo 'Token not set!';
exit;
}
// Check permissions
if (isset($accessToken)) {
$response = $fb->get('/me/permissions', $accessToken);
$permissions = $response->getDecodedBody();
echo 'Permissions: ';
print_r($permissions);
$permissions_list = [];
foreach($permissions['data'] as $perm) {
if($perm['status'] == 'granted') {
$permissions_list[] = $perm['permission'];
}
}
echo 'Permissions list: ';
print_r($permissions_list);
if(!in_array('pages_show_list', $permissions_list)) {
echo 'I will now unset the token<br>';
unset($accessToken);
unset($_SESSION['fb_access_token']);
}
}
} else {
$helper = $fb->getRedirectLoginHelper();
try {
$accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
}
if(isset($accessToken)) {
// Logged in!
// Save the string code of the AccessToken to re-create it later
$_SESSION['fb_access_token'] = (string) $accessToken;
echo '$_SESSION["fb_access_token"] = ' . $_SESSION['fb_access_token'] . '<br>';
try {
$response = $fb->get('/me/accounts', $accessToken);
$data = $response->getDecodedBody();
echo '<pre>';
print_r($data);
echo '</pre>';
exit;
} catch(Facebook\Exceptions\FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
} else {
$helper = $fb->getRedirectLoginHelper();
$permissions = ['email', 'public_profile','pages_show_list']; // Optional permissions
$redirect_url = "https://www.example.com/this_file.php";
$loginUrl = $helper->getLoginUrl($redirect_url, $permissions);
echo 'Log in with Facebook!';
}
I finally got it!
The problem is that the Facebook AccessToken is an object with two properties: a string code, and a datetime PHP object with the expiration time - see the code in:
Github repository of Facebook's PHP SDK. The first time I get a fresh token, its expiration time is set and everything works fine. But when I store its code in a session and try to recreate it with
$accessToken = new Facebook\Authentication\AccessToken($_SESSION['fb_access_token']);
I'm not setting the expiration time, which the object defaults to the UNIX time 0 (i.e. January 1, 1970). Since after I invoke the function validateExpiration(), this will return that the access token has expired (it just looks at the expiration time in the AccessToken object) and will fire an exception.
Solution: Do not re-validate the stored token. The validateAppId(APP_ID) continues to be valid. For the expiration time, either store it (for example in a session) and use it when recreating the AccessToken object, or make a call to the Graph API. If this call returns an error (probably because of a token which was expired or a permission which was revoked by the user), ask the user for a new token via Facebook Login.

Read User Wall Post and others who posted on wall

I am new to the facebook graph API ,but I know the basics. Now I need help from you all about how to read user wall posts and others who posted on the wall of any user, with read_stream. But I don't know how to call it. I tried some way but I was able to read just the name and basic info. I need help in reading objects. Please help me!!!
<?php
define('FACEBOOK_APP_ID', 'xxxxxx');
define('FACEBOOK_SECRET', 'xxxxxx');
function get_facebook_cookie($app_id, $application_secret) {
$args = array();
parse_str(trim($_COOKIE['fbs_' . $app_id], '\\"'), $args);
ksort($args);
$payload = '';
foreach ($args as $key => $value) {
if ($key != 'sig') {
$payload .= $key . '=' . $value;
}
}
if (md5($payload . $application_secret) != $args['sig']) {
return null;
}
return $args;
}
$cookie = get_facebook_cookie(FACEBOOK_APP_ID, FACEBOOK_SECRET);
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:fb="http://www.facebook.com/2008/fbml">
<body>
<?php
echo 'Your Facebook ID: '.$cookie;
if ($cookie) {
//cookie is set, user is logged in
$user = json_decode(file_get_contents('http://graph.facebook.com/'.$cookie['uid']));
//Display the facebook user ID, name, gender and Facebook URL in the web browser
echo '<br />';
echo 'Your Facebook ID: '.$user->{'id'};
echo '<br />';
echo 'Your name: '.$user->{'name'};
echo '<br />';
echo 'Your gender: '.$user->{'gender'};
echo '<br />';
echo 'Your Facebook URL: '.$user->{'link'};
echo '<br />';
echo '<img src="http://graph.facebook.com/'.$user->{'id.'/picture" alt="'.$user-> {'name'}.'"/>';
echo '<br />';
echo '<fb:login-button autologoutlink="true"></fb:login-button>';
}
else
{
//user is not logged in, display the Facebook login button
echo '<h2>Facebook Application Test page</h2>';
echo '<br />';
echo' message somethng';
</body>
</html>
First of all you must take permission from your users
$url = "https://graph.facebook.com/oauth/authorize?"
."client_id=".$app_id."&"
."redirect_uri=http://apps.facebook.com/".$app_name."/&scope=read_stream";
<script language="javascript">window.open('<?php echo $url ?>', '_parent', '');</script>
Then you can get user's wall. There is an example here.
if(isset($_GET["code"])){
if(isset($_REQUEST['state']) == isset($_SESSION['state'])) {
$token_url = "https://graph.facebook.com/oauth/access_token?"
. "client_id=" . $app_id . "&redirect_uri=" . "http://apps.facebook.com/".$app_name."/"
. "&client_secret=" . $app_secret . "&code=" . $_GET["code"];
$response = #file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$graph_url = "https://graph.facebook.com/".$user_id."/feed/?access_token=".$params['access_token'];
$user = json_decode(file_get_contents($graph_url));
foreach($user as $feeds)
{
foreach($feeds as $feed)
{
if(isset($feed->link))
{
echo $feed->link."<br>";
}
}
}
}
}

Server side flow example

At the bottom is a working example of server side flow. It is a file fb_server_side_flow.php that I prepared from a template I found on developers.facebook.com. My first question is what exactly is $code = $_REQUEST["code"]; doing? Is it getting a Facebook cookie? If so how is $code = $_REQUEST["code"]; different from the code directly below? Is it really necessary to use session_start at towards the top of fb_server_side_flow.php?
Mainly I am trying to implement a system that gives my user an OPTION to login via Facebook but a login via Facebook is not a requirement. Is there any documentation available on implementing a login via Facebook OPTION as opposed to a required login via Facebook?
Thank you!
....
function get_facebook_cookie($app_id, $app_secret) {
$args = array();
parse_str(trim($_COOKIE['fbs_' . $app_id], '\\"'), $args);
ksort($args);
$payload = '';
foreach ($args as $key => $value) {
if ($key != 'sig') {
$payload .= $key . '=' . $value;
}
}
if (md5($payload . $app_secret) != $args['sig']) {
return null;
}
return $args;
}
$cookie = get_facebook_cookie(YOUR_APP_ID, YOUR_APP_SECRET);
....
fb_server_side_flow.php
<?php
$app_id = "****";
$app_secret = "****";
$my_url = "http://www.sepserver.net/dsg/fb_server_side_flow.php";
session_start();
$code = $_REQUEST["code"];
if(empty($code)) {
$_SESSION['state'] = md5(uniqid(rand(), TRUE)); //CSRF protection
$dialog_url = "https://www.facebook.com/dialog/oauth?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url) . "&state="
. $_SESSION['state'];
echo("<script> top.location.href='" . $dialog_url . "'</script>");
}
if($_REQUEST['state'] == $_SESSION['state']) {
$token_url = "https://graph.facebook.com/oauth/access_token?"
. "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url)
. "&client_secret=" . $app_secret . "&code=" . $code;
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$graph_url = "https://graph.facebook.com/me?access_token="
. $params['access_token'];
$user = json_decode(file_get_contents($graph_url));
echo("Hello " . $user->name);
}
else {
echo("The state does not match. You may be a victim of CSRF.");
}
?>
The first block of code is for retrieving Facebook cookie parameters for users who are already authorized and logged in.
The second block of code is for letting the user authorize your application (oauth) AND for retrieving an access_token your application can use to make API (FB Graph) calls on the user's behalf.
$_REQUEST relates to POST or GET parameters, not cookies. If you check the docs on authentication flow, you can see that Facebook redirects the user to http://your_redirect_uri?code=1234abcd after the user has approved your application. You're supposed to grab that code parameter and use it to make another call to graph.facebook.com to get the user's access_token.
The purpose of session_start() is to prepare the $_SESSION array, so that $_SESSION['state'] is preserved across page reload. If your framework already has session handling code, you can omit it. It's only used for the CSRF protection bit.
Optional login is pretty straightforward. If you're using the new PHP SDK, you can check the return value of $facebook->getUser(); -- if it's 0, the user is not logged in (and you can show content as normal, with perhaps an additional link to fb_server_side_flow.php to begin the authorization procedure.)