facebook access_token request return NOTHING - php

it's been 5 days that I'm stuck in the implementation of a simple fb login and I'm banging my head like a motherf***r. anyways.
I'm at the point that I'm trying to set the accessToken by hand.
like shown in this post.
https://github.com/facebook/php-sdk/issues/418#issuecomment-2605012
the only problem is that the oauth/access_token call returns nothing
and I'm guessing that it's a pretty messed up behaviour.
this is the snippet I use to make the call
$token_url = "https://graph.facebook.com/oauth/access_token?client_id=".FB_APPID."&redirect_uri=".urlencode($curUrl)."&client_secret=".FB_APPSECRET."&code=".$_GET['code'];
log_to_file("curPageURL: ".$token_url);
$response = file_get_contents($token_url);
log_to_file("resp: ".$respone);
the log_to_file is a custm method that logs the taken message in a file so that I can have the log situation in a tail -f scenario.
what happens here is that the log "resp: ". returns nothing at all.
did anyone face the same problem?
thx in advance. this thing is driving me insane.
and I can officially state that the fb sdk is the most buggy and worse-documented service
I've ever used.

Facebook has the most badly-documented API in the world. I remember the time I used it and couldn't help swearing all the time ! :) Here is a piece of pseudo-code that did work for me. It gains permission from a user to post a link on his wall. I'm just posting it so that maybe you can take some hints and make your code work:
<?php
//A function for cURL operations.
function callFb($url)
{
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true
));
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
$url = "https://graph.facebook.com/oauth/access_token?client_id=<your_client_id>&redirect_uri=".urlencode("<the_url_where_the_user_is_redirected_after_granting_permission>")."&client_secret=<your_client_secret>";
/* Get access token. */
$access_token = callFb($url);
/* Parse the result to get access token */
$access_token = substr($access_token, strpos($access_token, "=")+1, strlen($access_token));
/* Save access token, if you want to for future.*/
mysql_query("INSERT INTO fb_auth_tokens (id,auth_token) VALUES('$_GET[id]','$auth_token')");
/* Post to users wall */
$apprequest_url = "https://graph.facebook.com/me/feed";
$mymessage="Hello World !";
$parameters = "?access_token=" . $access_token . "&message=" .
urlencode($mymessage) .
"&link=".urlencode("<link_that_you_want_to_post>").
"&description=<description_of_the_link>".
"&method=post";
$myurl = $apprequest_url . $parameters;
$result = callFb($myurl);
// Thy shall be done. :)

Related

Struggling to Get Token for REST API in PHP OAuth 2 Client. Have Successfully Tested with Postman

I need to add some functionality to my site to connect via REST to a provider and exchange data. I've used Postman for several years to test these APIs for myself and customers, but this is the first time I have tried to add the functionality to my site.
I've Googled numerous sites. I tried a few different things. First I tried the league/oauth2-client library. The requests went through without any errors, but all I received back was a response like this.
JSON response = {"status":"400","timeStamp":"2022-01-22T16:21:19+0000","error":{"errorId":"ea7bc74d-21ca-4503-92ad-3a76b05d7554","message":null,"code":"invalid_request","description":"Cannot generate token. Bad request","details":null}}
So I went to look at other examples. I found this nice and simple code from
UC San Diego Example for Client Credentials. I tried it and got the same type of results. "Cannot generate token. Bad request." For now, I like the simple option of the UCSD example if I can make it work.
As I said, I can successfully make this request and use the API all day long in Postman. So I know the Client ID, Client Secret, and URL are correct.
Unfortunately, I don't know how to troubleshoot this in PHP. I looked in the server log and I didn't find any errors. I tried to echo something out to see if I could see what was wrong, but I couldn't get the request to echo to the page. I tried using Fiddler to see if I could find the request with no luck.
Here's where I am right now. Any suggestions for what I am missing?
Thanks in advance for your help!
<?php
$token_url = "https://xxxx.xxxxx.com/services/api/oauth2/token";
$test_api_url = "https://xxxx.xxxxx.com/services/api/x/users/v2/employees/12345";
// client (application) credentials on xxxx.xxxxxx.com
$client_id = "xxxxxxxxxxx";
$client_secret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$access_token = getAccessToken();
$resource = getResource($access_token);
echo "</br>access_token = " . $access_token;
echo "</br>resource = " . $resource;
// step A, B - single call with client credentials as the basic auth header
// will return access_token
function getAccessToken() {
global $token_url, $client_id, $client_secret;
$content = "grant_type=client_credentials";
$authorization = base64_encode("$client_id:$client_secret");
$header = array("Authorization: Basic {$authorization}","Content-Type: application/x-www-form-urlencoded");
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $token_url,
CURLOPT_HTTPHEADER => $header,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $content
));
$response = curl_exec($curl);
curl_close($curl);
echo "</br>JSON response = " . $response;
return json_decode($response)->access_token;
}
// step B - with the returned access_token we can make as many calls as we want
function getResource($access_token) {
global $test_api_url;
$header = array("Authorization: Bearer {$access_token}");
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $test_api_url,
CURLOPT_HTTPHEADER => $header,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_RETURNTRANSFER => true
));
$response = curl_exec($curl);
curl_close($curl);
return json_decode($response, true);
}
?>
So it seems that with a little bit of research and learning on my part the answer to my question was in Postman. Postman includes a feature that will translate your request into any number of code languages.
All I had to do was select the PHP option and copy and paste the results into my project. Boom, there you go. That was easy.
Here's a YouTube video showing how it works.
Postman: Import/Export and Generating Code Samples

