Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Posting video on Facebook through Graph API using a valid access token

I have a video exist on my server, I need to post that video on Facebook using Graph API.

Here is the code suggested by Team Facebook.

What I am doing is as below.

1) From an Android device I am getting an access token

2) Recognizing user by passing that access token to Facebook and get email id and through email id recognize user

3) Posting user's video from my server to Facebook through Graph API.

4) Returning a video id to android device as an API response.

I am approaching this route because in Android device it is 2 step process to post video on Facebook.

1) Download the video first

2) Post to Facebook

This is time consuming.

Here is the code that I am trying

    define("FB_WEB_APP_ID","********");
    define("FB_WEB_SECRET","********");
    define("FB_WEB_REDIRECT_URI","<< redirect url >>");
    $GLOBALS["all_user_dir_path"]="/var/www/proj/web/video/user_videos/";
     define("FB_WEB_SCOPE","user_friends,email,public_profile,user_hometown,user_location,user_photos,user_videos,publish_actions,read_friendlists,publish_stream,offline_access");
    define("FB_WEB_RESPONSE_TYPE","code%20token");

    $GLOBALS["fb_app_creds"]=array();
    $GLOBALS["fb_app_creds"]['appId']= FB_WEB_APP_ID;
    $GLOBALS["fb_app_creds"]['secret']=FB_WEB_SECRET;
    $GLOBALS["fb_app_creds"]['response_type']=FB_WEB_RESPONSE_TYPE;
    $GLOBALS["fb_app_creds"]['redirect_uri']=FB_WEB_REDIRECT_URI;
    $GLOBALS["fb_app_creds"]['scope']=FB_WEB_SCOPE;
    $GLOBALS["facebook"] = new Facebook($GLOBALS["fb_app_creds"]);



class DefaultController extends Controller
{
// some code....

/**
     * @Route("/gk",name="_fb")
     * @Template()
     */
    public function gkAction(Request $request){

        $facebook = $GLOBALS["facebook"];

        $access_token=$request->query->get("access_token");

        if(!$access_token){
          die("give access token in url.......");
        }

        echo "<pre>";
        $facebook->setAccessToken($access_token);

        $user = $facebook->getUser();

        $me=$facebook->api("/me");

        $email=$me['email'];

        $all_user_dir_path=$GLOBALS["all_user_dir_path"];
        $user_directory = str_replace(array(".","@"), "_",$email);

        $user_dir_abs_path=$all_user_dir_path.$user_directory;

        print_r($me);

        $video_file_path=$user_dir_abs_path."/video.mp4";

        if(file_exists($video_file_path))
        { 
          echo "file exists...";
        }else{
          die("not exist");
        }

        $video_title="Test";
        $video_desc="Test";

        $access_token=$request->query->get("access_token");

        $file = "@".$video_file_path;
        $data =  array('name' => 'file', 'file' => $file);

          $post_url = "https://graph-video.facebook.com/me/videos?"
         . "title=" . $video_title. "&description=" . $video_desc
         . "&". $access_token
         ;


        echo "<hr>TRY 1<hr>";
        try{
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $post_url);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
            $res = curl_exec($ch);

            $video_id=0;
            if( $res === false ) {

            }else{
              $res=json_decode($res,true);
              /* $video_id = $res['id'];*/
               echo ":::: ";print_r($res);
            }
            curl_close($ch);
       }catch(\Exception $e){
           echo " Exception generated in Try 1 : ".$e->getMessage();
       }

       echo "<hr>TRY 2<hr>";

       $params = array(
            "access_token" => $access_token,
            "name"=>"file",
            "file" => "@".$video_file_path,
            "title" => $video_title,
            "description" => $video_desc
          );
          try {
              $ret = $facebook->api('/me/videos', 'POST', $params);
              print_r($ret);
          } catch(\Exception $e) {
            echo " Exception generated in Try 2 : ".$e->getMessage();
          } 

        die("</pre>");
    }    

}

Output I am getting is An active access token must be used to query information about the current user. error and (#353) You must select a video file to upload.

Look at this image

enter image description here

Please tell me how to solve this problem ??

New code tried...................................................

 /* code with sdk - object oriented way */
        $file=$GLOBALS["all_user_dir_path"].$user_directory."/video.mp4";
        $source = array();
        $source['name']="video.mp4";
        $source['type'] = "video/mp4";
        $source['tmp_name'] = $file;
        $source['error'] = 0;
        $source['size'] = filesize($file);
        echo "<br><br>$file<br><br>";

        $params = array(
          "access_token" => $access_token, 
            "source" => $source,
            "title" => "testvideo",
            "description" => "testvideo"
        );
          try {
              $ret = $facebook->api('/me/videos', 'POST', $params);
              echo 'Successfully posted to Facebook';
              echo "<pre>";print_r($ret);echo "</pre>";
          } catch(Exception $e) {
            echo $e->getMessage();
          } 

but this gives (#353) You must select a video file to upload error

like image 299
gkd Avatar asked Aug 07 '26 23:08

gkd


1 Answers

Here is the answer

public function shareSocialgrationFB($access_token,& $exception){
        $video_id=0;

        try{
            $config = array();
            $config['appId'] = FB_WEB_APP_ID;
            $config['secret'] = FB_WEB_SECRET;
            $config['fileUpload'] = true; 
            $config['cookie'] = true;
            $facebook = new Facebook($config);
            $facebook->setFileUploadSupport(true);  
            $facebook->setAccessToken($access_token);

            $me=$facebook->api("/me");
            $email=$me['email'];

            $user_directory = str_replace(array(".","@"), "_",$email);

            $file = $GLOBALS["all_user_dir_path"].$user_directory."/video.mp4";

            $usersFacebookID=$facebook->getUser();
            $video_details = array(   
                      'access_token'=> $access_token,
                      'message'=> 'Testvideo!',
                      'source'=> '@' .realpath($file),
                      'title'=>'Test'   
            );
            $post_video = $facebook->api('/'.$usersFacebookID.'/videos', 'post', $video_details);
            $video_id=$post_video['id'];
        }catch(\Exception $e){
            //echo "Exception generated :: ".$e->getMessage(); 
        $exception=$e->getMessage(); 
        // extra code to handle exception
        }
        return $video_id;
    }

Reference : How to POST video to Facebook through Graph API using PHP

I don't know why the info about configurations

$config['fileUpload'] = true; 
$config['cookie'] = true;

is not mentioned at below official docs of APIs

https://developers.facebook.com/blog/post/493/

https://developers.facebook.com/docs/graph-api/reference/v2.0/user/videos#publish

However solution given above, worked fine for me.

like image 81
gkd Avatar answered Aug 09 '26 12:08

gkd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!