Read feed on a Facebook page without login in - javascript

Is it possible to create a web site and, with JavaScript, read the feed from a Facebook page and display it to my sites visitor without them having to login, or even have Facebook for that matter.
I'm getting lost in the Facebook documentations :(

Thanks to #mch here commes version that uses php as a proxy to read a Facebook feed with JavaScript.
Place a file called proxy.php on your server and add this code:
<?php
// always add this header to ensure the JSON is output in the correct format
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Cache-Control: no-cache");
header("Pragma: no-cache");
header('Content-Type: application/json; charset=utf-8');
$graphUrl = $_POST[graphUrl];
if ($graphUrl == "") {
$graphUrl = "https://graph.facebook.com/facebook/feed/";
}
//App Info, needed for Auth
$app_id = "1234567890";
$app_secret = "0000011122234334445556aaass";
//retrieve auth token
$authToken = fetchUrl("https://graph.facebook.com/oauth/access_token?type=client_cred&client_id={$app_id}&client_secret={$app_secret}");
//Echo back json to read client side.
echo fetchUrl("{$graphUrl}?{$authToken}");
function fetchUrl($url){
$ch = curl_init();
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
$retData = curl_exec($ch);
curl_close($ch);
return $retData;
}
?>
Change app_id, app_secret to your apps ids. Create apps here https://developers.facebook.com/apps/
Create a HTML file next to your proxyfile. Add this code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>FB reader</title>
</head>
<body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var timeout = 5000,
load_error;
load_error = function (jqXHR, textStatus, errorThrown) {
if (errorThrown === "timeout") {
alert('Server bussy');
} else {
alert('error: 404', textStatus + ": " + errorThrown);
}
};
$(document).ready(function() {
console.log('Loading from Facebook...\n');
//Change data: {graphUrl: 'https://graph.facebook.com/iambounty/feed'}, to what ever you want.
$.ajax({
type: 'POST',
url: 'proxy.php',
data: {graphUrl: 'https://graph.facebook.com/iambounty/feed'},
timeout: timeout,
error: load_error,
success: function (rv) {
var data = rv.data,
len = data.length,
i,
out = '';
for (i = 0; i < len; i += 1) {
if (data[i].description) {
out += data[i].description + '\n\n';
}
}
console.log(out);
}
});
});
});
</script>
</body>
</html>

You can do it on the server side with PHP. Create a facebook App in the Facebook developer center to get a App Key and Secret Key.
$profile_id = "1234567890";
//App Info, needed for Auth
$app_id = "0001234567890";
$app_secret = "abc123ebf123f3g5g6j";
/* USE THIS LINE INSTEAD OF THE "veryfypeer" LINE BELOW */
Facebook::$CURL_OPTS[CURLOPT_CAINFO] = '/path/to/crt/fb_ca_chain_bundle.crt';
//retrieve auth token
$authToken = fetchUrl("https://graph.facebook.com/oauth/access_token?type=client_cred&client_id={$app_id}&client_secret={$app_secret}");
$data['feed_data'] = fetchUrl("https://graph.facebook.com/{$profile_id}/feed?{$authToken}");
function fetchUrl($url){
$ch = curl_init();
/* DO NOT USE THE FOLLOWING LINE: I'VE COMMENTED IT OUT HERE */
// curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
$retData = curl_exec($ch);
curl_close($ch);
return $retData;
}
... on the Javascript side I think it's not possible, since the FB API Secret must be hidden from the public. Information taken from here

Related

Can not get data from AJAX request to the Coinhive API

