PrestaShop: Update customer through web-service - php

I want to update a customer in PrestaShop using a webservice. I search for the customer based on his email and company name and then update with new details. But when I use filters to get the customer details and then update i receive the following error and im not sure how to resolve this issue.
Error 90 - id is required when modifying a resource
Code
$email=$_POST['email'];
$oldEmail=$_POST['oldEmail'];
$company=$_POST['company'];
try
{
$webService = new PrestaShopWebservice(PS_SHOP_PATH, PS_WS_AUTH_KEY, DEBUG);
$opt = array(
'resource' => 'customers',
'display' => 'full',
'filter[email]'=>'e.siona#example.gr',//['.$oldEmail.']',
'filter[company]'=>'euro'//['.$company.']'
);
$xml = $webService->get($opt);
// Retrieve resource elements in a variable (table)
$resources = $xml->children()->children();
//$opt['id'] = 17;
//echo $resources->id;
}
catch (PrestaShopWebserviceException $e){
// Here we are dealing with errors
$trace = $e->getTrace();
if ($trace[0]['args'][0] == 404) echo 'Bad ID';
else if ($trace[0]['args'][0] == 401) echo 'Bad auth key';
else echo 'Other error';
}
$resources->email = 'e.siona43#example.gr';
// Resource definition
$opt = array('resource' => 'customers');
//XML file definition
$opt['putXml'] = $xml->asXML();
$opt['id'] = 'How can I put here the id retrieved from previous call?';
// Calling asXML() returns a string corresponding to the file
$xml = $webService->edit($opt);
// Second : We update the data and send it to the web service

There was an error in official github examples.
Try this corrected version of your snippet:
$email=$_POST['email'];
$oldEmail=$_POST['oldEmail'];
$company=$_POST['company'];
try
{
$webService = new PrestaShopWebservice(PS_SHOP_PATH, PS_WS_AUTH_KEY, DEBUG);
// Filters must be an array (I'll suggest this method)
$filter = array(
'email' => $oldEmail,
'company' => 'ACME'
);
// I guess it's useless to use company because the e-mail it's a KEY in the database, so the correspondence 'should' be univocal.
$opt = array(
'resource' => 'customers',
'display' => 'full',
'filter' => $filter
);
$xml = $webService->get($opt);
// Retrieve resource elements in a variable (table)
$resources = $xml->children()->children();
}
catch (PrestaShopWebserviceException $e){
// Here we are dealing with errors
$trace = $e->getTrace();
if ($trace[0]['args'][0] == 404) echo 'Bad ID';
else if ($trace[0]['args'][0] == 401) echo 'Bad auth key';
else echo 'Other error';
}
// Here we retrieve the ID
$customer_id = $resources->customer->id;
// Here we update the e-mail
$resources->customer->email = $email; // E.g. 'e.siona43#example.gr';
// And call the web service
try
{
$opt = array('resource' => 'customers');
$opt['putXml'] = $xml->children()->asXML(); // This is correct if you have one customer in the XML. The GitHub examples it's incomplete and you get the error 90.
$opt['id'] = $customer_id;
$xml = $webService->edit($opt);
// if WebService don't throw an exception the action worked well and we don't show the following message
echo "Successfully updated.";
}
catch (PrestaShopWebserviceException $ex)
{
// Here we are dealing with errors
$trace = $ex->getTrace();
if ($trace[0]['args'][0] == 404) echo 'Bad ID';
else if ($trace[0]['args'][0] == 401) echo 'Bad auth key';
else echo 'Other error<br />'.$ex->getMessage();
}
Hope this helps :)

Related

PrestaShop WebService - Price Update for various products

