Khan Academy PHP Oauth Code - php

Im really struggling w/ the OAuth for Khan Academy. This is for my class website (Im a teacher) and I want to pull in user data on particular students. If I could do the OAUTH I would be fine. Im using PHP.
There seems to be many librarys out there, I have been playing w/ Google Oauth (located here http://code.google.com/p/oauth-php/source/browse/trunk/example/client/twolegged.php)
I can formulate the token request fine, although when I call it in the script, it seems like it tries to redirect to another page and gets blocked there.
http://myonlinegrades.com/prealg/khan/oauth-php/example/client/twoleggedtest.php
Im really struggling - Id love any help you might offer.
Code below:
<?php
include_once "../../library/OAuthStore.php";
include_once "../../library/OAuthRequester.php";
// Test of the OAuthStore2Leg
// uses http://term.ie/oauth/example/
$key = '*********';//'<your app's API key>';
$secret = '***********';//'<your app's secret>';
$callBack = "http://myonlinegrades.com/prealg/test2.php5";
$url = 'http://www.khanacademy.org/api/auth/request_token';
$options = array('consumer_key' => $key, 'consumer_secret' => $secret);
OAuthStore::instance("2Leg", $options);
$method = "GET";
//$params = null;
$params = array(oauth_consumer_key => $key,oauth_callback=>$callBack);
try
{
// Obtain a request object for the request we want to make
$request = new OAuthRequester($url, $method, $params);
// Sign the request, perform a curl request and return the results,
// throws OAuthException2 exception on an error
// $result is an array of the form: array ('code'=>int, 'headers'=>array(), 'body'=>string)
$result = $request->doRequest();
$response = $result['body'];
if ($response != 'oauth_token=requestkey&oauth_token_secret=requestsecret')
{
echo 'Error! $response ' . $response;
}
else
{
}
var_dump($response);
}
catch(OAuthException2 $e)
{
echo "Exception" . $e->getMessage();
}
?>

Not sure this is what you're looking for, but I put together a simple example of doing oAuth with Khan Academy using the Temboo SDK: take a look at https://github.com/matthewflaming/temboo-experiments/tree/master/KhanAcademyOauth
(Full disclosure: I work at Temboo)

Related

Ebay: Auth token is invalid. Validation of the authentication token in API request failed

I'm trying to use Ebay PHP SDK to connect to Ebay and fetch sellers selling item. For this I used following steps:
Step 1: Get authorize token and code for logged-in user. I used following code to implement.
use \DTS\eBaySDK\OAuth\Services as OauthService;
use \DTS\eBaySDK\OAuth\Types as OauthType;
use \DTS\eBaySDK\Constants;
use \DTS\eBaySDK\Trading\Services;
use \DTS\eBaySDK\Trading\Types;
use \DTS\eBaySDK\Trading\Enums;
$service = new OauthService\OAuthService([
'credentials' => $config['sandbox']['credentials'],
'ruName' => $config['sandbox']['ruName'],
'sandbox' => true
]);
$oauthParam = [
'client_id' => $config['sandbox']['credentials']['appId'],
'redirect_uri' => $config['sandbox']['redirect_uri'],
'response_type' => 'code',
'scope' => 'https://api.ebay.com/oauth/api_scope'
];
$urlParam = '';
$query = [];
foreach($oauthParam as $key => $param) {
$query[] = "$key=$param";
}
$urlParam = '?' . implode('&', $query);
$url = 'https://signin.sandbox.ebay.com/authorize' . $urlParam;
#session_start();
if(isset($_SESSION['ebay_oauth_token'])) {
$token = $_SESSION['ebay_oauth_token']['code'];
}
else {
if(isset($_GET['code'])) {
$token = $_GET['code'];
$_SESSION['ebay_oauth_token']['code'] = $token;
$request = new OauthType\GetUserTokenRestRequest();
$request->code = $token;
$response = $service->getUserToken($request);
if ($response->getStatusCode() !== 200) {
//Error
} else {
$_SESSION['ebay_oauth_token']['access_token'] = $response->access_token;
}
} else {
#header('location: ' . $url);
}
}
$userOauthToken = $_SESSION['ebay_oauth_token']['access_token'];
The above code is working as expected. That is the user is redirected to Sign In Page to authorize himself and get the set of Code and Access Token.
Step 2: Fetch Selling Items using code obtained from Step #1. I've used following code to implement the functionality.
$request->RequesterCredentials = new Types\CustomSecurityHeaderType();
$request->RequesterCredentials->eBayAuthToken = $token; //Obtained from Step 1
$request->ActiveList = new Types\ItemListCustomizationType();
$request->ActiveList->Include = true;
$request->ActiveList->Pagination = new Types\PaginationType();
$request->ActiveList->Pagination->EntriesPerPage = 10;
$request->ActiveList->Sort = Enums\ItemSortTypeCodeType::C_CURRENT_PRICE_DESCENDING;
$pageNum = 1;
do {
$request->ActiveList->Pagination->PageNumber = $pageNum;
$response = $service->getMyeBaySelling($request);
if (isset($response->Errors)) {
//Error Output
}
if ($response->Ack !== 'Failure' && isset($response->ActiveList)) {
foreach ($response->ActiveList->ItemArray->Item as $item) {
//Output response
}
}
$pageNum += 1;
} while ({condition});
I'm having problem in Step #2. It is generating Invalid Token while running the code.
I would highly appreciate if anyone help me.
You are mixing the requests. In the second part of your code, the request belongs to the Trading API that uses the Auth'n'Auth token, and you are trying to make the call using the OAuth token. These 2 tokens are different and work for different APIs.
You have 2 options.
Either keep the second part of your code, which appears to be correct, actually, but use the Auth'n'Auth token (that you can generate from the developer account). In this case, the first part is useless.
Keep the first part of your code, and delete the second part. In this case, you need to rewrite your second part of code using the OAuth API instead of the Trading API.

How to post on fb using php?

I am using facebook apis to post on my testing account using php. The following code does the job for me and it works. If I log in with my account I can see the post, but if I use another account the post does not show. I have modified the privacy setting to public but still. I went to facebook's documentation,but I couldn't really find something to solve my problem. Can anyone help???
Thanks in advanced
function fb_post($post, $msg, $url, $pic) {
$temp_array = queryFBTable($post);
if (count($temp_array) == 0) return;
// initialize Facebook class using your own Facebook App credentials
// see: https://developers.facebook.com/docs/php/gettingstarted/#install
$config = array();
$config['appId'] = 'xxxxxxxxxxx';
$config['secret'] = 'xxxxxxxxxxxxxxxx';
$config['fileUpload'] = true; // optional
$fb = new Facebook($config);
// define your POST parameters (replace with your own values)
// see: https://developers.facebook.com/docs/facebook-login/access-tokens/
$params = array();
if(isset($temp_array['AccessToken'])) {
$params['access_token'] = $temp_array['AccessToken'];
}
if(isset($msg)) {
$params['message'] = $msg;
}
if(isset($url)) {
$params['link'] = $url;
}
if(isset($pic)) {
$params['picture'] = $pic;
}
//"name" => "yooo",
//"caption" => "www.pontikis.net",
//"description" => "Automatically post on Facebook with PHP using Facebook PHP SDK. How to create a Facebook app. Obtain and extend Facebook access tokens. Cron automation."
// post to Facebook
// see: https://developers.facebook.com/docs/reference/php/facebook-api/
try {
//tim .. 1471145939793099
// van .. 1491737127730006
// mc .. 796523467054680
$ret = $fb->api("/".$temp_array['userID']."/feed", 'POST', $params);
echo "<br>Successfully posted to Facebook account ".$post.". <br/>";
}
catch(Exception $e) {
echo $e->getMessage();
}
}

How can I get both Facebook and Twitter data on the same page through both API calls ? My script isn't working [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I haven't been successful to receive help on this one on stackoverflow before, I already know how to pull tweets using the twitter API and how to pull facebook statuses using the Graph API .My question is this one ...and I know it's technically possible because klout.com does it . I would like to be able to let users of my websites sign in through Twitter , get the tweets of the people they follow , which already works, But at the same time , once already logged in with Twitter , I'd like to give them the option to connect to their facebook accounts , and view their FACEBOOK statuses ON TOP of their tweets of twitter and display both the tweets and FB statuses on the same page .It's technically possible because when I log on klout.com through twitter, it gives me the option to connect my facebook account and see both my twitter and facebook data . Below is the code I tried to implement but it won't work !!
// This twitter part works once logged in through twitter.
<?php
session_start();
require_once ('../madscore/twitter/twitteroauth/twitteroauth.php');
require_once ('../madscore/twitter/config.php');
require ('../madscore/database/connect.php');
/* If access tokens are not available redirect to connect page. */
if (empty($_SESSION['access_token']) || empty($_SESSION['access_token']['oauth_token']) || empty($_SESSION['access_token']['oauth_token_secret'])) {
header('Location: ./clearsessions.php');
}
/* Get user access tokens out of the session. */
$access_token = $_SESSION['access_token'];
/* Create a TwitterOauth object with consumer/user tokens. */
$handle = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']);
?>
// This is the part where I call the authentications service for Facebook through the require authentication.php file , which I also copied and pasted below.
<?php
require "../madscore/authentication.php";
// $config['baseurl'] ="../index3.php";
//if user is logged in and session is valid.
if ($fbme) {
//Retriving movies those are user like using graph api
try {
$movies = $facebook->api('/me/movies');
$pages = $facebook->api('/me/likes');
}
catch(Exception $o) {
d($o);
}
//Calling users.getinfo legacy api call example
try {
$param = array('method' => 'users.getinfo', 'uids' => $fbme['id'], 'fields' => 'name,current_location,profile_url', 'callback' => '');
$userInfo = $facebook->api($param);
}
catch(Exception $o) {
d($o);
}
//update user's status using graph api
if (isset($_POST['tt'])) {
try {
$statusUpdate = $facebook->api('/me/feed', 'post', array('message' => $_POST['tt'], 'cb' => ''));
}
catch(FacebookApiException $e) {
d($e);
}
}
//fql query example using legacy method call and passing parameter
try {
//get user id
$uid = $facebook->getUser();
//or you can use $uid = $fbme['id'];
$fql = "SELECT pic_square
FROM user
WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = me())";
$param = array('method' => 'fql.query', 'query' => $fql, 'callback' => '');
$fqlResult = $facebook->api($param);
}
catch(Exception $o) {
d($o);
}
}
?>
// This displays my twitter followers , and it works .. but below this code when i try to actually display data from facebook , nothing happens ..
<?php
$followers = $handle->get('friends/list', array('screen_name' => $screen_name));
$json = json_encode($followers);
$array = json_decode($json, true);
shuffle($array);
if (is_array($array)) {
foreach ($array as $value) {
if (is_array($value)) {
foreach ($value as $key => $second) {
if (is_array($second)) {
foreach ($second as $key_second => $third) if ($key_second != 'profile_image_url') {
unset($key_second);
} else {
echo "<img src='" . $third . "' width='100' height='100'/>";
}
}
}
}
}
}
?>
//Testing if facebook data gets returned here .. nothing happens ..
<?php var_dump($fbme); ?>
//this is the authentication file from the require statement for facebook(authentication.php)
<?php
$fbconfig['appid'] = "314216702389099";
$fbconfig['api'] = "314286708589099";
$fbconfig['secret'] = "8f803e0f9e9da4f2ba9f23ad3bd00ded";
try {
include_once "../madscore/facebook/facebook-sdk/src/facebook.php";
}
catch(Exception $o) {
echo '<pre>';
print_r($o);
echo '</pre>';
}
// Create our Application instance.
$facebook = new Facebook(array('appId' => $fbconfig['appid'], 'secret' => $fbconfig['secret'], 'cookie' => true,));
// We may or may not have this data based on a $_GET or $_COOKIE based session.
// If we get a session here, it means we found a correctly signed session using
// the Application Secret only Facebook and the Application know. We dont know
// if it is still valid until we make an API call using the session. A session
// can become invalid if it has already expired (should not be getting the
// session back in this case) or if the user logged out of Facebook.
$session = $facebook->getUser();
$fbme = null;
// Session based graph API call.
if ($session) {
try {
$uid = $facebook->getUser();
$fbme = $facebook->api('/me');
}
catch(FacebookApiException $e) {
// d($e);
}
}
function d($d) {
echo '<pre>';
print_r($d);
echo '</pre>';
}
?>
but when I try to var_dump the variable of facebook to show if I am even logged in , nothing gets returned
You are testing the value of the variable $fbme at the very top and in the the middle of your code.
Before you invoke the Facebook API.
Before you actually populate the variable.
Both of which happen at the bottom of your code.
PHP is executed in order. You can not retrieve the value of a variable before it has been set.
Even if your code is in order, you are completely discarding any exceptions that the Facebook API may be returning.