I recently tried to get the data from a Json API and post that back to a table in html.
I tried to do this from: https://api.coinhive.com/user/balance?name=username&secret=mysecret
It does show me: {"success":true,"name":"*user*","total":49152,"withdrawn":0,"balance":* a value *}
But I want to let my users push a button which will load the balance value to a table in their own user portal.
I got the user portal setup with all the mysqlvalues, But i can't manage to get the jsonpart to work.
Can anyone please help me?
Thanks in common,
Dennis.
edit:
I tried the following:
<html lang="en">
<head>
<title>JavaScript - read JSON from URL</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
</head>
<body>
<div class="mypanel"></div>
<script>
$.getJSON('https://api.coinhive.com/user/balance?name=username&secret=mysecret', function(data) {
var text = `Balance: ${data.balance}<br>`
$(".mypanel").html(text);
});
</script>
</body>
</html>
And I also tried:
function setup() {
loadJSON("https://api.coinhive.com/user/balance?name=username&secret=mysecret", gotData);
}
function gotData(data) {
alert(data);
}
And that isn't working.
What am I doing wrong?
figured it out!
The JSON request:
<?php
$url = 'the api url';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Content-Type: application/x-www-form-urlencoded"
));
$data = curl_exec($ch);
curl_close($ch);
$result = json_decode($data, true);
?>
The postback to the end user:
<span id="test" style="color:white"><?php
if (isset($data))
{
echo $result['balance'];
}
else
{
echo 'damn';
}
?></span>
I decided to go with php and kind of ditch the html getjson part.
Client side requests to the Coinhive HTTP API are restricted by CORS rules:
From API documentation:
You should never call the Coinhive HTTP API from the client side.

Unable to access Microsoft Graph API after getting OAuth access_token

I'm using adal.js to generate an access token via Microsoft OAuth, however whenever I try to use the access token to call the https://graph.microsoft.com/v1.0/me endpoint (or graph.windows.net), I receive the following error: Authentication_MissingOrMalformed: Access Token missing or malformed.
Any ideas on how I can remedy this? Here's my config in JS:
<script src="https://secure.aadcdn.microsoftonline-p.com/lib/1.0.12/js/adal.min.js"></script>
<script>
var authContext = new AuthenticationContext({
instance: 'https://login.microsoft.com/',
tenant: 'xxxxxx-xxxxxxx-xxxxxx-xxxxxx', //COMMON OR YOUR TENANT ID
clientId: 'xxxxxx-xxxxxxx-xxxxxx-xxxxxx', //REPLACE WITH YOUR CLIENT ID
redirectUri: '/login.php', //REPLACE WITH YOUR REDIRECT URL
callback: getUser,
popUp: true,
cacheLocation: 'localStorage'
});
...
authContext.login();
// SET COOKIE
var newToken = authContext.getCachedToken('tenantid-xxxxxxx-xxxxxx-xxxxxx');
var now = new Date();
now.setTime(now.getTime() + 1 * 3600 * 1000);
document.cookie = "token="+newToken+"; expires=" + now.toUTCString() + "; path=/";
</script>
And here's how I'm attempting to pull/use the token in my PHP script:
<?php
// Get the token
$token = $_COOKIE['token'];
// Set headers
$headers = array(
"Authorization: Bearer " . $token,
'Content-Type: application/json'
);
// Make request to Graph API
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://graph.windows.net/mywebsite.org/me?api-version=1.6");
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$response = json_decode($response);
curl_close($ch);
echo "<pre>";
var_dump($response);
echo "</pre>";
?>
All it does is return this error: Authentication_MissingOrMalformed: Access Token missing or malformed.
How can I fix this?? Is it a problem with not specifying the correct resource?
To call the Azure AD Graph REST successfully, we need to acquire the token for the Azure AD Graph.
To check whether the token is correct for the Azure AD Graph, you can print the token and parse it from here.
The aud claim in the token should be https://graph.windows.net. If it does't match, you need to acquire the token using the acquireToken instead of getting the token from cache. And the resource parameter should be https://graph.windows.net.

Not able to obtain Facebook access token

