Can I use the Facebook PHP SDK in Spotify apps? - php

I need to be able to post information from my application to the user's timeline. Now, the only way I know how to do that is with the Facebook PHP SDK. The thing is, since I use the standard JavaScript way to connect with Facebook's login, when I try to get the user id with the PHP SDK, it says it's 0. Is there any way I can use the PHP SDK, or is there just no way to post to Facebook from a Spotify application?
Also, can I use the PHP SDK as well for logging in instead of the standard code that looks like this:
function facebook(){
auth.authenticateWithFacebook('119914501490688', ['user_about_me', 'user_checkins'], {
onSuccess : function(accessToken, ttl) {
console.log("Success! Here's the access token: " + accessToken);
},
onFailure : function(error) {
console.log("Authentication failed with error: " + error);
},
onComplete : function() {}
});
}

You may need to make sure that Spotify will allow access to the Facebook API endpoints by adding them to your app manifest file. See "Talking to the Outside World" in the tutorial at https://developer.spotify.com/technologies/apps/tutorial/

Related

How to get data from fitbit using PHP

I'm trying to get user data from fitbit using fitbit api but the process seems confusing to me. I have tried several ways but could not succeed. I have searched in the internet for solution and found this
http://www.staze.org/retrieving-steps-data-fitbit-api/
But this process is also not working for me.
How to fix the code I mentioned to get data from fitbit or is there any other way to get data using PHP?
You need to do lot of homwwork Dude ;) Anyways...
To access Fitbit Data you can use OAuth 2.0 authentication
You need to pass tokenType and accessCode in any ajax call and you will get response
Now to get accessCode you need to register an App on Fitbit site
You can read API doc for more details
Here is sample code how to access Fitbit Profile using tokenType and accessCode
and I can assure you this is working Code so if your code doesnt work
it means you are doing somthing wrong in above steps
function getProfile() {
var authCode = token_type + " " + access_token;
$.ajax({
url: "https://api.fitbit.com/1/user/-/profile.json",
type: "GET",
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", fitbitAccessCode);
},
success: function(jsonObject) {
// logic ...
},
error: function(error) {
alert("Error");
}
});
}

Asana project is created but ajax readystate 0

I have a php application that accesses Asana API. I am able to create a project in Asana. However, the ajax call to the API class is returning a readystate=0.
While troubleshooting in firebug I also noticed that the network console has a 302, 400(??), and 200 status code. I thought 400 status code is related to invalid request or malformed url, but the project gets created anyway.
Any idea?
Update: More information.
I have a Ajax call to a php file which intern calls Asana API to getAuth code and tokens before calling the API services.
I believe I am getting the CORS warning and hence the readystate=0 and the 400 error. However because rest of my script proceeds with the token it was inserting records anyways. However, after the tokens expired (3600 sec), now I am unable to insert records. I know if I call the php file directly it works without the CORS error.
$.ajax({
type: 'POST',
url: "oa/asana.php",
data: {apiprovider:"asana",type:"addnewproject",notes:"notes",name:"name",id:"id",resource:"projects"},
//dataType:"json",
//contentType: "application/json",
success: function(data) {
console.log(data);
},
error: function( error )
{
console.log("asana api error");
console.log(JSON.stringify(error)) ;
},
async:true
});
my php code looks like this.
...$asana = new AsanaAuth(API_KEY,API_SECRET,callbackUrl);
if (!isset($_GET['code'])) {
$url = $asana->getAuthorizeUrl();
header('Location:' . $url);
} else {
$asana->getAccessToken($_GET['code']);
if ($asana->hasError()) {
echo 'Error response code: ' . $asana->responseCode;
}
else {
echo $asana->response;
}
}
Is there a better way to do this outside of Ajax call?
OK here's how I fixed it. Partly my understanding was wrong and I made a wrong assumption.
This is purely based on my application's need and this may not be applicable to all.
I have a settings page where the user clicks on the Asana app to authorize the connection. This is not a Ajax call but a hyperlink to a file which is also my redirect uri. Within this file I check if the user has already authorized if not I call authorize, get tokens and store the refresh token in the database for future use.
In the other parts of my application, when the user clicks on create an asana project, I check for the validity of the access token if it has expired, I refresh and get another token again.
Earlier, I was trying to call this from one page (which in a normal user flow will never happen -in my application). So right now there is no Ajax call for authorize but calling the refresh token, and Asana API endpoints are through Ajax and they work fine.
Hope this helps someone in future.

Displaying a Facebook newsfeed/timeline on a website