Vimeo Thumbnails for private video in PHP

I have tried every single answer on this forum and couldn't get a proper working code. So I am posting this again.
I want to get the thumbnail of private and hidden Videos from Vimeo. I also have an access token generated which I tried to use with the solutions provided for the old questions which also didn't work.
I tried this code
https://vimeo.com/api/oembed.json?url=https://vimeo.com/531126552/access_token
Also tried using cURL
curl_setopt($curl_h, CURLOPT_HTTPHEADER,
array(
'Authorization: bearer {access_token}',
'Accept: application/vnd.vimeo.*+json;version=3.4',
)
);
curl_setopt($curl_h, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl_h);
The response for above cURL code is this:
{"error":"Something strange occurred. Please contact the app owners.","link":null,"developer_message":"No user credentials were provided.","error_code":8003}
Please suggest me a way to do this or help me find where the error is.
The thumbnails can be accessed by the thumbnail_url in JSON data provided by Oembed API
sample :
https://vimeo.com/api/oembed.json?url=https://vimeo.com/{video_id}/
Here is what works for public videos. I know you asked about private, so I am going to ask, if you ever figured it out...ping me. Trying to figure out the same.
For others, here is the public solution. It is the private videos that it fails on.
function mmd_get_vimeo_info( $video_id )
{
// https://vimeo.com/api/oembed.json?url=https://vimeo.com/
$VimeoConnectLink = "https://vimeo.com/api/oembed.json?url=https://vimeo.com/" . $video_id ;
$request = wp_remote_get( esc_url_raw($VimeoConnectLink));
if ('error' == $request || is_wp_error($request))
return "";
$response = wp_remote_retrieve_body( $request );
if ('error' == $response || is_wp_error($response))
return "";
$video_array = json_decode( $response, true );
// Looking for [title], [thumbnail_url] [duration]
return $video_array;
}
But it can fail with domain privacy in place.

Vimeo API help (cURL or Library)?

