php - Facebook Video Upload Curl - php

To upload the video to Facebook using the following lines.
$video = "http://xxx.com/video.mp4";
$data = array('name' => 'file', 'file' => $video,
'access_token' => $access_token, '_title' => $video_title,
'description' => $video_desc);
$post_url = "https://graph-video.facebook.com/" . $page_id . "/videos";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $post_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$res = curl_exec($ch);
I received an error:
"error":{"message":"(#353) You must select a video file to
upload.","type":"OAuthException","code":353}}
If I change curl to form post it works. Any ideas on why is it so?

Use the path to the video on server instead of the url. So:
$video = "uploads/video.mp4";
Then:
$data = array('name' => 'file', 'file' => '#'.realpath($video),
'access_token' => $access_token, '_title' => $video_title,
'description' => $video_desc);
Notice the use of realpath() following the '#' symbol. Haven't tested with your code but I have a similar implementation and works great. Should do the trick!

For FB SDK4: (see the hardcoded video path, and the encoding).
FB requests the video file to be passed encoded as form-data:
https://developers.facebook.com/docs/graph-api/reference/user/videos/
private function postFBVideo($authResponse, $fileObj, $formData)
{
FacebookSession::setDefaultApplication('yourAppkey', 'yourAppSecret');
$ajaxResponse = '';
try {
$session = new FacebookSession($authResponse->accessToken);
} catch (FacebookRequestException $ex) {
// When Facebook returns an error
$ajaxResponse = 'FB Error ->' . json_encode($ex) ;
} catch (\Exception $ex) {
// When validation fails or other local issues
$ajaxResponse = 'FB Validation Error - ' . json_encode($ex) ;
}
if ($session) {
$response = (new FacebookRequest(
$session, 'POST', '/me/videos', array(
'source' => new CURLFile('videos/81JZrD_IMG_4349.MOV', 'video/MOV'),
'message' => $formDataMessage,
)
))->execute();
$ajaxResponse = $response->getGraphObject();
}
return json_encode($ajaxResponse);
}

Related

Untitle file issue at google drive when using curl API

When I try to upload file at google drive using php curl API it is giving untitled. ANd I can't show file name. How can I properly upload file using curl php? I don't want to use client libraries.There is not file title of uploaded file at google drive
function save_application_form($wpcf7) {
//global $wpdb;
$submission = WPCF7_Submission::get_instance();
if ($submission) {
$submited = array();
$submited['title'] = $wpcf7->title();
$submited['posted_data'] = $submission->get_posted_data();
$uploaded_files = $submission->uploaded_files();
}
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$cf7_file_field_name = 'file-846';
$image_location = $uploaded_files[$cf7_file_field_name];
$mime_type = finfo_file($finfo, $image_location);
$token = GetRefreshedAccessToken('client_id', 'refresh_token', 'client_secret');
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => 'https://www.googleapis.com/upload/drive/v3/files?uploadType=media',
CURLOPT_HTTPHEADER => array(
'Content-Type:' . $mime_type,
'Authorization: Bearer ' . $token
),
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => file_get_contents($image_location),
CURLOPT_RETURNTRANSFER => 1
));
$response = curl_exec($ch);
$err = curl_error($ch);
curl_close($ch);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
}
You are not uploading the metadata of the file you are only uploading the file itself. THe post body needs to include the file metadata the filename being one of those items.
Offical php client library example
The documentation shows how to do this with googles client library.
$fileMetadata = new Google_Service_Drive_DriveFile(array(
'name' => 'photo.jpg'));
$content = file_get_contents('files/photo.jpg');
$file = $driveService->files->create($fileMetadata, array(
'data' => $content,
'mimeType' => 'image/jpeg',
'uploadType' => 'multipart',
'fields' => 'id'));
printf("File ID: %s\n", $file->id);
PHP CURL wild guess
Sorry i cant help you do this in curl. But it should just be a matter of sending the post body as a JSon string containing the data you wish. The following is my best guess after some Googling.
$data = array("name" => "picture.jpg", "mimeType"=> "image/jpeg");
$data_string = json_encode($data);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);

Error access token with LinkedIn

