I'm trying to create an app that will upload & publish a video to user's wall.
following the api docs there are no examples of publishing
https://developers.facebook.com/…/reference/v2.2/user/videos
I've looked up for similar questions in here but they're all old referring to fb api.
the API returns a message that I should use curl, when I'm using curl
it returns false.
is there any php example of publishing video?
example of my code:
$url = 'https://graph-video.facebook.com/me/videos';
$cfile = new CURLFile('test.mp4','video/mp4','video');
$post_params = array(
'title' => "myTitle",
'name' => "blahblah",
'source' => $cfile,
'access_token' => $token
);
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type: multipart/form-data"));
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_params);
//execute post
$result = curl_exec($ch);
Thanks!
I found the answer for that using FB API & CURLFile, hope it would help someone else
$url = 'https://graph-video.facebook.com/me/videos';
$cfile = new CURLFile(realpath('test.flv'),'video/x-flv');
$movie_data = array('file' => $cfile);
$post_params = array(
'title' => "ffff",
'name' => "tablished businesses”",
'source' => $cfile,
'access_token' => $token
);
$request = new FacebookRequest(
$session,
'POST',
'/me/videos',
$post_params
);
$response = $request->execute();
the $response contains the id of the video.
enjoy
Related
I want to make php app to create post on wordpress.com using REST api.
I use this code:
<?php
$curl = curl_init( 'https://public-api.wordpress.com/oauth2/token' );
curl_setopt( $curl, CURLOPT_POST, true );
curl_setopt( $curl, CURLOPT_POSTFIELDS, array(
'client_id' => 12345,
'redirect_uri' => 'http://example.com/wp/test.php',
'client_secret' => 'L8RvNFqyzvqh25P726jl0XxSLGBOlVWDaxxxxxcxxxxxxx',
'code' => $_GET['code'], // The code fromthe previous request
'grant_type' => 'authorization_code'
) );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1);
$auth = curl_exec( $curl );
$secret = json_decode($auth);
$access_token = $secret->access_token;
$post = array(
'title'=>'Hello World',
'content'=>'Hello. I am a test post. I was created by
the API',
'date'=>date('YmdHis'),
'categories'=>'API','tags=tests'
);
$post = http_build_query($post);
$apicall = "https://public-api.wordpress.com/rest/v1/sites/mysite.wordpress.com/posts/new";
$ch = curl_init($apicall);
curl_setopt($ch, CURLOPT_HTTPHEADER, array
('authorization: Bearer ' . $access_token,"Content-Type: application/x-www-form-urlencoded;
charset=utf-8"));
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
$return = curl_exec($ch);
echo "<pre>";
print_r($return);
exit;
?>
but I get this error:
{"error":"unauthorized","message":"User cannot publish posts"}
Can help me?
Thanks
Standard way to create posts is to use cookies and nonce.
However I found a more easy way to do it.
Install Basic-Auth plugin to your wordpress.
Create wordpress user with username admin and password admin (both credentials are insecure, used for demonstration purposes only)
Create post using code:
$username = 'admin';
$password = 'admin';
$rest_api_url = "http://my-wordpress-site.com/wp-json/wp/v2/posts";
$data_string = json_encode([
'title' => 'My title',
'content' => 'My content',
'status' => 'publish',
]);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $rest_api_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string),
'Authorization: Basic ' . base64_encode($username . ':' . $password),
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
if ($result) {
// ...
} else {
// ...
}
Note that in example above version 2 of REST API is used.
The answer is right that we can use the "Basic-Auth" plugin to make a Rest API request.
But, #vallez want to create a post on wordpress.com website.
And wordpress.com provide the oAuth support for authentication.
Recently I have created a post which demostrate about using the oAuth to create a post on wordpress.com. You can read the article at create the post on wordpress.com site using oAuth and Rest API
Below are the steps to successfully create a post with oAuth on wordpress.com.
Step 1: Add authentication details to get auth key.
$auth_args = array(
'username' => '',
'password' => '',
'client_id' => '',
'client_secret' => '',
'grant_type' => 'password', // Keep this as it is.
);
$access_key = get_access_key( $auth_args );
Below is the function get_access_key() which return the access key.
Step 2: Get Access Key.
/**
* Get Access Key.
*
* #param array $args Auth arguments.
* #return mixed Auth response.
*/
function get_access_key( $args ) {
// Access Token.
$curl = curl_init( 'https://public-api.wordpress.com/oauth2/token' );
curl_setopt( $curl, CURLOPT_POST, true );
curl_setopt( $curl, CURLOPT_POSTFIELDS, $args );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1);
$auth = curl_exec( $curl );
$auth = json_decode($auth);
// Access Key.
return $auth->access_token;
}
Step 3: Set post arguments and pass it create the post.
$post_args = array(
'title' => 'Test Post with oAuth',
'content' => 'Test post content goes here..',
'tags' => 'tests',
'post_status' => 'draft',
'categories' => 'API',
);
Step 4: Create a post with the access key.
Now, We have access key and the create post arguments. So, Lets pass them to function create_post().
create_post( $access_key, $post_args );
Step 5: Create a post with access key.
/**
* Create post with access key.
*
* #param string $access_key Access key.
* #param array $post_args Post arguments.
* #return mixed Post response.
*/
function create_post( $access_key, $post_args )
{
$options = array (
'http' => array(
'ignore_errors' => true,
'method' => 'POST',
'header' => array(
0 => 'authorization: Bearer ' . $access_key,
1 => 'Content-Type: application/x-www-form-urlencoded',
),
'content' => http_build_query( $post_args ),
),
);
$context = stream_context_create( $options );
$response = file_get_contents(
'https://public-api.wordpress.com/rest/v1/sites/YOURSITEID/posts/new/',
false,
$context
);
return json_decode( $response );
}
I am developing an Instagram application. Nevermind, my questions isn't focused on the API.
Its a simple php question. However. Everytime I try to run the the output is that the TOKEN is empty.
$token = 'XxXXXXXXXXX.XXXXXXX.XXXXXX';
$access_token_parameters = array(
'access_token' => $token,
'action' => 'like'
);
$curl = curl_init($url);
curl_setopt($curl,CURLOPT_GET,true);
curl_setopt($curl,CURLOPT_GETFIELDS,$access_token_parameters);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
echo curl_exec($curl);
}
Is there a way to set a value externally the Array? (Between, I tried it with include file.php. which works.) But I would like to call this without using an external php file.
Hope you understand my problem and may help me :)
$token = 'XxXXXXXXXXX.XXXXXXX.XXXXXX';
$access_token_parameters = array(
'access_token' => $token,
'action' => 'like'
);
$curl = curl_init($url."?".http_build_query($access_token_parameters ));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
echo curl_exec($curl);
}
My site used to automatically submit all user generated artwork to a tumblr blog using the code below. Tumblr have now changed their api to v2. Any help on updating the block of code as below to work with the new version of the api would be greatly received. Thanks.
//submit to tumblr blog
// Authorization info
$tumblr_email = 'XXXXXXXXXX#drawaplanet.com';
$tumblr_password = 'XXXXXXXXXXX';
$post_type = 'photo';
$caption = $userCaption;
$post_title = '';
$post_body = '';
$source = 'http://www.drawaplanet.com/drawaplanet/gallery/' . $filename;
$click_through_url = 'http://www.drawaplanet.com/planet.php?s=' . $source;
// Prepare POST request
$request_data = http_build_query(
array(
'email' => $tumblr_email,
'password' => $tumblr_password,
'type' => $post_type,
'caption' => $caption,
'title' => $post_title,
'body' => $post_body,
'source' => $source,
'click-through-url' => $click_through_url,
'generator' => 'DRAWAPLANET'
)
);
// Send the POST request (with cURL)
$c = curl_init('http://www.tumblr.com/api/write');
curl_setopt($c, CURLOPT_POST, true);
curl_setopt($c, CURLOPT_POSTFIELDS, $request_data);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($c);
$status = curl_getinfo($c, CURLINFO_HTTP_CODE);
curl_close($c);
I am using facebook-php-sdk and my requirement is to post a story to the user's wall. My app requests the user for 'publish_stream' permission at the time of signup/login. After user has allowed the permission and logged in, somehow I am not able to publish to facebook wall a new comment created by the user on my app. This is the error I get:
Invalid OAuth access token signature
This is what I do:
$facebook = new Facebook(array(
'appId' => "$fb_app_id",
'secret' => "$fb_secret",
'cookie' => true
));
try {
$fb_user_id = $facebook->getUser();
$access_token = $facebook->getAccessToken();
$facebook->api("/me/feed", 'post', array(
'access_token' => $access_token,
'message' => 'I love SO',
'link' => 'http://mydomain.com',
'picture' => 'http://thinkdiff.net/ithinkdiff.png',
'name' => 'iOS Apps & Games',
'description'=> 'Checkout iOS apps and games from iThinkdiff.net. I found some of them are just awesome!'
)
);
} catch (FacebookApiException $e) {
echo '<pre>'.htmlspecialchars(print_r($e, true)).'</pre>';
}
Do share your thoughts please
You can use the following code to post into facebook wall , just call the function with proper arguments
Try this ,
<?php
function doWallPost($postName='',$postMessage='',$postLink='',$postCaption='',$postDescription='')
{
$FB_APP_ID='xxxxxxxxxxxxxxxxxxxxxxxx';
$FB_APP_SECRET='xxxxxxxxxxxxxxxxxxxxxxxxxxx';
$APP_RETURN_URL=((substr($_SERVER['SERVER_PROTOCOL'],0,4)=="HTTP")?"http://":"https://").$_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME'];
$code = $_REQUEST["code"];
if(empty($code))
{
$dialog_url = "http://www.facebook.com/dialog/oauth?client_id=".$FB_APP_ID."&redirect_uri=".$APP_RETURN_URL."&scope=publish_stream";
header("Location:$dialog_url");
}
$token_url = "https://graph.facebook.com/oauth/access_token?client_id=".$FB_APP_ID."&redirect_uri=".urlencode($APP_RETURN_URL)."&client_secret=".$FB_APP_SECRET."&code=".$code;
$access_token = file_get_contents($token_url);
$param1=explode("&",$access_token);
$param2=explode("=",$param1[0]);
$FB_ACCESS_TOKEN=$param2[1];
$url = "https://graph.facebook.com/me/feed";
$attachment = array( 'access_token' => $FB_ACCESS_TOKEN,
'name' => $postName,
'link' => $postLink,
'description' => $postDescription,
'message' => $postMessage,
'caption' => $postCaption,
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT,2);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $attachment);
$result=curl_exec($ch);
header('Content-type:text/html');
curl_close($ch);
return $result
}
?>
install app again through https://developers.facebook.com/tools/explorer/
select your app & click on Get access token
if you still have problem go to your developer dashboard
https://developers.facebook.com/apps
click on Edit settings & check up you set correct URL
in Site URL: field
I'm trying to implement Google's OAuth 2.0 authentication for a web server application.
I can obtain the code from Google ok, but when I post this back to try and get an access token, it always give me the error "Required parameter is missing: grant_type. Error 400" even though the grant_type is there.
Also if I specify the content-length to be anything other than 0, it throws other errors.
Here's the code that's doing this curl post:
$url = 'https://accounts.google.com/o/oauth2/token';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FAILONERROR, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/x-www-form-urlencoded',
'Content-length: 0'
));
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'code='. urlencode($code),
'client_id=' . urlencode($clientID),
'client_secret=' . urlencode($clientSecret),
'redirect_uri=http%3A%2F%2Flocalhost%2Fexperiments%2FnewGALogin.php',
'grant_type=authorization_code'
));
try
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'code' => $code,
'client_id' => $clientID,
'client_secret' => $clientSecret,
'redirect_uri' => 'http%3A%2F%2Flocalhost%2Fexperiments%2FnewGALogin.php',
'grant_type' => 'authorization_code'
));
or
curl_setopt($ch, CURLOPT_POSTFIELDS,
'code=' . urlencode($code) . '&' .
'client_id=' . urlencode($clientID) . '&' .
'client_secret=' . urlencode($clientSecret) . '&' .
'redirect_uri=http%3A%2F%2Flocalhost%2Fexperiments%2FnewGALogin.php' . '&' .
'grant_type=authorization_code'
);
I was trying to use the PHP code in the original question plus answers provided here and kept getting complaints from the Google token server about a missing "grant_type", even though it was definitely being passed in. It turns out the issue was the CURLOPT_HTTPHEADER didn't like/need the 'Content-length: 0'. Hopefully this complete working code will save someone else the same headache...
// This is what Google's OAUTH server sends to you
$code = $_GET['code'];
// These come from your client_secret.json file
$clientID = "your client id.apps.googleusercontent.com";
$clientSecret = "your client secret";
$redirectURI = "your redirect URI";
$token_uri = 'https://accounts.google.com/o/oauth2/token';
$ch = curl_init($token_uri);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FAILONERROR, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/x-www-form-urlencoded'
));
// Build the URLEncoded post data
$postFields = http_build_query(array(
'client_secret' => $clientSecret,
'grant_type' => 'authorization_code',
'redirect_uri' => $redirectURI,
'client_id' => $clientID,
'code' => $code
));
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
$response = curl_exec($ch);
// Save response, especially the "refresh_token"
$pathToAccessToken = "/your/path/to/access_token.json";
file_put_contents($pathToAccessToken, $response);
FYI, the response JSON looks something like this:
{
"access_token" : "xxxWhateverGibberish",
"token_type" : "Bearer",
"expires_in" : 3600,
"refresh_token" : "yyyMoreGibberish"
}
After that I could successfully query the Calendar (the API scope my original OAuth request called for) using code like the following:
function getClient() {
$client = new Google_Client();
$client->setApplicationName(APPLICATION_NAME);
$client->setScopes(SCOPES);
$client->setAuthConfigFile(CLIENT_SECRET_PATH);
$client->setAccessType('offline');
// Load previously authorized credentials from a file.
$pathToAccessToken = "/your/path/to/access_token.json";
$accessToken = file_get_contents($pathToAccessToken);
$client->setAccessToken($accessToken);
// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->refreshToken($client->getRefreshToken());
file_put_contents($pathToAccessToken, $client->getAccessToken());
}
return $client;
}
$client = getClient();
$service = new Google_Service_Calendar($client);
// Print the next 10 events on the user's calendar.
$calendarId = 'primary';
$optParams = array(
'maxResults' => 10,
'orderBy' => 'startTime',
'singleEvents' => TRUE,
'timeMin' => date('c'),
);
$results = $service->events->listEvents($calendarId, $optParams);
if (count($results->getItems()) == 0) {
print "No upcoming events found.\n";
} else {
print "Upcoming events:\n";
foreach ($results->getItems() as $event) {
$start = $event->start->dateTime;
if (empty($start)) {
$start = $event->start->date;
}
printf("%s (%s)\n", $event->getSummary(), $start);
}
}
After researching into this problem, it seems like the grant_type is not accepted in the array format. (Yes, the query string method works but it's messy to build.)
Adding http_build_query() to the array works if you are keen on keeping the POST fields in an array.
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array(
'code' => $code,
'client_id' => $clientID,
'client_secret' => $clientSecret,
'redirect_uri' => 'http%3A%2F%2Flocalhost%2Fexperiments%2FnewGALogin.php',
'grant_type' => 'authorization_code'
)));
Please read the documentation for CURLOPT_POSTFIELDS carefully:
... as an array with the field name as key and field data as value
You do just something but not that. Try:
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'code' => $code,
'client_id' => $clientID,
...
You don't need to urlencode in this case.
I didn't want to believe it, but strangely enough, simply switching from CURLOPT_POSTFIELDS from an array to a '&' concatenated string (with the same data!) let my OAuth server finally recognize the grant_type.
The core issue with the original question and some of the answers is the different values accepted in the curl_setopt call when using the key CURLOPT_POSTFIELDS.
When the input is an array the resulting Content-Type will be multipart/form-data which is not compliant with the OAuth 2.0 spec and the server will ignore it. When the input is a query-encoded string (e.g built using http_build_query) the Content-Type: will be application/x-www-form-urlencoded, which is what the spec requires.
See the "Notes" section at: http://php.net/manual/en/function.curl-setopt.php