Reading data from Facebook graphObject - facebook

A user has accepted my Facebook app. I can now access some of their data. It is returned as a graphObject, which contains something like:
Facebook\GraphObject Object ( [backingData:protected] => Array ( [id] => 11111 [first_name] => Bob [gender] => male [last_name] => Builder [link] => https://www.facebook.com/app_scoped_user_id/11111/ [locale] => de_DE [name] => Bob Builder [timezone] => 2 [updated_time] => 2014-02-14T14:35:54+0000 [verified] => 1 ) )
Unfortunately I cannot get at the data inside this object. Reading it like an array throws an error:
$fbid = $graphObject['id']; // Cannot use object of type Facebook\GraphObject as array
$fbid = $graphObject->id; // Undefined property: Facebook\GraphObject::$id
How can I get at the ID?

If you have casted the response as a GraphObject by using one of the following two methods:
// Get the response typed as a GraphLocation
$loc = $response->getGraphObject(GraphLocation::className());
// or convert the base object previously accessed
// $loc = $object->cast(GraphLocation::className());
You can use the Get properties of the graph object, depending on what kind of object you've casted it as... here's an example for the GraphUser Object:
echo $user->getName();
Or, if you know the name of the property (as shown in the base data), you can use getProperty():
echo $object->getProperty('name');
So in your example, you can use the following to get the id property:
echo $user->getProperty('id');
More examples and documentation here

In the New version of Graph API getProperty does not work.
For the New version Graph API v2.5 of Facebook Read read data as below :
$fb = new \Facebook\Facebook([
'app_id' => 'APPIDHERE',
'app_secret' => 'SECRET HERE',
'default_graph_version' => 'v2.5',
]);
$asscee_t ="ACCESS TOKEN HERE";
$response = $fb->get('/me/friends', $asscee_t);
$get_data = $response->getDecodedBody(); // for Array resonse
//$get_data = $response->getDecodedBody(); // For Json format result only
echo $get_data['summary']['total_count']; die; // Get total number of Friends

Note that from API version >= 5.0.0 getProperty() has been renamed to getField(). It will be removed from >= v6. So
Instead of
$user->getProperty('name')
Use
$user->getField('name')

Related

Does tweet_mode=extended work with the Twitter statuses/user_timeline API?

There is no mention of tweet_mode at https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline.html
I am wondering if perhaps I am using the wrong API to be able to take advantage of tweet_mode?
In my application, I supplied the tweet_mode=extended argument and it had no effect. My code...
// Load the Tweets.
$args = array(
'screen_name' => $username,
'exclude_replies' => 'true',
'include_rts' => 'true',
'tweet_mode' => 'extended',
'count' => $numitems,
);
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
$tweets = $connection->get('statuses/user_timeline', $args);
if (!empty($tweets)) {
foreach ($tweets as $tweet) {
$text = $tweet->full_text;
// etcetera
Yes, you can use tweet_mode with the statuses/user_timeline API. Retweets are a special case, though. Check the retweeted_status object, as described at https://dev.to/kehers/formatting-tweets-a-look-at-extended-tweets-retweets-and-quotes-n5j
In short, if a tweet is a retweet, the extended tweet must be accessed at $tweet->retweeted_status->full_text. Thus, it's necessary in your code to check if each tweet object has a retweeted_status property.

Unable to get Response Parameters in Notification and Success url SOFORT API

public function sofyAction()
{
$args = [ 'config_key' => $this->getConfigKey() ];
$sofy = new Api($args);
$helper = $this->getServiceLocator()->get('ViewHelperManager')->get('ServerUrl');
$successUrl = $helper($this->url()->fromRoute('sofort_response'));
$params = [
'amount' => 1500,
'currency_code' => 'EUR',
'reason' => 'Vouhcer Order',
'success_url' => $successUrl,
'customer_protection' => false,
'notification_url' => 'MY_PRIVATE_RESPONSE_URL',
];
$trans = $sofy->createTransaction($params);
return $this->redirect()->toUrl($trans['payment_url']);
}
How to get response and transaction ID as given it API document in Notification URL and on success URL too , please unable to find any help or guide for it ?
The easiest way is to let Payum do notification related job for you. To do so you either:
have to create manually a notification token using Payum's token factory (I am not sure it is present in the Zend module, it is quite old). Use the token as notification_url. Nothing more. Sofort will send a request to that url and Payum does the rest.
Make sure the token factory is passed to a gateway object and later is injected to capture action object. Leave the notification_url field empty and Payum will generate a new one.
use your own url as notification one and add there all the info you need (as a query string). I wouldn't recommend it since you expose sensitive data and once could try to exploit it.
I solved it this way by appending ?trx=-TRANSACTION- with success and notification url and than in response i recieved Transaction id as parameter and later loaded TransactionData with that transactionId . Payum Token way wasn't working for me ! Obiously had to use its config key to create Payum/Sofort/Api isnstance,
REQUEST:
$args = [ 'config_key' => $sofortConfigKey ];
$sofortPay = new Api($args);
// ?trx=-TRANSACTION- will append transacion ID as response param !
$params = [
'amount' => $coupon['price'],
'currency_code' => $coupon['currency'],
'reason' => $coupon['description'],
'success_url' => $successUrl.'?trx=-TRANSACTION-',
'abort_url' => $abortUrl.'?trx=-TRANSACTION-',
'customer_protection' => false,
'notification_url' => '_URL_'.'?trx=-TRANSACTION-',
];
$transactionParams = $sofortPay->createTransaction($params);
return $this->redirect()->toUrl($transactionParams['payment_url']);
RESPONSE:
$args = [ 'config_key' => $configKey ];
$sofy = new Api( $args );
$transNumber = $this->getRequest()->getQuery('trx');
$fields = $sofy->getTransactionData($transNumber);
Took help from API document. Payum documentation is worst. SOFORT API DOC

Linkedin: How to make api calls using access token?

I am storing the linkedin access token in database. This is the token that is stored in my database:
oauth_token=xxxxxxxxxxxxxxxxxxx&oauth_token_secret=xxxxxxxxxxxxxxxxxxx&oauth_expires_in=5183998&oauth_authorization_expires_in=5183998
I want to retrieve the linkedin connections using this access token. I am trying to make a call like this:
$a = new Zend_Oauth_Token_Access();
$client = $a->getHttpClient( array(
'siteUrl' => LIN_SITE_URL,
'callbackUrl' => LIN_SITE_CALLBACK_URL,
'requestTokenUrl' => LIN_REQUEST_TOKEN_URL,
'userAuthorizationUrl' => LIN_USER_AUTHORIZATION_URL,
'accessTokenUrl' => LIN_ACCESS_TOKEN_URL,
'consumerKey' => LIN_CONSUMER_KEY,
'consumerSecret' => LIN_CONSUMER_SECRET
) );
$client->setUri('http://api.linkedin.com/v1/people/~/connections:(id,first-name,last-name,picture-url)');
$client->setParameterGet('token',$linToken);
$client->setMethod(Zend_Http_Client::GET);
$response = $client->request();
$content = $response->getBody();
$data = json_decode(Zend_Json::fromXml($content, false));
print_r($data); echo "<br/>";
The error i am getting here is:
stdClass Object ( [error] => stdClass Object ( [status] => 404 [timestamp] => 1349429996351 [request-id] => 8U8A1UNF1V [error-code] => 0 [message] => Could not find person based on: ~ ) )
Is this the correct way to make a call or am i doing something wrong here. I am using zend framework.
Thanks.
I was able to solve the problem by passing the outh_token and outh_token_secret as an array to the setParams() of Zend_Oauth_Token_Access as below:
$a = new Zend_Oauth_Token_Access;
$a->setParams(array(
'oauth_token' => 'xxxxxxxxxxxxxxxxxxxxxxxxxx',
'oauth_token_secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx'
));
In your code example I don't see where you're setting the access token and secret. I just see that you're instantiating the $a variable:
$a = new Zend_Oauth_Token_Access();
Are you retrieving the access token and secret from you database then setting it to the $a variable? Something like this:
$a->setToken($row['token'])
->setTokenSecret($row['secret']);
By the way, this is a good reference for using Zend and LinkedIn: http://www.contentwithstyle.co.uk/content/linkedin-and-zendoauth/

Bing Custom Search Engine

What parameters should I use in order to get search result from only a site say abcd.com using bing 2.0 API? I am trying to fetch results in JSON format. Can anybody help?
fresh code to the masses
$query = array
(
'AppId' => <API_KEY>,
'sources' => 'Web',
'query' => 'site:www.tipografix.ro '.$keywords,
'Version' => '2.0',
'Options' => 'EnableHighlighting',
'Web.Count' => $per_page,
'Web.Offset' => $page_num,
'Web.Options' => 'DisableHostCollapsing DisableQueryAlterations'
);
$request = 'http://api.bing.net/json.aspx?'.http_build_query($query);
$response = file_get_contents($request);
$jsonobj = json_decode($response);
Not sure how the JSON format of the API works but in the query parameter put in "site:abcd.com bacon" where bacon is your original query.
I'm using the XML format so if I'd send a request to:
http://api.search.live.net/xml.aspx?Appid=________&query=site%3Aabcd.com+bacon&sources=web&web.count=5&web.offset=0

How to programmatically add an event to a page using Graph API?

Is it possible to programmatically add an event to a page using Facebook Graph API?
If yes, what HTTP request shall be made?
For example, Startup Weekend has events on its Facebook page.
These events can be added using Graph API Event object?
UPDATE
Creating event with the API is no longer possible in v2.0+. Check: https://developers.facebook.com/docs/apps/changelog#v2_0
Yes it's possible.
Permissions:
create_event
manage_pages
So first you get the page id and its access token, through:
$facebook->api("/me/accounts");
The Result will be something like:
Array
(
[data] => Array
(
[0] => Array
(
[name] => Page Name
[category] => Website
[id] => XXXXXX
[access_token] => XXXXX
)
[1] => Array
(
[name] => Page Name 2
[category] => Company
[id] => XXXXXXX
[access_token] => XXXXXXXX
)
)
)
UPDATE: To retrieve the page's access_token you could now call the page object directly like:
$page_info = $facebook->api("/PAGE_ID?fields=access_token");
The access token, if successful call, should be accessible: $page_info['access_token']
Now you get the Page ID and access token and use the events connection:
$nextWeek = time() + (7 * 24 * 60 * 60);
$event_param = array(
"access_token" => "XXXXXXXX",
"name" => "My Page Event",
"start_time" => $nextWeek,
"location" => "Beirut"
);
$event_id = $facebook->api("/PAGE_ID/events", "POST", $event_param);
And you are done! :-)