Creating a post by sending HTTP request to Facebook API - javascript

I want to post on my facebook page by sending a HTTP POST. The way I am doing this is by creating a permanent access_token that is used to post to my facebook page. The problem is the access_token can be easily taken/inspected using firebug or any other tool (since it is hard-coded). How can I send it in a way that is kept from others.
$appID = 'MY_APP_ID';
$fb_page_id = 'MY_PAGE_ID';
$fb_page_access_token = 'PERMANENT_ACCESS_TOKEN';
$html = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'
. '<html><body>'
. '<div id="fb-root"></div>'
. "<script type=\"text/javascript\">
function post_to_fb(commentText, commentUsername, commentLink) {
var logoName = get_logoname_from_link(commentLink);
var strURL = 'https://graph.facebook.com/" . $fb_page_id . "/feed';
var params = 'link=' + commentLink + '&name=Brandchamp+-+' + logoName + '&message=[' + commentUsername +'+commented on ' + logoName + ':]+' + commentText + '&access_token=" . $fb_page_access_token . "';
var xmlHttpReq;
xmlHttpReq = new XMLHttpRequest();
xmlHttpReq.open('POST', strURL, true);
xmlHttpReq.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xmlHttpReq.send(params);
}
window.fbAsyncInit = function() {
FB.init({
appId: " . $appID . ",
status: true,
cookie: true,
xfbml: true,
});
FB.Event.subscribe('comment.create', function(response) {
var commentQuery = FB.Data.query('SELECT fromid, text FROM comment WHERE post_fbid=\'' + response.commentID + '\' AND object_id IN (SELECT comments_fbid FROM link_stat WHERE url=\'' + response.href + '\')');
var userQuery = FB.Data.query('SELECT name FROM user WHERE uid in (select fromid from {0})', commentQuery);
FB.Data.waitOn([commentQuery, userQuery], function () {
var commentRow = commentQuery.value[0];
var userRow = userQuery.value[0];
var commentText = commentRow.text;
var commentUsername = userRow.name;
post_to_fb(commentText, commentUsername, response.href);
});
});
};
(function() {
var e = document.createElement('script');
e.async = true;
e.src = document.location.protocol + '//connect.facebook.net/de_DE/all.js';
document.getElementById('fb-root').appendChild(e);
}());
</script>"
. '</body></html>';
print $html;

Simply don't let users see your access token: you have to create some kind of proxy which will post to your's page wall server-side

Whats the problem if a user who is granting you permission can see his/her own access_token in firebug. Firebug is on client side only. Also, official javascript sdk gives access_token to client. I dont think its bad.
User can always see his/her own password :) . What is bad in it ?
You should care about sniffing access_token over network. As #Juicy suggested use https to overcome that situation.
Edit after reading comment:
In your situation, I would suggest not to use javascript/ajax.
Also, I would recommend to use an sdk over your own php code.
An sdk uses all security measures which should be taken.
Official php sdk:
https://github.com/facebook/facebook-php-sdk

Related

Can not retrieve xampp jsxc message history

We are using jsxc javascript client to access openfire chat server. However we have problems loading the chat history.
The history is stored in the database, we just do not know, how to retrieve it.
var url = 'servername';
var domain = 'https://' + url + ':7443/http-bind/';
var sid = jsxc.storage.getItem('sid');
if (sid == null) sid = username;
jsxc.init({
xmpp: {
url: 'https://' + url + ':7443/http-bind/',
sid: sid
},
root: '/jsxc'
});
var jid = username + '#' + url;
jsxc.start(jid , password);
This is our initialization script. Do we have to add something else?
Best,
Bojan

Facebook SDK not public for visiters

I made an FB.api that get the last 2 posts of my facebook page. I added it to my personal website. It works on my website, but when someone else visit my website they can't see my last posts...When I googled the problem, I saw my FB app need to be live. So I did it. But it still doesn't work...
Here is my code:
window.fbAsyncInit = function () {
FB.init({
appId: 'APP_ID', // App ID
status: true, // check login status
cookie: true, // enable cookies to allow the server to access the session
xfbml: true // parse XFBML
});
};
function toonID() {
FB.api('/PAGE_ID/feed?limit=2', function (response) {
var str = "";
for (var i = 0; i < response.data.length; i++) {
//console.log(i + " : " + response.data[i].message);
//str += "<b>id: </b>" + response.data[i].id.slice(16) + "<br><br />";
str += "<div class='fb-post' data-href='https://www.facebook.com/Beatpounce/posts/" + response.data[i].id.slice(16) + "' data-width='466'></div><br /><br />";
}
document.getElementById("post").innerHTML = str;
});
}
I think I need an acces_token but I don't know how to use
You need to use at least an App Token for the call - but you should do that API call server side, because the App Token includes your App Secret and you should never reveal your App Secret on the client. User PHP cURL for that call and add your App Token as access_token parameter.
More information about Tokens:
https://developers.facebook.com/docs/facebook-login/access-tokens
http://www.devils-heaven.com/facebook-access-tokens/

