How to tag photos in facebook-api? - facebook

I wanted to ask if/how is it possible to tag a photo using the FB API (Graph or REST).
I've managed to create an album and also to upload a photo in it, but I stuck on tagging.
I've got the permissions and the correct session key.
My code until now:
try {
$uid = $facebook->getUser();
$me = $facebook->api('/me');
$token = $session['access_token'];//here I get the token from the $session array
$album_id = $album[0];
//upload photo
$file= 'images/hand.jpg';
$args = array(
'message' => 'Photo from application',
);
$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));
$search = array('{"id":', "}");
$delete = array("", "");
// picture id call with $picture
$picture = str_replace($search, $delete, $data);
//here should be the photos.addTag, but i don't know how to solve this
//above code works, below i don't know what is the error / what's missing
$json = 'https://api.facebook.com/method/photos.addTag?pid='.urlencode($picture).'&tag_text=Test&x=50&y=50&access_token='.urlencode($token);
$ch = curl_init();
$url = $json;
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_exec($ch);
} catch(FacebookApiException $e){
echo "Error:" . print_r($e, true);
}
I really searched a long time, if you know something that might help me, please post it here :)
Thanks for all your help,
Camillo

Hey,
you can tag the Picture directly on the Upload with the GRAPH API,
see the example below:
This Method creates an array for the tag information, in this examples the method becomes an array with Facebook user Ids:
private function makeTagArray($userId) {
foreach($userId as $id) {
$tags[] = array('tag_uid'=>$id, 'x'=>$x,'y'=>$y);
$x+=10;
$y+=10;
}
$tags = json_encode($tags);
return $tags;
}
Here are the arguments for the call of the GRAPH API to upload an picture:
$arguments = array(
'message' => 'The Comment on this Picture',
'tags'=>$this->makeTagArray($this->getRandomFriends($userId)),
'source' => '#' .realpath( BASEPATH . '/tmp/'.$imageName),
);
And here is the Method for the GRAPH API call:
public function uploadPhoto($albId,$arguments) {
//https://graph.facebook.com/me/photos
try {
$fbUpload = $this->facebook->api('/'.$albId.'/photos?access_token='.$this->facebook->getAccessToken(),'post', $arguments);
return $fbUpload;
}catch(FacebookApiException $e) {
$e;
// var_dump($e);
return false;
}
}
The argument $albId contains an ID from an Facebook Album.
And if you want to Tag an existing Picture from an Album you can user this Method:
At First we need the correct picture ID from the REST API, In this example we need the Name from an Album wich the Application has create or the user wich uses this Application.
The Method returns The Picture ID From the last Uploaded Picture of this Album:
public function getRestPhotoId($userId,$albumName) {
try {
$arguments = array('method'=>'photos.getAlbums',
'uid'=>$userId
);
$fbLikes = $this->facebook->api($arguments);
foreach($fbLikes as $album) {
if($album['name'] == $albumName) {
$myAlbId = $album['aid'];
}
}
if(!isset($myAlbId))
return FALSE;
$arguments = array('method'=>'photos.get',
'aid'=>$myAlbId
);
$fbLikes = $this->facebook->api($arguments);
$anz = count($fbLikes);
var_dump($anz,$fbLikes[$anz-1]['pid']);
if(isset($fbLikes[$anz-1]['pid']))
return $fbLikes[$anz-1]['pid'];
else
return FALSE;
//var_dump($fbLikes[$anz-1]['pid']);
//return $fbLikes;
}catch(FacebookApiException $e) {
$e;
// var_dump($e);
return false;
}
}
Now you have the correct picture ID From the REST API and you can make your REST API CALL to tag this Picture $pid is the Picture from the Method getRestPhotoId and $tag_uid is an Facebook userId:
$json = 'https://api.facebook.com/method/photos.addTag?pid='.$pid.'&tag_uid='.$userId.'&x=50&y=50&access_token='.$this->facebook->getAccessToken();
$ch = curl_init();
$url = $json;
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_GET, true);
$data = curl_exec($ch);
And this line is very important:
curl_setopt($ch, CURLOPT_GET, true);
you must youse CUROPT_GET instead of CUROPT_POST to add a Tag throw the REST API.
I Hope this helps you.
Best wishes Kay from Stuttart

