How to GET Recent Status Updates on Facebook Page Using Facebook Graph Search API? - json

Similar to Getting Recent Page feeds? Facebook Graph API / FQL and Getting Facebook Status updates with JSon I would like to do a GET request using Facebook's Graph API, and insert that data into a page. Using the search API, I am able to retrieve information about the page like locale, description, and website, but there is no status update/post update included in the resulting JSON.
How can I retrieve the latest status updates/posts from a given page using Facebook's public Graph API?

It turns out it is possible to do this, but you need to generate an access token (for the page). To do this, you will need to have admin rights to the page in question. So for me, I had to request from that the page make me an admin (point them to the "Manage Admin Roles" dropdown on the page).
Next, you will need to generate an access token. Go here Facebook API Browser, and click on the "GET Access Token" button the right. Select the manage_pages role only.
The final URL should look something like this: https://graph.facebook.com/{page_id}/statuses?access_token=BAACEdE...
Here is the javascript function I used to test my URL (you could also just navigate there on your browser):
function populateFacebookUpdates() {
var pageID = "mycompanypage",
accessToken = "BAACEdE...";
var postsURL = "https://graph.facebook.com/" + pageID + "/statuses?access_token=" + accessToken;
$.ajax({
url: postsURL,
method: 'GET',
dataType: "jsonp",
success: function (data)
{
console.log("Successfully retrieved Facebook data");
console.dir(data);
},
error: function(status) {
console.log("Facebook data could not be retrieved. Failed with a status of " + status);
}
});
}
The data returned in JSON was what I wanted. Also, note that the retrieval would work on any browser/machine/IP (it does expire, however). I would just caution against putting the entire URL inside a client-side javascript file for obvious security reasons...

Status's is a connection and not a field as per the documentation. As far as I know only field information can be retrieved via the search API. If you want statuses you'll have to get the page Id from your search and then query for that pages statuses using the call below.
https://graph.facebook.com/{pageID}/statuses

Related

Chrome extension, how to track each visited page?

I wanted to build a Google Chrome extension that would display domain popularity, the way Alexa domain stats did;
I am able to display any data inside popup.html when user clicks my extension button (to show domain rank, backlinks, etc) but in background I need to track popular urls visited by users.
Using manifest v3, I was able (inside background.js) to detect and trigger code on each url change, but I cannot find a function that would allow the extension to ping my servers in order to tell what url/domain is visited by user.
I assume best way to do this is to make an URL get request in background. How can I do something like that ? Basically I want the extension to send a text message to an url of mine.
As wOxxOm mentioned you can use built in fetch API. As mentioned in this documentation, you can use fetch like this -
fetch(your_url, fetchParams) //fetch returns promise, that resolves to a response object
.then(response => response.json()) //assuming JSON response
.then(data => console.log(data))
.catch(err => console.error(err));
where fetchParam is typically a javascript object that follows the documentation mentioned above. you can add your custom data in the fetchParam's body key. like this
fetchParam = {
method: your_metod,
headers: your_header_object,
body: your_data
};
Hope I understood the question correctly.

"Invalid argument" when sending GET to spaces.members.list