CKEditor file upload not working in Yii2

I'm working on Yii2 Project where I've integrated http://ckeditor.com/demo
Now I want to implement functionality of file/image upload in it.
This is how I integrated CKEditor in Yii2 Project.
Step1: AppAsset.php
public $js = [
'ckeditor/ckeditor.js',
];
Calling ckeditor.js javascript file from config/AppAsset Class
Step2: View
<?= $form->field($model, 'standard_output_information')->textarea(['rows' => 2, 'class'=>'ckeditor']) ?>
Step3: config.js
CKEDITOR.editorConfig = function (config) {
var base_url = window.location.origin;
var pathArray = window.location.pathname.split('/');
var projectUrl = base_url + "/" + pathArray[1] + "/" + pathArray[2] + "/" + pathArray[3] + "/uploads";
config.filebrowserImageBrowseUrl = base_url + "/pcwf" + "/backend" + "/web" + "/businessprocessprofile" + "/upload";
config.filebrowserImageUploadUrl = base_url + "/pcwf" + "/backend" + "/web" + "/businessprocessprofile" + "/upload";
};
Here I've configured ImageBrowserUrl and ImageUploadUrl mentioned here http://docs.cksource.com/CKEditor_3.x/Developers_Guide/File_Browser_(Uploader)
Step4: Controller
public function actionUpload() {
echo \yii\helpers\Html::csrfMetaTags();
echo "<pre>";
print_r($_FILES);
print_r($_REQUEST);
exit;
}
Here I'm expecting uploaded image data. But whenever I click on Send it to Server button after selection of an image its giving me following error.
Not sure whether its issue of wrong url configuration in config.js or is it Yii2 form submission issue.
Any help would be appreciated.
I believe you have a problem with the CRSF tokens. Read more about the security here: http://www.yiiframework.com/doc-2.0/guide-security-best-practices.html. The easiest way to get around this is to disable CRSF for that particular action. You can take a look on how to do that here: https://stackoverflow.com/a/28526946/1880627
Rather than disabling CSRF validation it is far better and more secure to submit the token with the form to pass server-side validation. This can be quite easily done by injecting a hidden input field into the upload form with javascript:
$(document).off('click', '.cke_dialog_tabs a[id^="cke_Upload_"]').on('click', '.cke_dialog_tabs a[id^="cke_Upload_"]', function () {
var $forms = $('.cke_dialog_ui_input_file iframe').contents().find('form');
var csrfName = yii.getCsrfParam();
$forms.each(function () {
if (!$(this).find('input[name=' + csrfName + ']').length) {
var csrfTokenInput = $('<input/>').attr({
'type': 'hidden',
'name': csrfName
}).val(yii.getCsrfToken());
$(this).append(csrfTokenInput);
}
});
});
For a more detailed discussion on the issue refer to 2amigos/yii2-ckeditor-widget, issue #2. This is also where the code snippet is taken from, with a few minor tweaks to cover the case of multiple widgets on the page.

JavaScript/PHP: Get referral key URL