I have two pages, facebook.php and generatePageToken.php I'm trying to post as page to my facebook page but this script currently only posts as admin. In the facebook.php page I try and get an access token but it doesn't work - it alerts back blank. Please do not tell me to read some API, I have read it all and I truly do not understand what's wrong with this. I'd ideally like a permanent token if someone could swing it
facebook.php
<!doctype html>
<html>
<head>
<script type="text/javascript">
function SendToFacebook()
{
window.fbAsyncInit = function () {
// init the FB JS SDK
FB.init({
appId: '432036336937975', // App ID from the app dashboard
status: false, // Check Facebook Login status
xfbml: true // Look for social plugins on the page
});
FB.login(function (response) {
FB.api('/me/accounts', function (apiresponse) {
if (response.authResponse) {
//simple user access token
var accessToken = response.authResponse.accessToken,
ajaxRequest = new XMLHttpRequest(),
pageId = '1521533601413118';
ajaxRequest.onreadystatechange = function() {
if(ajaxRequest.readyState === 4) {
//print out the extended page access token
alert(ajaxRequest.responseText);
}
};
ajaxRequest.open('POST','generatePageToken.php?pageId=' + pageId, true);
ajaxRequest.setRequestHeader('Content-type','application/x-www-form-urlencoded');
ajaxRequest.send('accessToken=' + accessToken);
}
var data = {
message: "mymessage test",
display: 'iframe',
caption: "caption",
name: "name",
description: "description",
to: '1521533601413118',
from: '1521533601413118'
};
FB.api('/1521533601413118/feed', 'post', data, function () {
console.log(arguments);
});
});
}, { scope: 'manage_pages'});
};
// Load the SDK asynchronously
(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/all.js";
fjs.parentNode.insertBefore(js, fjs);
} (document, 'script', 'facebook-jssdk'));
}
</script>
</head>
<body>
Submit
</body>
</html>
generatePageToken.php
<?php
$accessToken = $_GET['accessToken'];
$pageId = $_POST['pageId'];
$fbAppId = '432036336937975';
$fbAppSecret = 'REMOVED FOR NOW';
$appsecretProof = hash_hmac('sha256', $accessToken, $fbAppSecret);
//init curl
$ch = curl_init();
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_USERAGENT, 'facebook-php-3.2');
//get extended user access token
$url = 'https://graph.facebook.com/oauth/access_token?grant_type=fb_exchange_token' .
'&client_id=' . $fbAppId .
'&client_secret=' . $fbAppSecret .
'&fb_exchange_token=' . $accessToken .
'&appsecret_proof=' . $appsecretProof;
curl_setopt($ch, CURLOPT_URL, $url);
$curlResult = curl_exec($ch);
$response_params = array();
parse_str($curlResult, $response_params);
$extendedUserToken = $response_params['access_token'];
$appsecretProof = hash_hmac('sha256', $extendedUserToken, $fbAppSecret);
//get extended page access token
$url = 'https://graph.facebook.com/' . $pageId .
'?fields=access_token' .
'&access_token=' . $extendedUserToken .
'&appsecret_proof=' . $appsecretProof;
curl_setopt($ch, CURLOPT_URL, $url);
$curlResult = curl_exec($ch);
curl_close($ch);
$pageToken = json_decode($curlResult)->access_token;
echo $pageToken;
?>
I think it's because you mixed up $_POST and $_GET:
Your code:
ajaxRequest.open('POST','generatePageToken.php?pageId=' + pageId, true);
^ pageId is GET
ajaxRequest.setRequestHeader('Content-type','application/x-www-form-urlencoded');
ajaxRequest.send('accessToken=' + accessToken);
^ accessToken is POST
You're sending pageId as a GET variable while accessToken is a POST variable.
However, your PHP retrieves the variables as:
$accessToken = $_GET['accessToken'];
$pageId = $_POST['pageId'];
It should be the other way around, such as:
$accessToken = $_POST['accessToken'];
$pageId = $_GET['pageId'];
If you want to post on your page as the page's user, you need to change the scope of your permissions first:
You need }, { scope: 'manage_pages, publish_stream'});, (added publish_stream).
Now, it's very easy to post, simply send a POST request:
$data = http_build_query(array(
'access_token' => **your access token**,
'message' => 'hello world!'
));
$ch=curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://graph.facebook.com/v2.1/1521533601413118/feed');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($ch);
curl_close($ch);

Cannot translate with Google translate