Background:
Vimeo PRO account (owner of videos)
Both public and private videos
Only embeddable on my domains
Goal:
I simple want to pass in a VIDEO ID, and get a JSON data dump response back.. (so I can use this in an embeddable iframe/player.. BUT ALSO be able to display the description from the video, as well as the video download links... this all seems to be available in the JSON returned data)
I have tried a simple cURL approach..
//project vars
$client_id = 'xxx';
$client_secret = 'xxx';
$access_token = 'xxx';
$video_endpoint = 'https://api.vimeo.com/videos/';
$video_url = '171811266';
//$video_url = '171811266/5822169b48';
$json_url = $video_endpoint . '.json?url=' . rawurlencode($video_url);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $json_url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"authorization: Bearer ".$access_token
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
}else {
echo $response;
}
And while I -thought- I was on the right track (even though its an OLD approach)..
I get this error:
{"error":"The requested video could not be found"}
Not sure what I could be doing wrong? Video link:
https://vimeo.com/171811266
I believe I set this video to be PUBLIC for testing..etc
Since I couldnt get that approach to work.. I moved on to attempt to use an 'official library':
https://github.com/vimeo/vimeo.php
However.. IMHO, it does not have any 'working examples' out of the box..
Here is what I tried so far:
*I am not clear why I need to 'authenticate' for videos "I" own.. on a Vimeo account "I" own.. and can only be displayed on domains "I" own?
I not clear why I need to send a user to the Vimeo site to 'accept/approve' ANYTHING? and then redirect them back... to where? The page where the video is housed?
//project vars
$client_id = 'xxxx';
$client_secret = 'xxx';
$access_token = 'xxx';
$redirect_uri = 'http://www.domain.com/file.php'; //what URL should this be? The .php page that has the embedded player on it?
// scope is an array of permissions your token needs to access. You can read more at https://developer.vimeo.com/api/authentication#scopes
$scopes = Array('public', 'private');
$state = 'Ldhg0478y'; //randomly made up state variable/value
require("Vimeo/autoload.php");
// instantiate a new instance of Vimeo class/object
$lib = new \Vimeo\Vimeo($client_id, $client_secret);
// build a link to Vimeo so your users can authorize your app. //whatever that means and is for?
$url = $lib->buildAuthorizationEndpoint($redirect_uri, $scopes, $state);
// redirect_uri must be provided, and must match your configured uri
$token = $lib->accessToken(code, redirect_uri);
// usable access token
var_dump($token['body']['access_token']);
// accepted scopes
var_dump($token['body']['scope']);
// use the token
$lib->setToken($token['body']['access_token']);
$response = $lib->request('/me/videos', array('per_page' => 2), 'GET');
var_dump($response['body']);
My response from the above is:
Notice: Use of undefined constant code - assumed 'code' in /usr/www/users/domain_name.org/file_name.php on line 27
Notice: Use of undefined constant redirect_uri - assumed 'redirect_uri' in /usr/www/users/domain_name.org/file_name.php on line 27
Notice: Undefined index: access_token in /usr/www/users/domain_name.org/file_name.php on line 30
NULL
Notice: Undefined index: scope in /usr/www/users/domain_name.org/file_name.php on line 33
NULL
Notice: Undefined index: access_token in /usr/www/users/domain_name.org/file_name.php on line 36
array(1) { ["error"]=> string(52) "You must provide a valid authenticated access token." }
I think I'd feel more comfortable and have more control (I think?) if I could get the cURL version working? Instead of trying to use this Vimeo library? (Theres just too many files and random lines to make sense for me at this point to understand what I need)
I dont need to upload anything.. I just need to/want to pass a video ID and get back a list of JSON data for that video.. (dont need USER info... dont need to UPLOAD.. dont need to DELETE)
Can anyone guide me or give me some direction on what I am doing wrong? and how to correct it?
Thanks
=========================================================================
Update: "What worked for me!"
Using the official library.. the readme 'example' just didnt work for me (as I posted)..
However.. this did work for me: (again, using the official library)
<?
//include offifial library
require("Vimeo/autoload.php");
$client_id = 'xxx';
$client_secret = 'xxx';
$access_token = 'xxx';
$video_id = 'xxx';
$lib = new Vimeo\Vimeo($client_id, $client_secret, $access_token);
$video_response = $lib->request('/videos/'.$video_id);
//dont really need this, but included in case there is some data you need to display
$token_response = $lib->clientCredentials();
//example of parsing out specific data from the array returned
//name/title
echo $video_response['body']['name'] . '<br><br>';
?>
Where are you getting the .json?url= part? Your request url should be just
$json_url = $video_endpoint . rawurlencode($video_url);
Your code works with that change.
Reference: https://developer.vimeo.com/api/endpoints/videos#/{video_id}

How to get access code along from Facebook which manually building a Login Flow