I have a client who wants their company's Facebook newsfeed/timeline to be displayed on their website. It's not a personal timeline/newsfeed, but an organisation's.
Everything I've read seems a few years old, but the upshot appears to be: Facebook wants to keep all its data on its own servers -- they don't want people exporting it, and people have been banned for trying. (As I say, this information was several years old.)
The closest current thing I've found is the Activity Feed Plugin, but that only registers other user's interactions with the site or a FB app.
Has anyone had any success exporting their public updates to an external website, or do I have to tell my client that it can't be done?
Thanks for any help!
AFAIK, it is possible, in a way. The simplest solution, but not best for your situation could be the Like Box plugin:
The Like Box enables users to:
See how many users already like this Page, and which of their friends like it too
Read recent posts from the Page
Like the Page with one click, without needing to visit the Page
Better solution: use their Graph API, however you can only read the data(as JSON), not have the stream exactly replicated on your client's website, don't expect to be able to apply the styles that facebook uses(i.e you won't be able to scrape it), you'll have to either replicate it, or create your own styles.
Now if the page is public and can be read by all, as in there are no privacy rules, then you can simply call the url with any valid access_token(can be app access_token also):
https://graph.facebook.com/<clientpagename_OR_id>/feed
or
https://graph.facebook.com/<clientpagename_OR_id>/posts
depending on what exactly you need, try the graph api explorer to check that(and also see the kind of data being returned). When there are lots of posts, there will be pagination urls, which you'll be able to notice in the explorer too.
Incase the page is not public, you'll need an access_token with the read_stream permission, hence you'll need to create a facebook app, of type website. Then get your client's page's admin to authorize the app, with read_stream permission. After that you can call the urls with the access_token that you receive after authentication and can continue reading the stream.
https://graph.facebook.com/<clientpagename_OR_id>/posts?access_token=thetoken
In this case use the PHP SDK, to simplify authentication and calling the graph api.
Important Links: Authentication Guide , Real-time-updates.
Good luck.
Edit: you do need an access token to access the feed or posts connections, but you do not necessarily need an access token to read the page object itself, as given in this documentation.
Note from the doc:
For connections that require an access token, you can use any valid access token if the page is public and not restricted. Connections on restricted pages require a user access token and are only visible to users who meet the restriction criteria (e.g. age) set on the page.
You can retrieve the organization's newsfeed using Facebook's Graph API. Timeline can't be retrieved via public API.
There is no plugin to do this. You would need to call
https://graph.facebook.com/USER_ID/home
which gives you a JSON response.
You then need to parse the JSON into a new layout on the organization's web page.
Confusingly, calling
https://graph.facebook.com/USER_ID/feed
doesn't retrieve the newsfeed, but a user's wall posts, which may or may not be what you want.
Here is a tutorial that goes through the basics of setting up a newsfeed on a website with php.
The easiest way to do this is to read the Facebook timeline RSS:
function FacebookFeed($pagename, $count, $postlength) {
$pageID = file_get_contents('https://graph.facebook.com/?ids='.$pagename.'&fields=id');
$pageID = json_decode($pageID,true);
$pageID = $pageID[$pagename]['id'];
ini_set('user_agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.9) Gecko/20071025 Firefox/2.0.0.9');
$rssUrl = 'http://www.facebook.com/feeds/page.php?format=rss20&id='.$pageID;
$xml = simplexml_load_file($rssUrl);
$entry = $xml->channel->item;
for ($i = 0; $i < $count; $i++) {
$description_original = $entry[$i]->description;
$description_striphtml = strip_tags($description_original);
$description = substr($description_striphtml, 0, $postlength);
$link = $entry[$i]->link;
$date_original = $entry[$i]->pubDate;
$date = date('d-m-Y, H:i', strtotime($date_original));
$FB_feed .= $description."…<br>";
$FB_feed .= "<small><a href='".$link."'>".$date."</a></small><br><br>";
}
return $FB_feed;
}
Yes, it can be done. First register the web site at facebook's developer page. Than you can use any suitable API for interacting with FB. Sometimes ago I used SpringSocial (since I was working tightly with Spring)... You can use FB's own api which is also very useful you can read the tutorial here
It can definitely be done. You just need to get an access token through facebook and then you can access a JSON feed of posts through the facebook API.
You need to go to the facebook developer site and click on Apps at the top. Follow the steps to get an app secret and client ID. Then just put them into the following URL and it will return your access token:
https://graph.facebook.com/oauth/access_token?grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET
Step by step instructions here: http://smashballoon.com/custom-facebook-feed/access-token/
This document details the steps to obtain the facebook access tokens and the using the tokens to fetch FB feeds.
Example:
A live example is available in
https://newtonjoshua.com
Introduction to Graph API:
The Graph API is the primary way to get data in and out of Facebook's platform. It's a low-level HTTP-based API that you can use to query data, post new stories, manage ads, upload photos and a variety of other tasks that an app might need to do.
FaceBook Apps:
https://developers.facebook.com
Create a Facebook app. You will get an App_Id and App_Secret
Graph API Explorer:
https://developers.facebook.com/tools/explorer/{{App_Id}}/?method=GET&path=me%2Ffeed&version=v2.8
You will get an access_token which is short lived. So this will be our short_lived_access_token.
note: while creating access token select all the fb fields that you require.This will give permission to the access token to fetch those fields.
Access Token Extension:
https://graph.facebook.com/oauth/access_token?grant_type=fb_exchange_token&client_id={{App_Id}}&client_secret={{App_Secret}}&fb_exchange_token={{short-lived-access_token}}
You will get an access_token with a validity of 2 months.
Access Token Debugger:
https://developers.facebook.com/tools/debug/accesstoken?q={{access_token}}&version=v2.8
you can check check the details of the access_token.
Facebook SDK for JavaScript:
Include the below JavaScript in your HTML to asynchronously load the SDK into your page
(function (d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {
return;
}
js = d.createElement(s);
js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
Graph API:
Let's make an API call to get our FB id, profile pic, cover pic and feeds.
window.fbAsyncInit = function () {
FB.init({
appId: '{{App_Id }}',
xfbml: true,
version: 'v2.7'
});
FB.api(
'/me',
'GET', {
fields: 'id,picture{url},cover,feed',
access_token: {{access_token}}
},
function (response) {
if (response.error) {
console.error(response.error.message);
}
if (response.picture.data.url) {
profilePic = response.picture.data.url;
}
if (response.cover.source) {
coverPic = response.cover.source;
}
if (response.feed.data) {
feeds = response.feed.data;
feeds.forEach(function (feed) {
// view each feed content
});
}
if (response.feed.paging.next) {
nextFeedPage = response.feed.paging.next;
// a request to nextFeedPage will give the next set of feeds
}
}
);
};
Use the Graph API Explorer to design your query that should be entered in the 'fields' (eg: 'id,picture{url},cover,feed')
Now you can fetch your Facebook data from Facebook Graph API using your access_token.
Refer to https://developers.facebook.com/docs/graph-api/overview/
Note: Your access_token will expire in 2 months. Create a new access_token after that.

Facebook deauthorize my app

Can I use Facebook PHP SDK to deauthorize my app for a particular user, basically I like to have a toggle so the user can link or unlink their facebook account to my site, I have the link part working, now just need the unlink part.
Thanks
Now Graph API has a way to do this: https://developers.facebook.com/docs/reference/api/user/#permissions
Delete
You can de-authorize an application entirely, or just revoke a specific permission on behalf of a user by issuing an HTTP DELETE to USER_ID/permissions or USER_ID/permissions/PERMISSION_NAME
respectively. This request must be made with a valid user access_token or an app access token for the current app.
Using the graph API, this works fine:
$ret = $this->Facebook->api('/me/permissions', 'DELETE');
Not using the currently supported Graph API: as currently setup there is no interface in the Graph API (or even the legacy APIs) to deauthorize an application. The user has to explicitly choose to do it themselves through the Facebook settings pages.
However...
The legacy REST api has http://developers.facebook.com/docs/reference/rest/auth.revokeAuthorization/, which SOUNDS like it does what you want.
Let me know if that works for you: I'm curious.
Please note Facebook in the process of deprecating the REST API, and have adding equivalent support to the Graph API User object for "auth.revokeAuthorization" method.
For delinking or deauthorization the user by making app call:
$user_id = $this->facebook->getUser();
$access_token=$this->facebook->getAccessToken();
$result = $this->facebook->api(array(
'method' => 'auth.revokeAuthorization',
'uid' =>$user_id,
'access_token'=>$access_token
));
Using the JS API an app can be deauthorized like this:
FB.api('/me/permissions', 'DELETE', function(res){
if(res === true){
console.log('app deauthorized');
}else if(res.error){
console.error(res.error.type + ': ' + res.error.message);
}else{
console.log(res);
}
});
Or delete a specific permission:
FB.api('/me/permissions/user_birthday', 'DELETE', function(res){
if(res === true){
console.log('permission removed');
}else if(res.error){
console.error(res.error.type + ': ' + res.error.message);
}else{
console.log(res);
}
});
If you go to Facebook Developer, then select your application, then under the "Advanced" menu there is a field called "Deauthorize Callback". Set this as a URL on your domain which is pinged when a user deauthorizes themselves, there is some documentation on the format of the data it requests here.

Facebook Connect - Post Status

I have just about got the Facebook connect working on my site. I am able to log in and PHP has all the users details. I would now like to post a status when a user logs in with the Facebook connect.
I have searched everywhere on how to do this, tried lots of code. And I'm still unable to get anywhere with it. Please be very specific with me as I am new to the Facebook Connect.
It sounds to me like you're looking for the Javascript Facebook SDK. More info about publishing to the stream through javascript can be found at http://developers.facebook.com/docs/reference/javascript/FB.ui.
Have you tried this, from the documentation, on the Publishing section?
You can publish to the Facebook graph
by issuing HTTP POST requests to the
appropriate connection URLs, using an
access token on behalf of the user or
an application access token (for Open
Graph Pages). For example, you can
post a new wall post on Arjun's wall
by issuing a POST request to
https://graph.facebook.com/arjun/feed
EDIT
Snipped from this part of the documentation:
If you have an authenticated user with
the publish_stream permission, and
want to publish a new story to their
feed:
var body = 'Reading Connect JS documentation';
FB.api('/me/feed', 'post', { body: body }, function(response) {
if (!response || response.error) {
alert('Error occured');
} else {
alert('Post ID: ' + response);
}
});

Categories