Photo id is unique for every user and looks like two numbers joined by underscore in the middle.
Getting this id is a bit tricky.
You can get it by running FQL on photo table but you need to provide album id which is also user unique. You can get album id from album table but you need to provide owner userid.
For example we have CocaCola user with userid 40796308305. To get photo ids from this user we can run FQL:
SELECT pid FROM photo WHERE aid IN ( SELECT aid FROM album WHERE owner="40796308305")
(you can run it in a test console on this page)
This would return our photo ids:
[
{
"pid": "40796308305_2298049"
},
{
"pid": "40796308305_1504673"
},
{
"pid": "40796308305_2011591"
},
...
]
I didn't work with photos much, maybe you don't have to go through all this process to get photo id, it might be some simple algorithm like <OWNER_ID>_<PHOTO_ID>. But try to get your photo id from FQL and see if tagging would work. If it does maybe you will be able to skip FQL part and build photo id from existing data you have.
Hopefully this helps.

I found out the problem, the problem is that when you use curl to send the array the post function will not send the array correctly, it was sending just "Array" that it was why the graph API complained about tags being an array. To solve that I did the following:
$data = array(array('tag_uid' => $taguser,
'x' => rand() % 100,
'y' => rand() % 100
));
$data = json_encode($data);
$photo_details = array(
'message'=> $fnames,
'tags' => $data
);
Now I just send using curl
curl_setopt($ch, CURLOPT_POSTFIELDS, $photo_details);

Related

How can I get product list with its detail in rest API backend is magento2