After many tests, I cannot retrieve the access token. It gives me every time this error:
"error_description":"missing required parameters, includes an invalid parameter value, parameter more than once. : Unable to retrieve access token : authorization code not found","error":"invalid_request"
I totally distraught. For a few days I cannot solve my problem.
Here is the code of my application :
Route::get('login/linkedin', function()
{
$lk_credentials = Config::get('linkedin.public0');
$provider = new LinkedIn($lk_credentials);
if(!Input::has('code')){
$provider->authorize();
}else{
$code = Input::get('code');
if(strlen($code) == 0) return Redirect::to('/')->with('message', 'There was an error communicating with LinkedIn');
try{
$params = array(
'response_type' => 'code',
'client_id' => '*************',
'redirect_uri' => urlencode(url('login/linkedin')),
'state' => $_GET['state'],
);
$postdata = http_build_query($params);
$url = '/uas/oauth2/authorization?'.$postdata;
$context = stream_context_create(array('https' => array('method' => 'GET')));
$t = $provider->getAccessToken('authorization_code', array('code' => $_GET['code']));
Session::put('oauth2_access_token', $t->accessToken);session(['oauth2_access_token' => $t->accessToken]);
try{
if(count($_POST) > 0){
print_r($_POST);
exit('post');
}
$params = array(
'grant_type' => 'authorization_code',
'code' => Session::get('oauth2_access_token'), //$_GET['code'],
'redirect_uri' => urlencode(url('login/linkedin')),
'client_id' => '123456789',
'client_secret' => '123456789',
);
$postdata = http_build_query($params);
$c = curl_init();
curl_setopt($c, CURLOPT_URL, 'https://www.linkedin.com/uas/oauth2/accessToken');
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_POST,true);
curl_setopt($c, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($c, CURLOPT_POSTFIELDS,$postdata);
curl_setopt($c, CURLOPT_HEADER, false);
curl_setopt($c, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded',));
$output = curl_exec($c);
if($output === false){
trigger_error('Erreur curl : '.curl_error($c),E_USER_WARNING);
exit('Erreur');
}else{
var_dump($output);
//exit('Affiche');
}
curl_close($c);
}catch(Exception $e){
return 'Unable to get Request Token';
}
}catch(Exception $e){
return 'Unable to get user authorization_code';
}
try{
$resource = '/v1/people/~:(id,emailAddress,firstName,lastName,pictureUrl,dateOfBirth,location)';
$params = array(
'oauth2_access_token' => Session::get('oauth2_access_token'),
'format' => 'json',
);
$url = 'https://api.linkedin.com' . $resource . '?' . http_build_query($params);
$context = stream_context_create(array('http' => array('method' => 'GET')));
$response = file_get_contents($url, false, $context);
$data = json_decode($response);
Session::put('data', $data);session(['data' => $data]);
return redirect('/')->with('data',$data);
}catch(Exception $e){
return 'Unable to get user details';
}
}
});
Does anyone could help me?
For information; I use Laravel5 and for the authentication is OAuth2.
Thank you in advance, David.

Request HTTP POST cURL

I have a problem with a request post http. The params are correct but I have an error.
This is my code
Route::get('login/linkedin', function()
{
$lk_credentials = Config::get('linkedin.public0');
$provider = new LinkedIn($lk_credentials);
if(!Input::has('code')){
//exit('debug');
$provider->authorize();
}else{
try{
$code = Input::get('code');
if(strlen($code) == 0) return Redirect::to('/')->with('message', 'There was an error communicating with LinkedIn');
$t = $provider->getAccessToken('authorization_code', array('code' => $code));
}catch(Exception $e){
return 'Unable to get access token';
}
try{
$userDetails = $provider->getUserDetails($t);
$resource = '/v1/people/~:(id,emailAddress,firstName,lastName,pictureUrl,dateOfBirth,location)';
$params = array(
'oauth2_access_token' => $t->accessToken,
'format' => 'json',
);
Session::put('oauth2_access_token', $t->accessToken);session(['oauth2_access_token' => $t->accessToken]);
$url = 'https://api.linkedin.com' . $resource . '?' . http_build_query($params);
$context = stream_context_create(array('http' => array('method' => 'GET')));
$response = file_get_contents($url, false, $context);
$data = json_decode($response);
Session::put('data', $data);session(['data' => $data]);
}catch(Exception $e){
return 'Unable to get user details';
}
try{
if(count($_POST) > 0){
print_r($_POST);
exit();
}
$params = array(
'grant_type' => 'authorization_code',
'code' => Session::get('oauth2_access_token'),
'redirect_uri' => url('login/linkedin'),
'client_id' => '************',
'client_secret' => '***************',
);
$c = curl_init();
curl_setopt($c, CURLOPT_URL, 'http://www.linkedin.com/uas/oauth2/accessToken?');
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_POST,true);
curl_setopt($c, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($c, CURLOPT_POSTFIELDS,$params);
curl_setopt($c, CURLOPT_HEADER, false);
curl_setopt($c, CURLOPT_HTTPHEADER, array(
'Content-Type: application/x-www-form-urlencoded',
)
);
$output = curl_exec($c);
if($output === false){
trigger_error('Erreur curl : '.curl_error($c),E_USER_WARNING);
exit('Erreur');
}
else{
var_dump($output);
exit('Affiche');
}
curl_close($c);
return redirect('/')->with('data',$data);
}catch(Exception $e){
return 'Unable to get Request Token';
}
}
});
And this is my error :
{"error_description":"missing required parameters,
includes an invalid parameter value, parameter more than once.
: Unable to retrieve access token : authorization code not found",
"error":"invalid_request"}
While building $params array remember that url must be urlencoded, so if your url function doesn't do that, change this line to:
'redirect_uri' => urlencode(url('login/linkedin'))
Then make post string like this:
$params = http_build_query($params);
And remove ? at the end of CURLOPT_URL.
Also you should include CURLOPT_USERAGENT.

Facebook Invalid OAuth access token signature trying to post an attachment to group wall from PHP

I am an administrator (manager role) of a Facebook Group. I created an app, and stored its id and secret.
I want my app to be able to post something on the Facebook group's feed. But when I attempt to post, I get the error 190 Invalid OAuth access token signature, even though I able to successfully obtain the access_token with publish_stream and offline_access scopes. It has the form of NNNNNNNNNNNNNNN|XXXXXXXXXXXXXXXXXXXXXXXXXXX, where N is a number (15) and X is a letter or a number (27).
What should I do more to get this accomplished? Here is the code I am using:
public static function postToFB($message, $image, $link) {
//Get App Token
$token = self::getFacebookToken();
// Create FB Object Instance
$facebook = new Facebook(array(
'appId' => self::fb_appid,
'secret' => self::fb_secret,
'cookie' => true
));
//$token = $facebook->getAccessToken();
//Try to Publish on wall or catch the Facebook exception
try {
$attachment = array('access_token' => $token,
'message' => $message,
'picture' => $image,
'link' => $link,
//'name' => '',
//'caption' => '',
'description' => 'More...',
//'actions' => array(array('name' => 'Action Text', 'link' => 'http://apps.facebook.com/xxxxxx/'))
);
$result = $facebook->api('/'.self::fb_groupid.'/feed/', 'post', $attachment);
} catch (FacebookApiException $e) { //If the post is not published, print error details
echo '<pre>';
print_r($e);
echo '</pre>';
}
}
Code which returns the token
//Function to Get Access Token
public static function getFacebookToken($appid = self::fb_appid, $appsecret = self::fb_secret) {
$args = array(
'grant_type' => 'client_credentials',
'client_id' => $appid,
'client_secret' => $appsecret,
'redirect_uri' => 'https://www.facebook.com/connect/login_success.html',
'scope' => 'publish_stream,offline_access'
);
$ch = curl_init();
$url = 'https://graph.facebook.com/oauth/access_token';
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $args);
try {
$data = curl_exec($ch);
} catch (Exception $exc) {
error_log($exc->getMessage());
}
return json_encode($data);
}
If I uncomment $token = $facebook->getAccessToken(); in the posting code, it gives me yet another error (#200) The user hasn't authorized the application to perform this action.
The token I get using
developers.facebook.com/tools/explorer/ is of another form, much longer and with it I am able to post to the group page feed.
How do I do it without copy/paste from Graph API Explorer and how do I post as a group instead of posting as a user?
Thanks.

FB development - Upload a photo into user's profile

Can you tell me what I do wrong. I use PHP. Try to upload the photo into users profile.. I get permissions and it works. But uploading doesn't work, I tryed many ways. So what do I do wrong?
<?php
include_once 'facebook.php';
$facebook = new Facebook(array(
'appId' => 'ID',
'secret' => 'SECRET',
'cookie' => true,
'domain' => 'DOMAIN',
'fileUpload' => 'true'
));
$session = $facebook->getSession();
if (!$session) {
$loginUrl = $facebook->getLoginUrl(array(
'canvas' => 1,
'fbconnect' => 1,
'display' => 'page',
'req_perms' => 'user_likes, publish_stream',
'next' => 'NEXTURL'
));
echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
} else{
try {
$uid = $facebook->getUser();
$me = $facebook->api('/me');
$token = $session['access_token'];//here I get the token from the $session array
$album_id = 'ALBUM ID'; /// what should I write here?
//upload your photo
$file= 'logo.png';
$args = array(
'message' => 'Photo from app',
);
$args[basename($file)] = '#' . realpath($file);
$ch = curl_init();
$url = 'https://graph.facebook.com/'.$album_id.'/photos?access_token='.$token;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $args);
$data = curl_exec($ch);
//returns the id of the photo you just uploaded
print_r(json_decode($data,true));
} catch(FacebookApiException $e){
echo "Error:" . print_r($e, true);
}
}
?>
Thanks in advance
You must add the property fileUpload==true to the Facebook-Object:
$facebook = new Facebook(array(
'appId' => 'ID',
'secret' => 'SECRET',
'cookie' => true,
'domain' => 'DOMAIN',
'fileUpload' => true
));
UPDATE:
I always use this code to upload photos:
$photo= $facebook->api(array('method'=>'photos.upload',
'caption'=>SOME_TEXT,
'file'=>'#'.$file));
You can try this :
$args = array('message' => $mess,
);
$args['image'] = '#' . realpath($file.".jpeg");
$facebook->setFileUploadSupport(true);
try
{
if(!isset($_GET['a']))
{
$data = $facebook->api('/me/photos', 'post', $args);
}
// echo "<br/>Image posted. Click here to view. Thanks for using this application.";
}
catch(FacebookApiException $e)
{
var_dump($e);
}
This is a direct excerpt from a working code.
try this
$args = array('message' => 'Photo Upload');
$args['image'] = '#' . realpath($FILE_PATH);
$data = $facebook->api("/{$album_id}/photos", 'post', $args);
Note: if you want to create a new album name same as the app name and upload there then you have to use
$facebook->api("/me/photos", 'post', $args);

Categories