I am trying to manually build a login flow, so that the our users are able to login to our website with their Facebook accout.
Anyhow, I am getting stuck at the step of "Confirming identity" where I have passed the code I have received with the use of $_GET["code"] to get the access_token with the url
https://graph.facebook.com/oauth/access_token?client_id={app-id}&redirect_uri={redirect-uri}&client_secret={app-secret}&code={code-parameter}
On visiting this url, I am able to see the access_code and the expire. Anyhow, what I want to do is to have the program visit the page and then copy the entire contents (or just the access_code part) into a variable in the php code.
I have tried this:
$access_token = readfile("https://graph.facebook.com/oauth/access_token?client_id=834481703238074&redirect_uri=http://example.co/app.php&client_secret={secret_code}&code=$code");
But it's not working. What should I do? What is the right way to solve this problem?
Of what I understood from the question, you are simply looking to get the access token from the access token url. (correct me if I'm wrong)
To do this-
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$access_token = $params['access_token'];
I have created this PHP function, you can use it:
function getAccessToken($app_id, $secret, $base_url, $code) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://graph.facebook.com/v2.0/oauth/access_token?'. 'client_id=' . $app_id . '&redirect_uri=' . urlencode($base_url) . '&client_secret=' . $secret . '&code=' . $code);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$r = curl_exec($ch);
$r = strstr(str_replace('access_token=', '', $r), '&expires=', true);
return $r;
}
it return the access_token string, just pass app_id, app_secret, redirect_uri & code from $_GET['code']
You might be wondering why am I using strstr() along with str_replace() that's because the header of /oauth/access_token is text/plain instead of JSON, keep in mind, this access_token lasts for 2 hours at maximum, you can extend it to last for 60 days

Using FB PHP API to post status update to news feed

I run a music search engine, I already use basic Facebook intergration, like the like button, but my next aim is to create deeper intergration,
I'm aiming that when a user searches for something($q which I set as a cookie $_COOKIE['q'] ), a status update will appear, saying what they searched for and a link to my site.
I can allow a user login to facebook through JavaScript but I presume I would need to do it the PHP way.
I need to use PHP, as, after the user gives permission, I would like it that the user isn't pestered again. I have the Facebook PHP SDK and have created an app on Facebook. Online tutorials haven't really helped and i'm still on square 1, even though my PHP is okayish.
I would really appreciate if anyone gave me some guidelines/ ideas or helped code it.
Thanks in advance!
Niall
Well What you need to do is relatively easy. I think you already have the right java script for this but I'll add that in aswell, just incase!
Okay! First we need to add the php script at the top of your page that gets the information if the user has logged-in to their facebook:
define('FACEBOOK_APP_ID', 'YOUR APP ID');
define('FACEBOOK_SECRET', 'YOUR APP SECRET');
function get_facebook_cookie($app_id, $application_secret) {
$args = array();
parse_str(trim($COOKIE['fbs' . $app_id], '"'), $args);
ksort($args);
$payload = '';
foreach ($args as $key => $value) {
if ($key != 'sig') {
$payload .= $key . '=' . $value;
}
}
if (md5($payload . $application_secret) != $args['sig']) {
return null;
}
return $args;
}
$fbcookie = get_facebook_cookie(FACEBOOK_APP_ID, FACEBOOK_SECRET);
$fb_access_token = $fbcookie['access_token'];
I'm presuming you know about the app ID and secret etc etc... fill those out under the define section.
Next we need to add a couple of things into the html for the javascript login:
FB.init({appId: 'YOUR APP ID AGAIN', status: true,
cookie: true, xfbml: true});
FB.Event.subscribe('auth.login', function(response) {
window.location.reload();
});
That goes into your body script.
The next part is the facebook login button:
?fb:login-button perms="publish_stream,offline_access" onlogin="window.location.reload(true);" autologoutlink="true"? ?/fb:login-button?
(the question marks are the <> symbols as these conflict with the coding symbols in Stackoverflow)
Now you may wonder about the need for offline access. That's easy... I wonder about that too! lol I'm not 100% sure why that occurs but I think it's my webserver (a tad odd it is) so try it without offline permissions first and if that doesn't work then add it back in.
So that's all you have to do for the login aspect and posting aspect is a curl script:
$url = "https://graph.facebook.com/me/feed";
$ch = curl_init();
$attachment = array( 'access_token' => '' . $fb_access_token . '',
'message' => "just searched " . $q . " at http://domain.com",
);
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $attachment);
$result= curl_exec($ch);
curl_close ($ch);
So did you see what I did? don't forget to add if statements depending on your website layout etc etc so that users don't keep posting "i just searched at http:// domain.com" lol although that would spark that human curiosity ;) due to no searching being done thus $q=NULL and thus it'll still send nothing lol so maybe ad an if statement for when you have a query lol :P (Yes i know I added a space in the url from my 'print' version however stackoverflow is picky about how many url's I can post v_v" lol).
Please ask me if you need me to explain an other parts any further.
Good luck and happy searching!
Jon

Categories