I'm working on native mobile application backend is magento2 and I want to display product after customer selected a category. I am able to get list of the product by category in rest request but that list don't have much details about the product.
Request : http://localhost/magento2/index.php/rest/V1/categories/24/products
(24 is category ID)
Response : [{"sku":"WH01","position":1,"category_id":"24"},...]
Earlier in Magento 1.9 product list was something like
{
2: {
entity_id: "2"
type_id: "simple"
sku: "Levis Bagpack"
description: "Bagpack"
short_description: "Bagpack"
meta_keyword: null
name: "Levis Bagpack"
meta_title: null
meta_description: null
regular_price_with_tax: 45
regular_price_without_tax: 45
final_price_with_tax: 45
final_price_without_tax: 45
is_saleable: true
image_url: "http://172.16.8.24:8080/magento/media/catalog/product/cache/0/image/9df78eab33525d08d6e5fb8d27136e95/images/catalog/product/placeholder/image.jpg"
}
What should I do to get more info about product so I can show image and other things in mobile app ?
Maybe you can try the GET /V1/products/:sku REST API to get all the details.
Link
The returned value will be a representation of \Magento\Catalog\Api\Data\ProductInterface (including the additional attributes)
Link for Reference
Check \Magento\Catalog\Api\ProductRepositoryInterface::get which services the GET /V1/products/:sku REST API.
You can make multiple requests for all product SKUs.
OR
You can use the search API to fetch the entire list in a single request based on your criteria:
For example:
http://localhost/magento2/index.php/rest/V1/products?searchCriteria[filter_groups][0][filters][0][field]=sku&searchCriteria[filter_groups][0][filters][0][value]=simple&searchCriteria[filter_groups][0][filters][1][field]=sku&searchCriteria[filter_groups][0][filters][1][value]=Simple2&searchCriteria[filter_groups][0][filters][0][condition_type]=eq&searchCriteria[current_page]=1&searchCriteria[page_size]=2
In the case of products with SKUs - simple and Simple2 are being searched.
define('BASEURL','http://localhost/magento20_0407/');
$apiUser = 'testUser';
$apiPass = 'admin123';
$apiUrl = BASEURL.'index.php/rest/V1/integration/admin/token';
/*
Magento 2 REST API Authentication
*/
$data = array("username" => $apiUser, "password" => $apiPass);
$data_string = json_encode($data);
try{
$ch = curl_init($apiUrl);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$token = curl_exec($ch);
$token = json_decode($token);
if(isset($token->message)){
echo $token->message;
}else{
$key = $token;
}
}catch(Exception $e){
echo 'Error: '.$e->getMessage();
}
/*
Get Product By SKU REST API Magento 2
Use above key into header
*/
$headers = array("Authorization: Bearer $key");
//$requestUrl = BASEURL.'index.php/rest/V1/products/24-MB01';//24-MB01 is the sku.
//$requestUrl = BASEURL.'index.php/rest/V1/products?searchCriteria[page_size]=10';// get total 10 products
//$requestUrl = BASEURL.'index.php/rest/V1/categories/24/products';// 24 category id
$requestUrl = BASEURL.'index.php/rest/V1/products?searchCriteria=';//get all products
$ch = curl_init();
try{
$ch = curl_init($requestUrl);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
$result = json_decode($result);
if(isset($result->message)){
echo $result->message;
}else{
print_r($result);
}
}catch(Exception $e){
echo 'Error: '.$e->getMessage();
}
Similarly you can change $requestUrl and filter product list by category id and get product detail.
Please confirm whether it solves your problem or not. Else I'll post another solution.
You can try this, where '30' is category id. http://magentohost.com/rest/default/V1/products?searchCriteria[filter_groups][0][filters][0][field]=category_id&%20searchCriteria[filter_groups][0][filters][0][value]=30&%20searchCriteria[filter_groups][0][filters][0][condition_type]=eq&searchCriteria[pageSize]=10
Please try to use this endpoint instead of your endpoint:
/V1/products?searchCriteria[filter_groups][0][filters][0][field]=category_id&searchCriteria[filter_groups][0][filters][0][value]=24&searchCriteria[filter_groups][0][filters][0][condition_type]=eq
It is the same as #Alexander Timonchev, But you have to remove the space after &

How to post to my facebook wall from my own adminpages(CMS)?

How can I post a ordinary post to my facebook wall from my administration pages where I upload content to my webpage?
So I upload content to my webpage from my CMS and next to where I display my uploaded content in my adminpages I would like to have a button that can publish that post to my facebook wall. As an ordinary post and not like a LIKE post or Comment post!
First you need to create an facebook app.
Then you will get an app id and a secret key.
Using this details you can do post into ur wall using facebook php library
or u can use the following function
<?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
}
?>
For details
follow How to post wall in facebook using API in PHP?
function postonwall(){
// showLoader(true);
FB.api('/me/feed', 'post',
{
message : "testtext.",
link : 'http://www.mydomain.se',
picture : 'http://www.mydomain.se/image.jpg',
name : 'iOS Apps & Games',
description : 'Checkout iOS apps and games from iThinkdiff.net. I found some of them are just awesome!'
},
function(response) {
// showLoader(false);
if (!response || response.error) {
alert('Error occured');
} else {
//alert('Post ID: ' + response.id);
alert('Success: Content Published');
}
});
}

How to submit form to a page on another server with some type of ajax?