I have this to update the PrestaShop price for one product with the WebService.
<html><head><title>CRUD Data Transfer - Update example</title></head><body>
<?php
// Here we define constants /!\ You need to replace this parameters
define('DEBUG', true);
define('PS_SHOP_PATH', 'https://my.domain.com');
define('ID_PRODUCT', 1);
define('PS_WS_AUTH_KEY', 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX');
require_once('./PSWebServiceLibrary.php');
#ini_set('display_errors', 'on');
try
{
$webService = new PrestaShopWebservice(PS_SHOP_PATH, PS_WS_AUTH_KEY, DEBUG);
$opt = array('resource' => 'products');
$opt['id']=ID_PRODUCT;
$xml = $webService->get($opt);
echo "Successfully recived data.";
/* List of nodes that can't modify
*
* - "manufacturer_name"
* - "position_in_category"
* - "quantity"
* - "type"
*/
unset($xml->children()->children()->manufacturer_name);
unset($xml->children()->children()->position_in_category);
unset($xml->children()->children()->quantity);
unset($xml->children()->children()->type);
$xml->children()->children()->price = 111.0; // <-- new price!
//Load new data to query generator
$opt['putXml']=$xml->asXML();
$xml = $webService->edit($opt);
// if WebService don't throw an exception the action worked well and we don't show the following message
echo "Successfully updated.";
}
catch (PrestaShopWebserviceException $ex)
{
// Here we are dealing with errors
$trace = $ex->getTrace();
if ($trace[0]['args'][0] == 404) echo 'Bad ID';
else if ($trace[0]['args'][0] == 401) echo 'Bad auth key';
else echo 'Other error<br />'.$ex->getMessage();
}
?>
</body></html>
How can i do the same, but for all the products in a MySQL table?
I have all the products in a MySQL table with the ID Key as Source_ID.
Appreciate any help!
Regards
You'll need to retrieve the product data for each product, update it's price, and then save it.
Try something like this:
<html><head><title>CRUD Data Transfer - Update example</title></head><body>
<?php
// Here we define constants /!\ You need to replace this parameters
define('DEBUG', true);
define('PS_SHOP_PATH', 'http://my.domain.com');
define('PS_WS_AUTH_KEY', 'XXXXXXXXXXXXXXXXXXXXXXXXX');
require_once('PSWebServiceLibrary.php');
#ini_set('display_errors', 'on');
try {
$webService = new PrestaShopWebservice(PS_SHOP_PATH, PS_WS_AUTH_KEY, DEBUG);
// Get products from your database via a query
$products = array(array('id' => 1, 'price' => 1.5,), array('id' => 2, 'price' => 2.95));
// Loop through products
foreach ($products as $product) {
$opt = array('resource' => 'products', 'id' => $product['id']);
// Call webservice to get product data
$xml = $webService->get($opt);
// Remove nodes that can't be modified
unset($xml->children()->children()->manufacturer_name);
unset($xml->children()->children()->position_in_category);
unset($xml->children()->children()->quantity);
unset($xml->children()->children()->type);
// Update product data
$xml->children()->children()->price = $product['price']; // <-- new price!
// Load new data to query generator
$opt['putXml'] = $xml->asXML();
// Save product
$xml = $webService->edit($opt);
// if WebService don't throw an exception the action worked well and we don't show the following message
}
} catch (PrestaShopWebserviceException $ex) {
// Here we are dealing with errors
$trace = $ex->getTrace();
if ($trace[0]['args'][0] == 404)
echo 'Bad ID';
else if ($trace[0]['args'][0] == 401)
echo 'Bad auth key';
else
echo 'Other error<br />' . $ex->getMessage();
}
?>
</body></html>
Hope this helps!

PrestaShop webService returns unexpected HTTP status 503

I am integrating warehouse management system (which is based on PHP) with PrestaShop1.6 and I am using PrestaShop Web Service for integration.
I have to make new products (which are created in warehouse management system) appear on PrestaShop 1.6 online store. Warehouse management system asks PrestaShop WebService to create new product on PrestaShop online store.
I have written this function showed below. It works good at my localhost, but on test server it receives HTTP status 503 after trying to update stock availability. All WebService methods (GET, PUT, DELETE, etc) are enabled on all WebService entities. I don't know how to debug this problem, can you help me?
By the way, I used this code as example: https://github.com/xabikip/PrestaShopWebService/blob/master/examples/createProduct.php
private function saveProduct($update, $webService, $root_path, $n_id, $n_id_category_default, $n_id_category, $n_price, $n_active, $n_avail4order, $n_show_price, $n_l_id, $n_name, $n_desc, $n_desc_short, $n_link_rewrite, $n_meta_title, $n_meta_description, $n_meta_keywords, $n_available_now, $n_available_later, $idtaglist, $cod, $quantity) {
$webService = new PrestaShopWebservice($this->ps_shop_path, $this->ps_ws_auth_key, $this->ps_ws_debug);
$xml = $webService->get(array('url' => $root_path . '/api/products?schema=blank'));
$resources = $xml->children()->children();
/*
many values of attributes of XML object $resources are assigned here, instead of this comment
*/
$id = "";
try {
$opt = array('resource' => 'products');
if(!$update){
$opt['postXml'] = $xml -> asXML();
$xml = $webService -> add($opt);
$id = $xml->product->id;
}
else{
$opt['putXml'] = $xml -> asXML();
$opt['id'] = $n_id;
$xml = $webService -> edit($opt);
$id = $n_id;
}
}
catch (PrestaShopWebserviceException $ex) {
echo '<b>Error : '.$ex->getMessage().'</b>';
}
$resources = $xml->children()->children();
$stock_available_id = $resources->associations->stock_availables->stock_available[0]->id;
/*
Here we get the sotck available with were product id
*/
try
{
$opt = array('resource' => 'stock_availables');
$opt['id'] = $stock_available_id;
$xml = $webService->get($opt);
}
catch (PrestaShopWebserviceException $e)
{
$trace = $e->getTrace();
if ($trace[0]['args'][0] == 404) die('1:Bad ID');
else if ($trace[0]['args'][0] == 401) die('1:Bad auth key');
else die('1:Other error '.$e->getMessage());
}
$resources = $xml->children()->children();
$resources->quantity = $quantity;
/*
There we call to save our stock quantity.
*/
try
{
$opt = array('resource' => 'stock_availables');
$opt['putXml'] = $xml->asXML();
$opt['id'] = $stock_available_id;
$xml = $webService->edit($opt);
echo "Successfully updated.";
}
catch (PrestaShopWebserviceException $e)
{
$trace = $e->getTrace();
if ($trace[0]['args'][0] == 404) die('2:Bad ID');
else if ($trace[0]['args'][0] == 401) die('2:Bad auth key');
else echo('Other error: '.$e->getMessage()); // function echoes this PrestaShopWebServiceException: "Other error: This call to PrestaShop Web Services returned an unexpected HTTP status of:503"
}
}
PUT request are closed by default in most of hosting. Did you check this with your hosting manager??
Anyway, you must activate Prestashop DEBUG MODE in order to know the exact reason of your error (after you solve this of course).
Good luck.

Mailchimp PHP api v.2, User already exists or unsubscribe returns error

I'm using the Mailchimp v.2 API PHP wrapper to handle subscriptions... https://bitbucket.org/mailchimp/mailchimp-api-php however if a subscriber already exists on the list or the subscriber was unsubscribed, it returns an error, and I want to know a way I can code this to where if either of those cases exist, it will continue running the code without displaying an error. I apologize if this is a simple question.
$api_key = "XXXXXXXXX";
$list_id = "XXXXXX";
require('Mailchimp.php');
$Mailchimp = new Mailchimp( $api_key );
$Mailchimp_Lists = new Mailchimp_Lists( $Mailchimp );
$merge_vars = array('FNAME'=>htmlentities($_POST['stripeFirstName']), 'LNAME'=>htmlentities($_POST['stripeLastName']) );
$subscriber = $Mailchimp_Lists->subscribe( $list_id, array( 'email' => htmlentities($_POST['stripeEmail']) ), $merge_vars );
You'll want to make use of try and catch. Mailchimp is pretty verbose about what goes wrong.
try {
$result = $Mailchimp_Lists->subscribe(
$list_id,
array(/* ... */), // primary subscriber data
array(/* ... */), // merge fields
'html', // email-type preference
false // double-opt-in
);
// Action for successful subscribe attempt.
} catch (\Exception $e) {
if ($e instanceof \Mailchimp_List_AlreadySubscribed) {
// In case they are already subscribed:
$errors[] = $e->getMessage();
} else {
// In case something else went wrong.
$errors[] = 'There was an error adding your email to the list. Would you mind trying again?';
}
// Debug time!
var_dump($errors);
}

(403) The user is not enabled for live streaming

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!

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
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);
}

Categories