I'm trying to create a Google Hangouts Chat chatbot (in G Suite) using Apps Script. I want to get a list of everyone in the chatroom, but this isn't directly supported in Apps Scripts yet, so I'm using the rest API. The API call list seems straightforward:
The command is
GET https://chat.googleapis.com/v1/{parent=spaces/*}/members
I've created a service account for authorization and then used
var endpoint = 'https://chat.googleapis.com/v1/{parent="spaces/pQkgxxxxxxx"}/members'
var options = {
method: "GET",
contentType : "application/json" ,
muteHttpExceptions : true,
headers: {
"Authorization": "Bearer " + goa.getToken(),
}
};
var response = UrlFetchApp.fetch(endpoint, options)`
To which I get
Invalid argument: https://chat.googleapis.com/v1/{parent="spaces/pQkgxxxxxxxx"}/members
I've tried encoding the parent parameter, but the error persists. Any ideas?
Per official documentation on the page you linked, the expected format of the path parameter parent is of the form spaces/*. The example value given is spaces/AAAAMpdlehY
In other words, you are not expected to write the {parents= and } bits, even though the template URL
GET https://chat.googleapis.com/v1/{parent=spaces/*}/members
has them. This template url format is explained in-depth on the Google API HTTP annotation website.
In your example, the correct URI to GET is https://chat.googleapis.com/v1/spaces/pQkgxxxxxxx/members
You should also consider that it may take multiple calls to resolve all members of the space pQkgxxxxxxx, by checking for a nextPageToken in the response (and passing that as the URL parameter pageToken in the next call).
You should also consider that the MemberShip returned by this query may include members with various states of membership.

Yii When using PageCaching in ajax call not working

I was trying to implement page caching in Yii2 advanced project and everything seemed to be super cool. And suddenly I was hit by a strange issue.
Case: On the homepage of the website there is some dynamic data like showing records from DB, info of current user like the name (if the user is logged-in) and some static content. Also, a search input field which fetches result using AJAX call.
To speed page loading I implemented PageCaching provided by Yii2. And all worked good. But one issue I got stuck at is that after user log-in the ajax call didn't work and gave Error:
Bad Request (#400): Unable to verify your data submission.
I get this error till cache is refreshed after the set duration or I disable cache.
Is this issue related to cookie/session or something else? How to resolve it?
The 400 Bad Request is because the csrf-token is not being sent, with the request which is required to prevent cross-site attacks by Yii whenever you use POST to submit a page or ajax request, if you create an ActiveForm then it creates an input automatically with the token value.
You didn't add the code that you are using for the ajax call so not clear if you are using it for only one field or the whole form, so I would suggest the concerning part only.
You need to send the csrf-token and you can get it via javascript using yii.js and calling these 2 methods
yii.getCsrfParam() to get the parameter name of the token
yii.getCsrfToken() to get the token or actual value of the csrf-token
The csrfParam name is configured inside your frontend/config.php or config/web.php depending on the app you are using (advance /basic) under the request component like below
'components'=>[
......
......
'request' => [
'csrfParam' => '_csrf-frontend',
],
......
......
]
So what you need to do is either change the request method from POST to GET and send data via query string or use the following way to send the POST request.
Note: You should change the URL and add the csrf data into your existing data that you are sending with the request
let data={};
data[yii.getCsrfParam()]=yii.getCsrfToken();
$.ajax(
{
method:"POST",
url:"/site/test",
data:data,
success:function(data) {
console.log(data);
},
error:function(jqXHR,textStatus,errorThrown) {
console.log(jqXHR,textStatus,errorThrown);
}
}
);
If you have a test action inside the SiteController with the following code, then the above ajax call should show you the $_POST array inside the console with the csrf param and token value as key=>value.
public function actionTest()
{
print_r($_POST);
}

weird file listing response differences between v2 and v3

I am using the google-drive-sdk with our company-made device. We upload pictures made by our device to google drive. After that I try to list the files with a GET request to https://www.googleapis.com/drive/v2/files to get thumbnailLink and webContentLink. Everything is working fine except that when I switch to v3 I don't get the response I should. The documentation says I should get a metadata response like https://developers.google.com/drive/v3/reference/files
but I only get: id, kind, name and mimeType. What am I doing wrong?
As stated in Migrate to Google Drive API v3 documentation, there are changes on how fields were returned.
Full resources are no longer returned by default. You need to use the fields query parameter to request specific fields to be returned. If left unspecified only a subset of commonly used fields are returned.
You can see examples on Github. This SO question might also help.
In v3 they made all the queries parametric. So you can query passing some parameter like
var request = gapi.client.drive.files.list({
'pageSize': 10,
'fields': 'files,kind,nextPageToken'
});
This block of code will return you all the information of every file just like v2.
If you are sending a get request then for fetching all the information you can try GET https://www.googleapis.com/drive/v3/files?fields=files%2Ckind%2CnextPageToken&key={YOUR_API_KEY}
Suppose you need ownsers and permissions only then set
var request = gapi.client.drive.files.list({
'pageSize': 10,
'fields':'files(owners,permissions),kind,nextPageToken'
});
For GET request use GET https://www.googleapis.com/drive/v3/files?fields=files(owners%2Cpermissions)%2Ckind%2CnextPageToken&key={YOUR_API_KEY}
for reference you can use Google Developers Documentation for fetching File list

How can I access auth-only Twitter API methods from a web application

I have a web application for iPhone, which will ultimately run within a PhoneGap application - but for now I'm running it in Safari.
The application needs to access tweets from Twitter friends, including private tweets. So I've implemented OAuth using the Scribe library. I successfully bounce users to Twitter, have them authenticate, then bounce back.
At this point the web app has oAuth credentials (key and token) which it persists locally. From here on I'd like it to user the Twitter statuses/user_timeline.json method to grab tweets for a particular user. I have the application using JSONP requests to do this with unprotected tweets successfully; when it accesses the timeline of a private Twitter feed, an HTTP basic authentication dialog appears in the app.
I believe that I need to provide the OAuth credentials to Twitter, so that my web application can identify and authenticate itself. Twitter recommends doing so through the addition of an HTTP Authorization header, but as I'm using JSONP for the request I don't think this is an option for me. Am I right in assuming this?
My options therefore appear to either be putting the oAuth credentials as query-string parameters (which Twitter recommends against, but documentation suggests still supports); or proxying all the Tweets through an intermediate server. I'd rather avoid the latter.
I access the Twitter API using URLs of the form
http://api.twitter.com/1/statuses/user_timeline.json?user_id=29191439&oauth_nonce=XXXXXXXXXXX&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1272323042&oauth_consumer_key=XXXXXXXXXX&oauth_signature=XXXXXXXXXX&oauth_version=1.0
When user_id is a public user, this works fine. When user_id is a private user, I get that HTTP Basic Auth dialog. Any idea what I'm doing wrong? I'm hoping it's something embarrassingly simple like "forgetting an important parameter"...
The oAuth stanza needs to be exact, as per http://dev.twitter.com/pages/auth#auth-request - I ended up building an Authorization: header that I could first check with curl.
I built it using the really helpful interactive request checker at http://hueniverse.com/2008/10/beginners-guide-to-oauth-part-iv-signing-requests/
Here's a friends API request for a protected user:
curl -v -H 'Authorization: OAuth realm="https://api.twitter.com/1/friends/ids.json", oauth_consumer_key="XXXXXXXXXXXXXXXX", oauth_token="XXXXXXXXXXXXXXXX", oauth_nonce="XXXXXXXXXXXXXXXX", oauth_timestamp="1300728665", oauth_signature_method="HMAC-SHA1", oauth_version="1.0", oauth_signature="XXXXXXXXXXXXXXXX%3D"' https://api.twitter.com/1/friends/ids.json?user_id=254723679
It's worth re-iterating that as you've tried to do, instead of setting the Authorization header via e.g. jquery's beforeSend function, that for cross-domain JSONP requests (which can't add HTTP headers) you can make oAuth requests by putting all the relevant key/value pairs in the GET request. This should hopefully help out various other questioners, e.g
Set Headers with jQuery.ajax and JSONP?
Modify HTTP Headers for a JSONP request
Using only JQuery to update Twitter (OAuth)
Your request looks like it has a couple of problems; it's missing the user's oauth_token plus the oauth_signature doesn't look like it has been base64 encoded (because it's missing a hex encoded = or ==, %3 or %3D%3D respectively).
Here's my GET equivalent using oAuth encoded querystring params, which you can use in a cross-domain JSONP call:
https://api.twitter.com/1/friends/ids.json?user_id=254723679&realm=https://api.twitter.com/1/friends/ids.json&oauth_consumer_key=XXXXXXXXXXXXXXXX&oauth_token=XXXXXXXXXXXXXXXX&oauth_nonce=XXXXXXXXXXXXXXXX&oauth_timestamp=1300728665&oauth_signature_method=HMAC-SHA1&oauth_version=1.0&oauth_signature=XXXXXXXXXXXXXXXX%3D
I was struggling with similar problem of making JSONP requests from Jquery, the above answer helped just to add what I did to achieve my solution.
I am doing server to server oauth and then I send oauth token, secret, consumer key and secret (this is temporary solution by the time we put a proxy to protect consumer secret). You can replace this to token acquiring code at client.
Oauth.js and Sha1.js download link!
Once signature is generated.
Now there are 2 problems:
JSONP header cannot be edited
Signed arguments which needs to be sent as part of oauth have problem with callback=? (a regular way of using JSONP).
As above answer says 1 cannot be done.
Also, callback=? won't work as the parameter list has to be signed and while sending the request to remote server Jquery replace callback=? to some name like callback=Jquery1232453234. So a named handler has to be used.
function my_twitter_resp_handler(data){
console.log(JSON.stringify(data));
}
and getJSON did not work with named function handler, so I used
var accessor = {
consumerSecret: XXXXXXXXXXXXXXXXXXXXXX,
tokenSecret : XXXXXXXXXXXXXXXXXXXXXX
};
var message = { action: "https://api.twitter.com/1/statuses/home_timeline.json",
method: "GET",
parameters: []
};
message.parameters.push(['realm', "https://api.twitter.com/1/statuses/home_timeline.json"]);
message.parameters.push(['oauth_version', '1.0']);
message.parameters.push(['oauth_signature_method', 'HMAC-SHA1']);
message.parameters.push(['oauth_consumer_key', XXXXXXXXXXXXXXXX]);
message.parameters.push(['oauth_token', XXXXXXXXXXXXXXX]);
message.parameters.push(['callback', 'my_twitter_resp_handler']);
OAuth.completeRequest(message, accessor);
var parameterMap = OAuth.getParameterMap(message.parameters);
Create url with base url and key value pairs from parameterMap
jQuery.ajax({
url: url,
dataType: "jsonp",
type: "GET",
});