I would like to submit my form to another page but making it not go to that page (like AJAX, but I know that AJAX does not work across domains)
Do you guys know how to do this? I don't like submitting it to the page on the other site because it is just really a slower and crappier way of doing things.
Thanks,
Nathan Johnson
Submit your form to a local page via AJAX. From that page you can post the data to the remote site with e.g. cURL.
Here's a very abstract example:
page_with_form.php
<form id="form1">
//input fields
</form>
<script>
$.post('post_to_remote.php', $('#form1').serialize(), function(){
//do something when finished
return false; //prevent from reloading
});
</script>
post_to_remote.php
$param1 = $_POST['param1'];
$param2 = $_POST['param2'];
$remoteUrl = 'http://www.remote_site.com/page_to_post_to.php';
$postFields = array('param1' => $param1, 'param2' => $param2);
//if you don't want to do any sanitizing, you can also simply do this:
//$postFields = $_POST;
$data_from_remote_page = $getUrl($remoteUrl, 'post', $postFileds);
function getUrl($url, $method='', $vars='') {
$ch = curl_init();
if ($method == 'post') {
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $vars);
}
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookies.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookies.txt');
$buffer = curl_exec($ch);
curl_close($ch);
return $buffer;
}
If you do not need the full power of curl and it's really just a simple post, you can also use native PHP functions:
$postFields = http_build_query($_POST);
$remoteUrl = 'http://www.remote_site.com/page_to_post_to.php';
$context = stream_context_create(
array(
'http' => array(
'method' => 'POST',
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'content' => $postFields,
'timeout' => 10,
),
)
);
$result = file_get_contents($remoteURL, false, $context);
A vary basic example, but you get the idea.
You can try using JSONP:
http://davidwalsh.name/jsonp
http://api.jquery.com/jQuery.getJSON/#jsonp
It can be used cross-domain, but the data you send back from the server has to be something like (PHP):
echo $_GET['callback']."(".json_encode($data).")";
When I first used it I didn't echoed the callback function's name and it took me a couple of hours to see why it wasn't working.
Good luck!
Try jsonp in javascript:
$.ajax({
url: 'some_url' ,
data: $('#form_id').serialize(),
dataType: "jsonp",
jsonp : "callback",
jsonpCallback: "jsonpcallbask"
});
function jsonpcallbask(data) {
//handle response here
}

User must have accepted TOS - Facebook Graph API error when posting photos to group page

I've been struggling to upload an image from the user's computer and posted to our group page using the Facebook Graph API. I was able to send a post request to facebook with the image however, I'm getting this error back: ERROR: (#200) User must have accepted TOS. To some extent, I don't believe that I need the user to authorize himself as the photo is being uploaded to our group page. This below, is the code i'm using:
if($albumId != null) {
$args = array(
'message' => $description
);
$args[basename($photoPath)] = '#' . realpath($photoPath);
$ch = curl_init();
$url = 'https://graph.facebook.com/'.$albumId.'/photos?'.$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);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$data = curl_exec($ch);
$photoId = json_decode($data, true);
if(isset($photoId['error'])) die('ERROR: '.$photoId['error']['message']);
$temp = explode('.', sprintf('%f', $photoId['id']));
$photoId = $temp[0];
return $photoId;
}
Can somebody tell me if I need to request extra permissions from the user or what i'm doing wrong?
Thanks very much!
Actually, I never succeeded in this :(. As a work around, we created a new facebook user instead of a group page.
This is a known bug and it looks like they're working on it:
http://bugs.developers.facebook.net/show_bug.cgi?id=11254

Add a wall post to a page or application wall as page or application with facebook graph API

I wan't to create a new wall post on a appliaction page or a "normal" page with the facebook graph API. Is there a way to "post as page"? With the old REST-API it worked like this:
$facebook->api_client->stream_publish($message, NULL, $links, $targetPageId, $asPageId);
So, if I passed equal IDs for $targetPageId and $asPageId I was able to post a "real" wall post not caused by my own facebook account.
Thanks!
$result = $facebook->api("/me/accounts");
foreach($result["data"] as $page) {
if($page["id"] == $page_id) {
$page_access_token = $page["access_token"];
break;
}
}
$args = array(
'access_token' => $page_access_token,
'message' => "I'm posting as a Page!"
);
$post_id = $facebook->api("/$page_id/feed","post",$args);
To publish as Page you need to add manage_pages permission first of all (and get the tokens).
Next use something like this:
$url = 'https://api.facebook.com/method/stream.publish?message=TEST&target_id=PAGEID&uid=PAGEID&access_token=YOUR_TOKEN';
$ch = curl_init();
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, "");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0);
curl_setopt($ch, CURLOPT_URL, $url);
$result = curl_exec($ch);
curl_close($ch);
Set the value of targetpageid=null and check the output...