i want to make an 2 legged oauth yql request with php.
So far:
// Include the PHP SDK.
include_once("yosdk/lib/Yahoo.inc");
// Define constants to store your API Key (Consumer Key) and
// Shared Secret (Consumer Secret).
define("API_KEY","her_comes the key");
define("SHARED_SECRET","here_comes_the_secret");
$two_legged_app = new YahooApplication(API_KEY,SHARED_SECRET);
$stock_query = "elect * from ......";
$stockResponse = $two_legged_app->query($stock_query);
var_dump($stockrResponse);
But the problem is, that i dont want to query the command line..... i just want to oauth with the api key i got and use the url directly i got of the command when i typed in yql....
like this:
$url='http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20('+url_stocks+')&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys';
(i edited the url that came out my wishes for).Please dont ask why i dont use the command to query (long story). i would be pleased by getting some help.
thanks.
solved it:
http://code.google.com/p/oauth-php/wiki/ConsumerHowTo
include_once "oauth/library/OAuthStore.php";
include_once"oauth/library/OAuthRequester.php";
$key_1 = "your_key"; $secret_1 = "your_secret";
$ticks="%22AAPL%22%2C%22MSFT%22";
$options = array( 'consumer_key' => $key_1, 'consumer_secret' =>
$secret_1 ); OAuthStore::instance("2Leg", $options );
$url =
"http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20('$ticks')&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
// this is the URL of the request $method = "GET"; // you can also use
POST instead $params = null;
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'];
$resp_array=json_decode($response,TRUE);
echo $resp_array['query']['results']['quote'][1]['symbol']; // MSFT
} catch(OAuthException2 $e) { }
Related
I am using twitter account activity api's to send/receive messages. In it i am facing problem in generating webhook. First time it was created successfully. In webhook file i am saving messages in database when each time message sent or received. But when I sent message nothing goes in database. Here is webhook file:
const APP_CONSUMER_SECRET = '**********';
// Example token provided by incoming GET request
if(isset($_REQUEST['crc_token'])) {
$token = $_REQUEST['crc_token'];
/**
* Creates a HMAC SHA-256 hash created from the app TOKEN and
* your app Consumer Secret.
* #param token the token provided by the incoming GET request
* #return string
*/
function get_challenge_response($token) {
$hash = hash_hmac('sha256', $token, APP_CONSUMER_SECRET, true);
$response = array(
'response_token' => 'sha256=' . base64_encode($hash)
);
return json_encode($response);
}
}else{
$feedData = file_get_contents('php://input');
$handleData = fopen('twitterDemo.txt', "w" );
fwrite($handleData,$feedData);
fclose($handleData);
$array = json_decode(file_get_contents('php://input'), true);
if (isset($array['direct_message_events'][0]['type']) && $array['direct_message_events'][0]['type'] == 'message_create' ) {
include_once ('config.php');
include_once ('database-queries.php');
$message = $array['direct_message_events'][0]['message_create']['message_data']['text'];
$sender = $array['direct_message_events'][0]['message_create']['sender_id'];
$from = $array['direct_message_events'][0]['message_create']['target']['recipient_id'];
$message_type = 'incoming';
$message_status = 'unread';
$userId = $sender;
$account_name = 'twitter';
$image_url = '';
if(isset($array['direct_message_events'][0]['message_create']['message_data']['attachment'])){
$image_url = "Not Image";
}
$data = array('to'=>$from, 'from'=>$sender, 'msg'=>$message,'image_url' =>$image_url);
insert($data, $account_name, $message_type, $message_status, $conn);
}
}
I thought there might be webhook problem so i deleted the existing app and create new one and set development environment label for it with new name. But for it when i tried to create webhook it gives me error:
[code] => 214 [message] => Webhook URL does not meet the requirements.
Invalid CRC token or json response format.
I dont know whats happening here now. I am using this api to create webhook url
$url = "https://example.com/twitter/webhook.php";
$result = $connection->post("account_activity/all/env_name/webhooks", ["url" => $url]);
Can anyone please help me this out. Any help will be appreciated.
Thanks!
I ran into the same error message.
The problem seem to be that the
if(isset($_REQUEST['crc_token']))
is not working anymore. Though the token is set. I don't know what is causing the problem but when I let the code just fetch the $_REQUEST['crc_token'] and create and print the hash its working.
But I see your code is not calling the get_challenge_response($token) function.
I think
print get_challenge_response($token)
may help? If the Webhook was deactivated by twitter you have to initiate another CRC check:
https://developer.twitter.com/en/docs/twitter-api/v1/accounts-and-users/subscribe-account-activity/guides/securing-webhooks
Your app can also trigger a CRC when needed by making a PUT request with your webhook id. Triggering a CRC is useful as you develop your webhook application, after deploying new code and restarting your service.
I was performing Google Sign in on Android Application for the first time. At the client side, I obtained the access token and sent to the PHP server via POST.
By referring to Google's Documentation, the code I used in backend is as follows:
$id_token = $_POST['id_token'];
$CLIENT_ID = "** MY WEB APPLICATION CLIENT ID **";
$client = new Google_Client(['client_id' => $CLIENT_ID]);
$client->setAuthConfigFile('client_secret.json');
...
$payload = $client->verifyIdToken($id_token);
if ($payload) {
$userid = $payload['sub'];
} else {
echo "Invalid Token";
}
When obtaining user id, the error is : "Cannot use object of type Google_Auth_LoginTicket as array"
I am pretty new to Google sign in. Please point out what all has gone wrong.
Found It. I made some modifications to the code
$token_data = $client->verifyIdToken($id_token)->getAttributes();
$user_id = $token_data['payload']['sub'];
Now the user id is retrieved fine.
I'm trying to create a instagram app using the php library which is here(its not very long file, don't worry):
http://pastie.org/3391787
I'm trying to authorise the user by using OAUTH, which works perfectly, and the authorised(current user) can see his information(like Image, name etc...), but when i refresh the page it all goes and I'm left with blank data, heres the code -
// Instantiate the API handler object
$instagram = new Instagram($config);
$accessToken = $instagram->getAccessToken();
$_SESSION['InstagramAccessToken'] = $accessToken;
$instagram->setAccessToken($_SESSION['InstagramAccessToken']);
$userinfo = $instagram->getUser($_SESSION['InstagramAccessToken']);
// After getting the response, let's iterate the payload
$ures = json_decode($userinfo, true);
this code works fine the first time round, but when you refresh the page, the information is not being retrieved, and that could only mean one thing, that the session or the cookie is not set properly and thats why the getUser method is not retrieving the information,
$userinfo = $instagram->getUser($_SESSION['InstagramAccessToken']);
please can you shed some light into this problem, i have been trying for 4 hours!!
On each your request you overwrite current session data with nothing by this line:
$_SESSION['InstagramAccessToken'] = $accessToken;
Most likely this is how it should look like:
$instagram = new Instagram($config);
if (!empty($_SESSION['InstagramAccessToken'])) {
$accessToken = $instagram->getAccessToken();
$_SESSION['InstagramAccessToken'] = $accessToken;
} else {
$instagram->setAccessToken($_SESSION['InstagramAccessToken']);
}
$userinfo = $instagram->getUser($_SESSION['InstagramAccessToken']);
// After getting the response, let's iterate the payload
$ures = json_decode($userinfo, true);
Im using the following code to read to consumer_key and consumer_secret from config.php, pass it to twitter and retrieve some bits of information back from them.
What the script below attempts to do is 'cache' the request_token and request_secret. So in theory I should be able to reuse those details (all 4 of them to automatically tweet when required).
<?php
require_once('twitteroauth/twitteroauth.php');
require_once('config.php');
$consumer_key = CONSUMER_KEY;
$consumer_secret = CONSUMER_SECRET;
if (isset($_GET["register"]))
{
// If the "register" parameter is set we create a new TwitterOAuth object
// and request a token
/* Build TwitterOAuth object with client credentials. */
$oauth = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
$request = $oauth->getRequestToken();
$request_token = $request["oauth_token"];
$request_token_secret = $request["oauth_token_secret"];
// At this I store the two request tokens somewhere.
file_put_contents("request_token", $request_token);
file_put_contents("request_token_secret", $request_token_secret);
// Generate a request link and output it
$request_link = $oauth->getAuthorizeURL($request);
echo "Request here: " . $request_link . "";
die();
}
elseif (isset($_GET["validate"]))
{
// This is the validation part. I read the stored request
// tokens.
$request_token = file_get_contents("request_token");
$request_token_secret = file_get_contents("request_token_secret");
// Initiate a new TwitterOAuth object. This time we provide them with more details:
// The request token and the request token secret
$oauth = new TwitterOAuth($consumer_key, $consumer_secret,
$request_token, $request_token_secret);
// Ask Twitter for an access token (and an access token secret)
$request = $oauth->getAccessToken();
// There we go
$access_token = $request['oauth_token'];
$access_token_secret = $request['oauth_token_secret'];
// Now store the two tokens into another file (or database or whatever):
file_put_contents("access_token", $access_token);
file_put_contents("access_token_secret", $access_token_secret);
// Great! Now we've got the access tokens stored.
// Let's verify credentials and output the username.
// Note that this time we're passing TwitterOAuth the access tokens.
$oauth = new TwitterOAuth($consumer_key, $consumer_secret,
$access_token, $access_token_secret);
// Send an API request to verify credentials
$credentials = $oauth->oAuthRequest('https://twitter.com/account/verify_credentials.xml', 'GET', array());
// Parse the result (assuming you've got simplexml installed)
$credentials = simplexml_load_string($credentials);
var_dump($credentials);
// And finaly output some text
echo "Access token saved! Authorized as #" . $credentials->screen_name;
die();
}
?>
When i run /?verify&oauth_token=0000000000000000 - It works however trying to resuse the generated tokens etc... I get a 401
Here is the last bit of code where I attempt to reuse the details from Twitter combined with my consumer_key and consumer_secret and get the 401:
require_once('twitteroauth/twitteroauth.php');
require_once('config.php');
// Read the access tokens
$access_token = file_get_contents("access_token");
$access_token_secret = file_get_contents("access_token_secret");
// Initiate a TwitterOAuth using those access tokens
$oauth = new TwitterOAuth($consumer_key, $consumer_key_secret,
$access_token, $access_token_secret);
// Post an update to Twitter via your application:
$oauth->OAuthRequest('https://twitter.com/statuses/update.xml',
array('status' => "Hey! I'm posting via #OAuth!"), 'POST');
Not sure whats going wrong, are you able to cache the details or do i need to try something else?
You can't store the OAuth tokens in cache and to more than 1 request with it, as OAuth is there to help make the system secure, your "oauth_token" will contain some unique data, this token will only be able to make one call back to twitter, as soon as the call was made, that "oauth_token" is no longer valid, and the OAuth class should request a new "oauth_token", thus making sure that every call that was made is secure.
That is why you are getting an "401 unauthorized" error on the second time as the token is no longer valid.
twitter is still using OAuth v1 (v2 is still in the draft process even though facebook and google already implemented it in some parts)
The image below describes the flow of the OAuth authentication.
Hope it helps.
A while ago I used this to connect to twitter and send tweets, just note that it did make use of some Zend classes as the project was running on a zend server.
require_once 'Zend/Service/Twitter.php';
class Twitter {
protected $_username = '<your_twitter_username>';
protected $_token = '<your_twitter_access_token>';
protected $_secret = '<your_twitter_access_token_secret>';
protected $_twitter = NULL;
//class constructor
public function __construct() {
$this->getTwitter();
}
//singleton twitter object
protected function getTwitter() {
if (null === $this->_twitter) {
$accessToken = new Zend_Oauth_Token_Access;
$accessToken->setToken($this->_token)
->setTokenSecret($this->_secret);
$this->_twitter = new Zend_Service_Twitter(array(
'username' => $this->_username,
'accessToken' => $accessToken,
));
$response = $this->_twitter->account->verifyCredentials();
if ($response->isError()) {
throw new Zend_Exception('Provided credentials for Twitter log writer are wrong');
}
}
return $this->_twitter;
}
//send a status message to twitter
public function update( $tweet ) {
$this->getTwitter()->status->update($tweet);
}
}
In your second script, it looks like you aren't setting the Consumer Key and Consumer Secret when you create your TwitterOAuth instance.
// Initiate a TwitterOAuth using those access tokens
$oauth = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token, $access_token_secret);
I want to read all birthdays of the friends from current user. I use the new Graph API of facebook. I request the authorization of the permissions (read_friendslist and friends_birthday) based on Facebooks insights example and php-sdk example. For reading the friendslist and the user details I used the Graph API with Facebook PHP SDK.
The upcoming code snippets are a short self contained correct example of my approach. If I try to use my app it requests login, then asks for permissions and then fails in printing all my friends due to the fact that no session is available. What's wrong here?
First is the birthday.php which is used by the following index.php, I removed some boilerplate code or code I think it's not causing this problem (identified by [...]). You can find the complete code on the end of this question.
<?php
function get_birthday_of_friends() {
$fbconfig['appid' ] = "MY_APP_ID";
$fbconfig['secret'] = "MY_APP_SECRET";
try{
include_once "facebook/src/facebook.php";
}
catch(Exception $o){
// [...] log error
}
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => $fbconfig['appid'],
'secret' => $fbconfig['secret'],
'cookie' => true,
));
$session = $facebook->getSession();
$fbme = null;
// Session based graph API call.
if ($session) {
// [...] return birthdays
} else {
echo "No session found";
}
}
?>
The required lib.php is identically with the insights example.
<?php
// [...] Include and define app-id etc.
function get_access_token($base_url) {
if (isset($_REQUEST['access_token'])) {
return $_REQUEST['access_token'];
}
$params = array();
$params['client_id'] = APP_ID;
$params['redirect_uri'] = $base_url;
if (!isset($_REQUEST['code'])) {
$params['scope'] = 'read_friendlists, friends_birthday';
$url = FacebookMethods::getGraphApiUrl('oauth/authorize', $params);
throw new RedirectionException($url);
} else {
$params['client_secret'] = APP_SECRET;
$params['code'] = $_REQUEST['code'];
$url = FacebookMethods::getGraphApiUrl('oauth/access_token');
$response = FacebookMethods::fetchUrl($url, $params);
$response = strstr($response, 'access_token=');
$result = substr($response, 13);
$pos = strpos($result, '&');
if ($pos !== false) {
$result = substr($result, 0, $pos);
}
return $result;
}
}
// [...] Call get_access_token() and get_birthday_of_friends()!
?>
Can you help me with that? I added the whole source code on pastebin.com if this helps you to identify my problem. Source code on pastebin.com for "index.php" and "birthday.php".
Thank you in advance!
I am not sure if the method that you are using is deprecated or not, but I know it's the old way and you should try with the new one in order to get the auth token.
Take a look at this link:
http://developers.facebook.com/docs/authentication/signed_request/
In a glance, you have to:
Get the signed_request parameter from $_REQUEST.
Use the sample function provided in
the link to decode it Once you decode
it, you will have an array in which
there is a parameter called
oauth_token.
With this parameter, you can start
making calls to the Graph by
appending it to the URL e.g.
*https://graph.facebook.com/PROFILE_ID/pictures/?access_token=OAUTH_TOKEN*
Make sure that you have Oauth 2.0 for Canvas enabled into the Configuration settings of your app (Advanced tab).
I think in some browsers there's a prblem with third party cookies. Are you testing in Safari? And also, try to add permissions to the loginUrl - it's a bit more simple than adding and requesting the permissions with oauth.
If no session is available, I had to redirect to the login page and require the extended permissions with the parameters. This did the trick to me, thanks to manuelpedrera for helping me out.
$facebook->getLoginUrl(array('req_perms' => 'read_friendlists, [...]'));