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);
Related
I'm trying login to a remote site, by having curl to the login form.
I want to redirect to another subdomain and get content.
The code I have doesn't seem to work and only tries to show the main page of the site.
<?php
$username = 'user';
$password = 'pass';
$loginUrl = 'https://site_url';
//init curl
$ch = curl_init();
//Set the URL to work with
curl_setopt($ch, CURLOPT_URL, $loginUrl);
// ENABLE HTTP POST
curl_setopt($ch, CURLOPT_POST, 1);
//Set the post parameters
curl_setopt($ch, CURLOPT_POSTFIELDS, 'user='.$username.'&password='.$password);
//Handle cookies for the login
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
curl_setopt ($ch, CURLOPT_COOKIEFILE, 'cookie.txt');
//Setting CURLOPT_RETURNTRANSFER variable to 1 will force cURL
//not to print out the results of its query.
//Instead, it will return the results as a string return value
//from curl_exec() instead of the usual true/false.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//execute the request (the login)
$store = curl_exec($ch);
//the login is now done and you can continue to get the
//protected content.
//set the URL to the protected file
curl_setopt($ch, CURLOPT_URL, 'https://site_url/statistics');
//execute the request
$content = curl_exec($ch);
curl_close($ch);
//save the data to disk
file_put_contents('~/file.txt', $content);
?>
Does it have to be via cURL?
Have you considered leveraging a library like Guzzle?
They have good documentation that covers scenarios as you have described.
https://docs.guzzlephp.org/en/stable/quickstart.html#post-form-requests
Something like the below but could be laid out better
use GuzzleHttp\Client;
use GuzzleHttp\Exception\BadResponseException;
$client = new Client(['base_uri' => 'https://url_site/', 'cookies' => true]);
// Login
try {
$client->request(
'POST',
'login/',
[
'form_params' => [
'username' => $username,
'password' => $password,
],
]
);
} catch (BadResponseException $e) {
echo "Error Logging On for User {$username}";
exit;
}
// Navigate
$response = $client->request('GET', '/statistics');
$content = $response->getBody()->getContents();
file_put_contents('~/file.txt', $content);
I want to confirm transaction from other third-party, e.g I pay goods of $50 to juma Joe after click pay button and pay page is still loading and tell me to wait almost 5 seconds to check if the transaction is processing succeed, and if the transaction succeeds, it redirects to a success page.
So i need javascript and html confirmation code call from php to check if transaction is success then to show redirect seconds.
Thank you
Bellow is code for for validate transaction
$result = array();
$url = 'https://api.xxxx.co/transaction/verify/reference';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt(
$ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer xxxxxxx']
);
$request = curl_exec($ch);
if(curl_error($ch)){
echo 'error:' . curl_error($ch);
}
curl_close($ch);
if ($request) {
$result = json_decode($request, true);
}
if (array_key_exists('data', $result) && array_key_exists('status', $result['data']) && ($result['data']['status'] === 'success')) {
echo "Transaction was successful";
//Compete transaction
}else{
// Not complete
echo "Transaction not complete";
}
So. You can using ajax to request and response in you code.
Example:
PHP Code: validate.php
//....above you code here
// my code config response
$res = [
'mess' => null,
'status' => 404
];
//...you code validation result
if (array_key_exists('data', $result) && array_key_exists('status', $result['data']) && ($result['data']['status'] === 'success')) {
//Compete transaction
$res['mess'] = "Transaction was successful";
$res['status'] = 200;
}else{
// Not complete
$res['mess'] = "Transaction not complete";
$res['status'] = 404;
}
// my code response mess
echo json_encode($res);
So, below my front-end code, using jQuery Ajax to send POST request.
Document you can check here
$(document).ready(function() {
function validate(){
$.ajax({
url: 'validate.php',
type: 'POST',
dataType: 'json',
success: function(res) {
if (res.status === 200) {
console.log("you code here for success");
} else {
console.log("you code here for fail");
}
},
error: function(err) {
console.log("Request is error with: " + err);
}
});
}
});
HTML for submit button. Call to javascript
<button id="submit" type="submit" onclick="validate();">Send Request</button>
function checking(){
$.ajax({
dataType: "json",
url: status.php,
success: function(data){
if (data.done=='y') window.location = 'done.html';
}
});
}
setInterval(checking,5000);
With this script, you can call for every 5 seconds. But the best practice is to use a webhook. For more information, search it up on your payment gateway API documentation.
status.php
$result = array();
$respond=array();
$url = 'https://api.xxxx.co/transaction/verify/reference';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt(
$ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer xxxxxxx']
);
$request = curl_exec($ch);
if(curl_error($ch)){
echo 'error:' . curl_error($ch);
}
curl_close($ch);
if ($request) {
$result = json_decode($request, true);
}
if (array_key_exists('data', $result) && array_key_exists('status', $result['data']) && ($result['data']['status'] === 'success')) {
$respond[done]='y';
//Compete transaction
}else{
// Not complete
$respond[done]='n';
}
echo json_encode($respond);
i have a json encoded data in a variable named $json, it looks like-
string(1243) "{"screenShareCode":"882919360",
"appletHtml":"",
"presenterParams":"aUsEN5gjxX/3NMrlIEGpk0=",
"viewerUrl":"http://api.screenleap.com/v2/viewer/882919360?accountid=mynet",
"origin":"API"}"
}
i need to pass this json data into javascript function, please see below
script type="text/javascript" src="http://api.screenleap.com/js/screenleap.js">/script>
script type="text/javascript">
window.onload = function() {
var screenShareData = '?php echo $json;?>';
screenleap.startSharing('DEFAULT', screenShareData);
};
/script>
when i am trying to run this code it is giving me an error saying "missing mandatory screen share data".
How to solve this error?
i am following "https://www.screenleap.com/api/presenter"
It looks like $json is a string, you need to pass in a json object. Try the following:
window.onload = function() {
var screenShareData = '?php echo $json;?>';
screenleap.startSharing('DEFAULT', JSON.parse(screenShareData));
};
This is how you implement it based on the documentation
https://www.screenleap.com/api/presenter
<?php
// Config
$authtoken = '';
$accountid = '';
// 1. Make CURL Request
$url = 'https://api.screenleap.com/v2/screen-shares';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('authtoken:<authtoken>'));
curl_setopt($ch, CURLOPT_POSTFIELDS, 'accountid=<accountid>');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
curl_close($ch);
$json = json_decode($data, true);
?>
<!-- 2. Launch the Presenter App -->
<script type="text/javascript" src="http://api.screenleap.com/js/screenleap.js"></script>
<script type="text/javascript">
window.onload = function() {
screenleap.startSharing('DEFAULT', JSON.parse('<?php echo $json; ?>'));
};
</script>
If this doesn't work, you got to report it to screenleap.
You should only need to actually parse the JSON if you want to access the values. Otherwise, just pass the response data right into the startSharing function, like this:
<?php
$url = 'https://api.screenleap.com/v2/screen-shares';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('authtoken:<your authtoken>'));
curl_setopt($ch, CURLOPT_POSTFIELDS, 'accountid=<your accountid>');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$data = curl_exec($ch);
curl_close($ch);
$json = json_decode($data, true);
?>
<script type="text/javascript" src="http://api.screenleap.com/js/screenleap.js"></script>
<script type="text/javascript">
window.onload = function() {
screenleap.startSharing('DEFAULT', <?php echo $data; ?>);
};
</script>
If you just insert your own accountid and authtoken (without leading spaces), that should work for you.
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 ;-)
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