I'm working on an ajax (native JavaScript) form. I'm having trouble getting the referral key and sending it to the PHP back-end.
The idea is that the ajax request sends the entire URL (with the form data) as string to the PHP engine. I can then break down the URL in the PHP and extract the key.
Here is what I have so far:
Page url:
http://example.com?ref=gr84r34ijg98g
JS:
// Send the form data with the URL
function getquerystring() {
var email = document.getElementById('email').value;
var URL = document.URL;
qstr = 'email=' + email + '& URL=' + URL;
return qstr;
}
Then, in my PHP, I can retrieve the form data and url:
$email = $_POST['email'];
$url = $_POST['URL'];
How can I then break-down the URL, so as I only have the code at end as string? I was thinking I could break-down the URL in JavaScript before sending it, although I thought it might be easier to do that part with PHP.
Something like a preg_match() that removes "http://example.com?ref=" would probably do. Although not really sure how to do that.
Yes, you can get the value of ref in Javascript
function getquerystring() {
var email = document.getElementById('email').value;
var URL = document.URL;
var URL_arr = URL.split('ref='); //<-- URL_arr[1] will give ref string
qstr = 'email=' + email + '&URL=' + URL;
return qstr;
}
function getquerystring() {
var email = document.getElementById('email').value;
var URL = document.URL;
qstr = '?email=' + email + '& URL=' + URL;
return qstr;
}
try this.
$email = $_GET['email'];
$url = $_GET['URL'];
There is an extra space before URL .. and you should encode it with encodeURIComponent. Update this line
qstr = 'email=' + encodeURIComponent(email) + '&URL=' + encodeURIComponent(URL);
And on php side
$url = url_decode($_POST['URL']);
$email = url_decode($_POST['email']);
Try this:
var query = window.location.search.substring(1).split('&');
var ref = '';
$.each(query, function(i, v) {
v = v.split('=');
if (v[0] === 'ref') {
ref = v[1];
return false;
}
});
console.log(ref);
Why don't you just do the following in PHP (place it in either a header (if you want it to work on all pages) or at the top of index.php after all your includes :
<?php
$ref = (isset($_GET['ref']) && strlen($_GET['ref']) > 0) ? trim($_GET['ref']) : null;
//Process what ever you wanted to process from the beginning if you had a referral code
if(!is_null($ref)) {
// do your action
}
?>
Using the above you don't really need any kind of javascript.

Sending URL as a parameter using javascript

I have to send a name and a link from client side to the server. I thought of using AJAX called by Javascript to do this.
This is what I mean. I wished to make an ajax request to a file called abc.php with parameters :-
1. http://thumbs2.ebaystatic.com/m/m7dFgOtLUUUSpktHRspjhXw/140.jpg
2. Apple iPod touch, 3rd generation, 32GB
To begin with, I encoded the URL and tried to send it. But the server says status Forbidden
Any solution to this ?
UPDATE ::
It end up calling to
http://abc.com/addToWishlist.php?rand=506075547542422&image=http://thumbs1.ebaystatic.com/m/mO64jQrMqam2jde9aKiXC9A/140.jpg&prod=Flat%20USB%20Data%20Sync%20Charging%20Charger%20Cable%20Apple%20iPhone%204G%204S%20iPod%20Touch%20Nano
Javascript Code ::
function addToWishlist(num) {
var myurl = "addToWishlist.php";
var myurl1 = myurl;
myRand = parseInt(Math.random()*999999999999999);
var rand = "?rand="+myRand ;
var modurl = myurl1+ rand + "&image=" + encodeURI(storeArray[num][1]) + "&prod=" + encodeURI(storeArray[num][0]);
httpq2.open("GET", modurl, true);
httpq2.onreadystatechange = useHttpResponseq2;
httpq2.send(null);
}
function useHttpResponseq2() {
if (httpq2.readyState == 4) {
if(httpq2.status == 200) {
var mytext = httpq2.responseText;
document.getElementById('wish' + num).innerHTML = "Added to your wishlist.";
}
}
}
Server Code
<?php
include('/home/ankit/public_html/connect_db.php');
$image = $_GET['image'];
$prod = $_GET['prod'];
$id = $_GET['id'];
echo $prod;
echo $image;
?>
As I mentioned, its pretty basics
More Updates :
On trying to send a POST request via AJAX to the server, it says :-
Refused to set unsafe header "Content-length"
Refused to set unsafe header "Connection"
2 things.
Use encodeURIComponent() instead of encodeURI().
Here is a detailed discussion on this: When are you supposed to use escape instead of encodeURI / encodeURIComponent?
If you are new to JavaScript, use some lib to help you do the AJAX work. Like mootools, jQuery, etc.
Using a POST request solved my issue :)
function addToWishlist(num) {
var url = "trial.php";
var parameters = "prod=" + encodeURIComponent(storeArray[num][0]) + "&image=" + encodeURIComponent(storeArray[num][1]);
httpq2.open("POST", url, true);
httpq2.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
httpq2.onreadystatechange = function(){
if (httpq2.readyState == 4) {
if(httpq2.status == 200) {
var mytext = httpq2.responseText;
document.getElementById('wish' + num).innerHTML = "Added to your wishlist.";
}
}
};
httpq2.send(parameters);
}

Categories