I'm trying to translate text with Google translate:
$.ajax({
type : "GET",
url : "https://www.googleapis.com/language/translate/v2",
dataType : 'jsonp',
cache : false,
contentType : "application/x-www-form-urlencoded; charset=UTF-8",
data : "key="+translateKey+"&source=en&target=de&q=Hello",
success : function(res) {
console.log('res', res.data.translations[0].translatedText);
},
error : function(xhr, ajaxOptions, thrownError) {
}
});
$.get("https://www.googleapis.com/language/translate/v2", {
key : translateKey,
source : "en",
target : "fr",
q : "hello"
}, function(res) {
console.log(res.data.translations[0].translatedText);
}, "json").fail(function(jqXHR, textStatus, errorThrown) {
alert("error :" + errorThrown);
});
I'm using API's:
Google+ API
Google+ Domains API
Translate API
I create a Google project and inserted my local host and my real site address.
I got back an error 403 forbidden.
I tried to copy it into the URL like that:
https://www.googleapis.com/language/translate/v2?key=AIzaSyCClt5fo3FDMAym59FQw-R5D39eaTNfWIg&source=en&target=de&q=Hello
And I got the error JSON.
Where am I wrong?
I'm writing with AJAX and Javascript.
HERE THE ANSWER !!!
you must to pay.. BUT their is a hack in php if someone want to use:
<?php
function curl($url,$params = array(),$is_coockie_set = false){
if(!$is_coockie_set){
/* STEP 1. let’s create a cookie file */
$ckfile = tempnam ("/tmp", "CURLCOOKIE");
/* STEP 2. visit the homepage to set the cookie properly */
$ch = curl_init ($url);
curl_setopt ($ch, CURLOPT_COOKIEJAR, $ckfile);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec ($ch);
}
$str = ''; $str_arr= array();
foreach($params as $key => $value){
$str_arr[] = urlencode($key)."=".urlencode($value);
}
if(!empty($str_arr))
$str = '?'.implode('&',$str_arr);
/* STEP 3. visit cookiepage.php */
$Url = $url.$str;
$ch = curl_init ($Url);
curl_setopt ($ch, CURLOPT_COOKIEFILE, $ckfile);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec ($ch);
return $output;
}
function Translate($phrase, $from , $to){
$ret = "";
if(strlen($phrase)>1600){ //split and translate each part individually to get around 2048 size limit:
$phrases = str_split($phrase,1600);
foreach($phrases as $p) $ret .= translate($p, $from, $to);
return($ret);
}else{
$url = "http://translate.google.com/translate_a/t?client=p&q=".urlencode($phrase)."&hl={$to}&sl={$from}&tl={$to}&ie=UTF-8&oe=UTF-8&multires=0" ; // client = p !
$out = json_decode(curl($url), 1);
foreach($out['sentences'] as $sentence){
$ret .= $sentence['trans'].' ';
}
return stripslashes(trim($ret));
}}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body dir="rtl">
<?php
$text = "my name is name" ;
echo Translate($text,'en','iw');
?>
</body>
</html>
Its better to go for an experienced and a professional website translator. I don't believe on translation tools for any kind of translation, human translators are the best option for these kind of jobs.
goto Google API Console, click on "Enable an API" and then search for "Translate API" and switch it on(http://pastemehere.com/ai2xhwxm).

How to display instagram API response in javascript alert?

I am trying to send a delete request to instagram api using ajax but my current javascript code display the response in alert box as:
<pre></pre><pre></pre>
so i cant find the problem why delete request is not successful! if i call the same php script(doit.php) from the browser and pass it media id then the delete will be successful!
could any one tell me what is wrong with my current delete ajax request that fails to make delete request to instagram api?
Instagram API Docs for Deleting Like
sample api response:
{
"meta": {
"code": 200
},
"data": null
}
javascript:
<script>
function deleteLike(a,b)
{
alert("MediaID:"+a+"\nId:"+b);
var url = "./doit.php";
$.post(url, {
"method": "post",
//"method": "delete",
"MediaID": a,
}, function(data)
{
var ajaxResponse = data;
alert("Response:"+ajaxResponse);
if (data.meta.code == 200) {
alert("sucessDelete");
}
})
}
</script>
PHP CODE:
$MediaIDvar= $_POST["MediaID"];
//$MediaIDvar= $_GET["MediaID"];
$url2 = "https://api.instagram.com/v1/media/".$MediaIDvar."/likes?xxxxx";
$api_response2 = get_data2(''.$url2);
$record2 = json_decode($api_response2); // JSON decode
echo '<pre>' . print_r($api_response2, true) . '</pre>';
echo '<pre>' . print_r($record2, true) . '</pre>';
// to see what is in the $api_response and $record object
/* gets the data from a URL */
function get_data2($url2) {
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$MediaIDvar= $_POST["MediaID"];
$MediaIDvar= $_GET["MediaID"]; // => this will overwrite the previous $MediaIDvar
it will work if you call the php script with a GET variable, not through ajax using POST ;-)

Categories

Resources