When trying to create an event on YouTube using YouTube Data API I get following error only in case of very few users:
Fatal error: Uncaught exception 'Google_Service_Exception' with message 'Error calling POST https://www.googleapis.com/youtube/v3/liveBroadcasts?part=snippet%2Cstatus: (403) The user is not enabled for live streaming.' in E:\Rupesh\Websites\abtv\abstream\Google\Http\REST.php on line 110
Please also note following :
The user id is of the form xyz#gmail.com only. I know for fact, this code does not work for user id of the form xyz##pages.plusgoogle.com.
User is authenticated using Google's OAuth 2 prior to calling this function.
User has allowed access to Web Application using #gmail.com id.
Following is class I have put together:
set_include_path(get_include_path() . PATH_SEPARATOR . '/home/aprilbr3/public_html/google-api-php-client/src');
require_once 'Google/autoload.php';
require_once 'Google/Client.php';
require_once 'Google/Service/Oauth2.php';
require_once 'class.miscellaneous_functions.php';
class GoogleClient
{
public static $cdn_formats = array(
"Poor" => "240p", "Ok" => "360p", "Good" => "480p", "Better" => "720p", "Best" => "1080p");
public static $privacy_statuses = array(
"public" => "public", "unlisted" => "unlisted", "private" => "private");
private static $OAUTH2_CLIENT_ID = 'CLIENT_ID_HERE';
private static $OAUTH2_CLIENT_SECRET = 'CLIENT_SECRET_HERE';
private static $privacy_status = "public"; // $privacy_statuses["public"];
//private static $cdn_format = $cdn_formats["Ok"];
private static $cdn_injestion_type = "rtmp";
var $client;
var $plus;
var $redirect_url;
var $user_info;
function __construct()
{
$this->client = new Google_Client();
$this->client->setClientId(GoogleClient::$OAUTH2_CLIENT_ID);
$this->client->setClientSecret(GoogleClient::$OAUTH2_CLIENT_SECRET);
$redirect_url = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'],
FILTER_SANITIZE_URL);
$this->client->setRedirectUri($redirect_url);
$this->client->setScopes(array(
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile',
'https://www.googleapis.com/auth/youtube'));
$this->plus = new Google_Service_Oauth2($this->client);
} // __construct()
function OAuth2()
{
if (!isset($_SESSION))
session_start();
if (isset($_REQUEST['logout'])) {
unset($_SESSION['access_token']);
}
if (isset($_GET['code'])) {
try {
$this->client->authenticate($_GET['code']);
} catch (Google_Auth_Exception $e) {
MiscellaneousFunctions::DestroySessionAndRedirectTo($this->redirect_url);
}
$_SESSION['access_token'] = $this->client->getAccessToken();
header('Location:' . $this->redirect_url);
}
if (isset($_SESSION['access_token'])) {
$this->client->setAccessToken($_SESSION['access_token']);
}
$error = false;
if (!$this->client->getAccessToken()) {
$error = true;
}
if (!$error) {
try {
$user_info = $this->plus->userinfo->get();
return array('result' => true, 'user_info' => $user_info);
} catch (Google_Service_Exception $e) {
MiscellaneousFunctions::DestroySessionAndRedirectTo($this->redirect_url);
//exit();
} catch (Google_Exception $e) {
MiscellaneousFunctions::DestroySessionAndRedirectTo($this->redirect_url);
//exit();
}
}
return array('result' => false, 'auth_url' => $this->client->createAuthUrl());
//MiscellaneousFunctions::DestroySessionAndRedirectTo($this->client->createAuthUrl());
//exit();
} // OAuth2
function CreateEvent($broadcast_title, $broadcast_description, $cdn_format,
$start_date_time, $end_date_time)
{
//echo( "Step 1" . "\n<br><br><br>");
$stream_title = "Stream for " . $broadcast_title;
$youtube = new Google_Service_YouTube($this->client);
try {
// Create an object for the liveBroadcast resource's snippet. Specify values
// for the snippet's title, scheduled start time, and scheduled end time.
$broadcastSnippet = new Google_Service_YouTube_LiveBroadcastSnippet();
$broadcastSnippet->setTitle($broadcast_title);
//echo( "Step 2" . "\n<br><br><br>");
//echo( "Start Time : " . MiscellaneousFunctions::GetDateTimeStringForYoutube($start_date_time) . "\n</br>");
//echo( "End Time : " . MiscellaneousFunctions::GetDateTimeStringForYoutube($end_date_time) . "\n</br>");
//exit;
$broadcastSnippet->setScheduledStartTime(
MiscellaneousFunctions::GetDateTimeStringForYoutube($start_date_time));
$broadcastSnippet->setScheduledEndTime(
MiscellaneousFunctions::GetDateTimeStringForYoutube($end_date_time));
$broadcastSnippet->setDescription($broadcast_description);
//echo( "Step 3" . "\n<br><br><br>");
// Create an object for the liveBroadcast resource's status, and set the
// broadcast's status to "private".
$status = new Google_Service_YouTube_LiveBroadcastStatus();
$status->setPrivacyStatus(GoogleClient::$privacy_status);
//echo( "Step 4" . "\n<br><br><br>");
// Create the API request that inserts the liveBroadcast resource.
$broadcastInsert = new Google_Service_YouTube_LiveBroadcast();
$broadcastInsert->setSnippet($broadcastSnippet);
$broadcastInsert->setStatus($status);
$broadcastInsert->setKind('youtube#liveBroadcast');
//echo( "Step 5" . "\n<br><br><br>");
//echo( json_encode( $youtube ) . "\n<br><br><br>");
// Execute the request and return an object that contains information
// about the new broadcast.
$broadcastsResponse = $youtube->liveBroadcasts->insert('snippet,status',
$broadcastInsert, array());
//echo( "Step 6" . "\n<br><br><br>");
// Create an object for the liveStream resource's snippet. Specify a value
// for the snippet's title.
$streamSnippet = new Google_Service_YouTube_LiveStreamSnippet();
$streamSnippet->setTitle($stream_title);
// echo( "Step 7" . "\n<br><br><br>");
// Create an object for content distribution network details for the live
// stream and specify the stream's format and ingestion type.
$cdn = new Google_Service_YouTube_CdnSettings();
$cdn->setFormat($cdn_format);
$cdn->setIngestionType(GoogleClient::$cdn_injestion_type);
// echo( "Step 8" . "\n<br><br><br>");
// Create the API request that inserts the liveStream resource.
$streamInsert = new Google_Service_YouTube_LiveStream();
$streamInsert->setSnippet($streamSnippet);
$streamInsert->setCdn($cdn);
$streamInsert->setKind('youtube#liveStream');
// echo( "Step 9" . "\n<br><br><br>");
// Execute the request and return an object that contains information
// about the new stream.
$streamsResponse = $youtube->liveStreams->insert('snippet,cdn', $streamInsert, array());
// Bind the broadcast to the live stream.
$bindBroadcastResponse = $youtube->liveBroadcasts->bind(
$broadcastsResponse['id'], 'id,contentDetails',
array('streamId' => $streamsResponse['id'],));
// echo( "Step 10" . "\n<br><br><br>");
return array('result' => true,
'broadcasts_response' => $broadcastsResponse,
//'broadcasts_response_id' => $broadcastsResponse['id'],
//'broadcasts_response_snippet' => $broadcastsResponse['snippet'],
'streams_response' => $streamsResponse
//'streams_response_id' => $streamsResponse['id'],
//'streams_response_snippet' => $streamsResponse['snippet'],
//'streams_response_cdn' => $streamsResponse['cdn'],
//'streams_response_cdn_ingestionInfo' => $streamsResponse['cdn']['ingestionInfo']
);
} catch (Google_Service_Exception $e) {
//MiscellaneousFunctions::DestroySessionAndRedirectTo($this->redirect_url);
$reason = json_encode($e->getMessage(), JSON_PRETTY_PRINT);
//echo( "Google_Service_Exception:" . json_encode( $e ) . "\n<br><br><br>");
// return array('result' => false, 'reason' => $reason);
} catch (Google_Exception $e) {
//MiscellaneousFunctions::DestroySessionAndRedirectTo($this->redirect_url);
$reason = json_encode($e->getMessage(), JSON_PRETTY_PRINT);
//echo( "Google_Exception:" . json_encode( $e ) . "\n<br><br><br>");
//return array('result' => false, 'reason' => $reason);
}
return array('result' => false, 'reason' => $reason);
}
function GetEvent( $broadcast_id )
{
$youtube = new Google_Service_YouTube($this->client);
try {
// Execute an API request that lists broadcasts owned by the user who
// authorized the request.
$broadcastsResponse = $youtube->liveBroadcasts->listLiveBroadcasts(
'id,snippet,contentDetails,status',
array( 'id' => $broadcast_id ));
$broadcastItem = $broadcastsResponse['items'][0];
$streamId = $broadcastItem['contentDetails']['boundStreamId'];
$streamsResponse = $youtube->liveStreams->listLiveStreams(
'id,snippet,cdn,status',
array( 'id' => $streamId ));
$streamItem = $streamsResponse['items'][0];
return array('result' => true,
'broadcasts_response' => $broadcastItem,
'streams_response' => $streamItem
);
} catch (Google_Service_Exception $e) {
$reason = json_encode($e->getMessage(), JSON_PRETTY_PRINT);
} catch (Google_Exception $e) {
$reason = json_encode($e->getMessage(), JSON_PRETTY_PRINT);
}
return array('result' => false, 'reason' => $reason);
}
} // class GoogleClient
Thank you.
Rupesh
P.S: Sorry, I forgot to mention that all the users of the system have enabled live streaming in their respective youtube accounts. That's what puzzles me!
Related
I have created an event on my test page and I'm going to upload a video to that event page from my web site. I have used the below code but it is doesn't work.
$data = [
'title' => 'test Video',
'description' => 'This is test video',
'source' => $fb->videoToUpload($video_path),
];
try {
$response = $fb->post('/' . $event_id . '/videos', $data, $page_token);
} catch(Facebook\Exceptions\FacebookResponseException $e) {
return 'Graph returned an error: ' . $e->getMessage();
} catch(Facebook\Exceptions\FacebookSDKException $e){
return 'Facebook SDK returned an error: ' . $e->getMessage();
}
$graphNode = $response->getGraphNode();
I got this error.
Graph returned an error:(#33) This object does not exist or does not support this action.
So I fix some parts like this.
$data = [
.......
'source' => $video_path
];
try{
$response = $fb->post('/' . $event_id . '/feed', $data, $page_token);
}
.......
Then it works like this.
But I want to result like as this picture.
How shall I do?
Official reference for post video on event (Api Graph v5.0):
Upload:
$fb = new Facebook\Facebook([
'app_id' => '{app-id}',
'app_secret' => '{app-secret}',
'default_graph_version' => 'v2.2',
]);
$data = [
'title' => 'My Foo Video',
'description' => 'This video is full of foo and bar action.',
'source' => $fb->videoToUpload('/path/to/foo_bar.mp4'),
];
try {
$response = $fb->post('/me/videos', $data, 'user-access-token');
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
$graphNode = $response->getGraphNode();
var_dump($graphNode);
echo 'Video ID: ' . $graphNode['id'];
POST ON EVENT:
/* PHP SDK v5.0.0 */
/* make the API call */
try {
// Returns a `Facebook\FacebookResponse` object
$response = $fb->get(
'/{event-id}/videos',
'{access-token}'
);
} catch(Facebook\Exceptions\FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
$graphNode = $response->getGraphNode();
/* handle the result */
If you see the result JSON :
{
"data": [],
"paging": {}
}
All reference:
-Start - Initialize an upload session
-Transfer - Upload video chunks
-Finish - Post the video
In the function:
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', '/.$idevent./videos', array(
'source' => new CURLFile('path', 'video/MOV'),
'message' => $formDataMessage,
)
))->execute();
$ajaxResponse = $response->getGraphObject();
}
return json_encode($ajaxResponse);
}
I've implemented system wide with JWT. Everything is working great except a key point, the expiration method.
Map<String, Object> header = new HashMap<>();
header.put("typ", Header.JWT_TYPE);
String compactJws = Jwts.builder()
.setHeader(header)
.claim("email", email)
.claim("password", password)
.setIssuedAt(new Date(System.currentTimeMillis()))
.setExpiration(new Date(System.currentTimeMillis() + 3600000))
.signWith(SignatureAlgorithm.HS256, settings.getString("keychain", "password"))
.compact();
Request request = new Request.Builder()
.url(SITE_URL + "secure.php")
.post(new FormBody.Builder().add("data", compactJws).build())
.tag("login")
.build();
okClient.newCall(request).enqueue(this);
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJlbWFpbCI6Imd1eSIsInBhc3N3b3JkIjoiZ3V5IiwiaWF0IjoxNDk3NTU0MzAzLCJleHAiOjE0OTc1NTc5MDN9.4GFSC_OCYzkCxGetTFKKxoUkbpxWi51ccoKtIpPjz6g
<?php
$jwt = $_POST['data'];
require_once 'jwt/src/BeforeValidException.php';
require_once 'jwt/src/ExpiredException.php';
require_once 'jwt/src/SignatureInvalidException.php';
require_once 'jwt/src/JWT.php';
use \Firebase\JWT\JWT;
try {
$decoded_array = (array) JWT::decode($jwt, base64_decode("password"), array('HS256'));
}
catch (SignatureInvalidException $e) {
echo json_encode(array('user_id' => - 3, 'title' => 'Contact 3gcb19#gmail.com', 'msg' => 'SignatureInvalidException'));
exit(0);
}
catch (ExpiredException $e) {
echo json_encode(array('user_id' => - 3, 'title' => 'Contact 3gcb19#gmail.com', 'msg' => 'ExpiredException'));
exit(0);
}
catch (UnexpectedValueException $e) {
echo json_encode(array('user_id' => - 3, 'title' => 'Contact 3gcb19#gmail.com', 'msg' => 'UnexpectedValueException'));
exit(0);
}
$email = $decoded_array['email'];
$password = $decoded_array['password'];
Always throws an UnexpectedValueException
Remove the timestamps and it works fine on the php end
.setIssuedAt(new Date(System.currentTimeMillis()))
.setExpiration(new Date(System.currentTimeMillis() + 3600000))
What am I missing here??
Facebook SDK returned an error: Cross-site request forgery validation failed. The "state" param from the URL and session do not match.
ok.I have try all the way that I find on the stackoverflow about the same question,but unfortunately,the same question has occured all the time,I am crazy now.Please help me!
this is the login.php:
<?php
require_once __DIR__ . '\Facebook\autoload.php';
if(!session_id()) {
session_start();
}
$fb = new Facebook\Facebook([
'app_id' => 'my_app_id',
'app_secret' => 'and_my_app_secret',
'default_graph_version' => 'v2.5',
// 'persistent_data_handler'=>'session',
]);
$helper = $fb->getRedirectLoginHelper();
$permissions = ['email']; // Optional permissions
$loginUrl = $helper->getLoginUrl('http://my_ip/facebook/login-callback.php', $permissions);
foreach ($_SESSION as $k=>$v) {
if(strpos($k, "FBRLH_")!==FALSE) {
if(!setcookie($k, $v)) {
echo "there is no cookie";
exit;
} else {
$_COOKIE[$k]=$v;
}
}
}
var_dump($_COOKIE);
echo 'Log in with Facebook! ';
?>
and this is the login-callback.php:
<?php
require_once __DIR__ . '\Facebook\autoload.php';
if(!session_id()) {
session_start();
}
foreach ($_COOKIE as $k=>$v) {
if(strpos($k, "FBRLH_")!==FALSE) {
$_SESSION[$k]=$v;
}
}
$fb = new Facebook\Facebook([
'app_id' => 'my_app_id',
'app_secret' => 'my_app_secret',
'default_graph_version' => 'v2.5',
// 'persistent_data_handler'=>'session',
]);
$helper = $fb->getRedirectLoginHelper();
try {
$accessToken = $helper->getAccessToken();
var_dump($accessToken);
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
if (! isset($accessToken)) {
if ($helper->getError()) {
header('HTTP/1.0 401 Unauthorized');
echo "Error: " . $helper->getError() . "\n";
echo "Error Code: " . $helper->getErrorCode() . "\n";
echo "Error Reason: " . $helper->getErrorReason() . "\n";
echo "Error Description: " . $helper->getErrorDescription() . "\n";
} else {
header('HTTP/1.0 400 Bad Request');
echo 'Bad request';
}
exit;
}
// Logged in
echo '<h3>Access Token</h3>';
var_dump($accessToken->getValue());
$_SESSION['fb_access_token'] = (string) $accessToken;
?>
hello correct your permission variable like
FacebookSession::setDefaultApplication( 'app_id','app_secreat' );
// login helper with redirect_uri
$helper = new FacebookRedirectLoginHelper('redirect url' );
try {
$session = $helper->getSessionFromRedirect();
} catch( FacebookRequestException $ex ) {
$session = null;
// When Facebook returns an error
} catch( Exception $ex ) {
// When validation fails or other local issues
}
// see if we have a session
if ( isset( $session ) ) {
// graph api request for user data
$accessToken = $session->getAccessToken();
$longLivedAccessToken = $accessToken->extend();
if (isset($longLivedAccessToken)) {
// Logged in!
$_SESSION['facebook_access_token'] = (string) $longLivedAccessToken;
}
$request = new FacebookRequest($session, 'GET', '/me',
array(
'fields' => 'id,name,email'
) );
$response = $request->execute();
// get response
$graphObject = $response->getGraphObject();
//print_r($graphObject);die();
$fbid = $graphObject->getProperty('id'); // To Get Facebook ID
$fbfullname = $graphObject->getProperty('name'); // To Get Facebook full name
$femail = $graphObject->getProperty('email');
//checkuser($fbid,$fbfullname,$femail);
$request1 = new FacebookRequest($session, 'GET', '/me/accounts',
array(
'fields' => 'id,access_token,name'
) );
$pageList= $request1->execute()
->getGraphObject()
->asArray();
use this code and get request
Please Go to the file
src/Facebook/PersistentData/PersistentDataFactory.php
In Your Facebook SDK
find this Code
if ('session' === $handler) {
new FacebookSessionPersistentDataHandler();
}
and Replace With
if ('session' === $handler) {
return new FacebookSessionPersistentDataHandler();
}
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
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
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.
file is not a valid parameter. Instead of parameter file, use source.
Reference
For FB SDK4+Composer: (see the hardcoded video path, and the encoding).
Doc: https://developers.facebook.com/docs/php/gettingstarted/4.0.0
FB requests the video file to be passed encoded as form-data:
https://developers.facebook.com/docs/graph-api/reference/user/videos/
use Facebook\FacebookSession;
use Facebook\GraphSessionInfo;
use Facebook\FacebookRequest;
use Facebook\GraphUser;
use Facebook\FacebookRequestException;
use Facebook\FacebookRedirectLoginHelper;
private function postFBVideo($authResponse, $filePath, $formDataMessage)
{
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);
}
I am tring to access http://xxxxxxxxxxx/CRM2011/XRMServices/2011/Organization.svc?wsdl
I can able to see functions list. means i can access to webservice. But while i tring to write data using function create it through "an error occurred when verifying security for the message" my code is below
<?php
date_default_timezone_set("Asia/Kolkata");
ini_set("soap.wsdl_cache_enabled", "0");
$location = "http://182.18.175.29/CRM2011/XRMServices/2011/Organization.svc?wsdl";
$config['Username'] = 'xxxxxxx';
$config['Password'] = 'xxxxxx';
$config['soap_version'] = SOAP_1_2;
$config['trace'] = 1; // enable trace to view what is happening
$config['use'] = SOAP_LITERAL;
$config['style'] = SOAP_DOCUMENT;
$config['exceptions'] = 0; // disable exceptions
$config["cache_wsdl"] = WSDL_CACHE_NONE; // disable any caching on the wsdl, encase you alter the wsdl server
$config["features"] = SOAP_SINGLE_ELEMENT_ARRAYS;
include_once 'ntlmSoap.php';
$client = new NTLMSoapClient($location, $config);
print('<pre>');
print_r($client->__getFunctions());
$HeaderSecurity = array("UsernameToken" => array("Username" => 'xxxxxx', "Password" => 'xxxxxx'));
$header[] = new SoapHeader($location, "Security", $HeaderSecurity);
$client->__setSoapHeaders($header);
$params = array(
"bmw_firstname" => "test",
"bmw_lastname" => "test"
);
try {
$response = $client->__soapCall("Create", $params);
var_dump($response);
} catch (Exception $e) {
print_r($e);
}
// display what was sent to the server (the request)
echo "<p>Request :" . htmlspecialchars($client->__getLastRequest()) . "</p>";
// display the response from the server
echo "<p>Response:" . htmlspecialchars($client->__getLastResponse()) . "</p>";