Can not connect to Facebook with a curl request

I have created a simple Facebook application some weeks ago. I was getting user information through the Facebook API by asking permission from the users. But it stopped working last week out of nothing and I have been looking for an answer since then.
Basically I used to use file_get_contents to get the user information from Facebook API. But I tried changing it to cURL after it started failing, but still not working. I tried using the Facebook PHP-SDK, even debugged the code to makeRequest method, but I get the same return in all methods.
When a cURL request is made to Facebook Open Graph URL, the request fails either with error number 7 or 28. They are both error codes for unable to connect to the site or getting time out.
My site is on a shared hosting, I have tried using cURL to get other sites, and It works fine. But when I try to get even http://www.facebook.com, cURL returns FALSE.
The hosting has SSL certificate, has cURL enabled etc. And it was working fine some time ago. I have read through various threads and posts about this, tried many different cURL options, and none of them seem to work.
Any ideas?
index.php
$auth_url = "https://www.facebook.com/dialog/oauth?client_id=" . $app_id . "&redirect_uri=" . urlencode($GLOBALS['canvas_page']) . "&scope=publish_stream,email";
$signed_request = $_POST["signed_request"];
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
$data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true);
if (empty($data["user_id"])) {
echo("<script> top.location.href='" . $auth_url . "'</script>");
} else {
$_SESSION['oauth_token'] = $data['oauth_token'];
$_SESSION['user_id'] = $data["user_id"];
$user = new User($_SESSION['user_id'], $_SESSION['oauth_token']);
User class
function __construct($fid, $at) {
$this->facebook = new Facebook(array(
'appId' => "<APP_ID>",
'secret' => "<FACEBOOK_SECRET_ID>",
));
$this->fid = $fid;
$this->token = $at;
if ($data = $this->getGraph()) {
...
}
}
public function getGraph() {
$session = $this->facebook->getUser();
if ($session) {
try {
$access_token = $this->facebook->getAccessToken();
$attachment = array('access_token' => $access_token);
//$result = $this->facebook->api('/' . $this->fid, 'GET', $attachment);
$result = $this->facebook->api('/' . $this->fid, 'GET');
return $result;
} catch (FacebookApiException $e) {
return false;
}
}
}
Notes:
After checking the Facebook PHP SDK methods, I've realized that I do not need to send access token, as it will set it if access token is not in the $params.
It goes down to makeRequest() method in sdk, and returns false from the curl_exec.
Apparently this is related with the round-robin DNS structure of Facebook. I guess one of the addresses of the Facebook failed and the server was still trying to connect to that address because of the DNS cache.
The hosting provider had to clear their DNS caches to resolve the problem.
For more information about the round-robin DNS, you may visit http://en.wikipedia.org/wiki/Round-robin_DNS.

Error 403 when trying to Twitter "Send User to Authorization" step (PHP OAuth)

I have spent a ton of hours on this and cannot for the life of me figure out what the problem is here. I am writing my own twitter web app. I downloaded the OAuth PHP Library which is what I am using. Everything was setup correctly.
I did Step 1 and "Acquire a Request Token". I got a correct response back with a token, token secret and callback confirmed of TRUE.
Now I proceeded to the next step of "Send User to Authorization" and passed along the oauth_token parameter to the request. The request got sent and redirects to the Twitter page, but when it gets there is is showing an error message of :
Exception Request failed with code 403:
Woah there!
This page requires some information that was not provided. Please return to the site that sent you to this page and try again … it was probably an honest mistake.
What is the problem?? The error message is not very helpful. According to Twitter 403 means the request was understood but denied. I am really stuck here and would appreciate the help with this one.
Here is what the code looks like (I have obviously replaces my token and secret keys with ########, so if anyone wanted to test this locally with their own keys, just replace the ######### values:
<?php
include_once "scripts/OAuth/OAuthStore.php";
include_once "scripts/OAuth/OAuthRequester.php";
// register at http://twitter.com/oauth_clients and fill these two
define("TWITTER_CONSUMER_KEY", "#############");
define("TWITTER_CONSUMER_SECRET", "#############");
define("TWITTER_OAUTH_HOST","https://api.twitter.com");
define("TWITTER_REQUEST_TOKEN_URL", TWITTER_OAUTH_HOST . "/oauth/request_token");
define("TWITTER_AUTHORIZE_URL", TWITTER_OAUTH_HOST . "/oauth/authorize");
define("TWITTER_ACCESS_TOKEN_URL", TWITTER_OAUTH_HOST . "/oauth/access_token");
define("TWITTER_PUBLIC_TIMELINE_API", TWITTER_OAUTH_HOST . "/statuses/public_timeline.json");
define("TWITTER_UPDATE_STATUS_API", TWITTER_OAUTH_HOST . "/statuses/update.json");
define('OAUTH_TMP_DIR', function_exists('sys_get_temp_dir') ? sys_get_temp_dir() : realpath($_ENV["TMP"]));
// Twitter test
$options = array('consumer_key' => TWITTER_CONSUMER_KEY, 'consumer_secret' => TWITTER_CONSUMER_SECRET);
OAuthStore::instance("2Leg", $options);
try
{
// Obtain a request object for the request we want to make
$request = new OAuthRequester(TWITTER_REQUEST_TOKEN_URL, "POST");
$result = $request->doRequest(0);
parse_str($result['body'], $params);
list($token, $secret, $status) = explode('&', $result['body']);
// now make the request.
$request = new OAuthRequester(TWITTER_AUTHORIZE_URL, 'POST', $token);
$result = $request->doRequest();
}
catch(OAuthException2 $e)
{
echo "Exception " . $e->getMessage();
}
?>

Categories