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

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 &

Related

Paypal GetUserinfo (Identity) only returning user_id

I am using PHP to get user information from paypal identity API, but unfortunately i only get user_id in response. I need email and payer_id in response. I have read the documentation , according to that i am supposed to receive multiple parameters in response, but i am receiving only user_id. I have enabled all the scopes in App permissions. here is the documentation getuserinfo.
here is my code to get user info (I am passing $access_token into this function). I am using sandbox credentials.
$api_url = 'https://api.sandbox.paypal.com/v1/oauth2/token/userinfo?schema=openid';//sandbox
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $api_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer '. $access_token, 'Content-Type: application/json'));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$data = json_decode(curl_exec($ch), true);
//dd($data);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if($http_code == 200)
return $data;
else if($http_code == 404)
return false;
else
return false;
my response :
array:1 [▼ "user_id" => "https://www.paypal.com/webapps/auth/identity/user/HdoaS1nMgR_Ltt5mBTv4mRvC9P1wUrWt2NlOVH2e_3w"]
This is most likely your issue: "The attributes returned depend on the scopes configured for the REST app"
https://developer.paypal.com/docs/integration/paypal-here/sandbox-testing/configuring-accounts/#create-a-rest-application
Log In with PayPal. When you enable Log In with PayPal, click Advanced Options and select Personal Information and Address Information, which are disabled by default.

Connect Yii2 to another RESTful application

I have a Yii2 application. I would like to connect it to another restful webpage. So user will send data to my application, I will send them via POST request and do something according to a JSON response. How can I do the send a request / fetch response part in a yii2?
The best method would be to use curl to make end to end calls to your RESTful API, in which case you may be interested in checking out a yii2 extension for curl.
Without a Yii2 extension, we can accomplish this by creating a more general function in a controller or more preferably a model (for shared access) as exampled below:
/**
* $method e.g POST, GET, PUT
* $data = [
'param' => 'value',
]
*/
public function curlToRestApi($method, $url, $data = null)
{
$curl = curl_init();
// switch $method
switch ($method) {
case 'POST':
curl_setopt($curl, CURLOPT_POST, 1);
if($data !== null) {
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
break;
// logic for other methods of interest
// .
// .
// .
default:
if ($data !== null){
$url = sprintf("%s?%s", $url, http_build_query($data));
}
}
// Authentication [Optional]
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, "username:password");
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
curl_close($curl);
return $result;
}
We then call this function on a need basis i.e. depending on the method and url and/or data.
It is also conveniently easy to use file_get_contents if fopen wrapper is enabled in order to access Web Service URLs.
$response = file_get_contents('http://example.com/path/to/api?param1=stack&param2=overflow');
If a JSON response is served, you can recover the php array as follows:
$response = json_decode($response, TRUE);
If an XML response is returned, then
$response = new \SimpleXMLElement($response);
However, if the API endpoint returns an HTTP error status, the file_get_contents function fails with a warning and returns null.

How to get Paypal transaction Id after getting paykey in paypal integration in iphone?

I am going to implement paypal in my iphone native app. But I am facig an issue in that.
I want to get my transaction Id regarding my PayKey. There is a direct method to get pay key in PayPal library to get PayKey but not a method to get transactionId.
Here is that method:
-(void)paymentSuccessWithKey:(NSString *)payKey andStatus:(PayPalPaymentStatus)paymentStatus;
As I am thinking IPN(Instant Payment Notification ) can help to resolve this issue but I don't know how to implement that one in my app?
Please help me to resolve this issue.
Thanks,
Chandra Prakash
Fianlly I have got solution of my question.
I have got transaction Id using IPN.
When I selected ENABLE IPN Option from my PayPal account then all details send by paypal I have received on URL which I given from there I have got all required fields.
Here are a few links to help you
IPN Overview:
https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/howto_html_instantpaymentnotif
IPN Documentation:
https://cms.paypal.com/cms_content/US/en_US/files/developer/IPNGuide.pdf
IPN Variables:
https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_html_IPNandPDTVariables
IPN Script Example:
https://cms.paypal.com/us/cgi-bin/?&cmd=_render-content&content_ID=developer/e_howto_admin_IPNImplementation
IPN Script Generator:
https://www.paypaltech.com/SG2/
Thanks,
Cp
I had a similar issue but was unable to rely on IPN so I thought I would share another method.
you don't need to use IPN, you can get the transaction ID with the payKey, which is useful for verifying mobile payments. Here is a php block that will get all of the transaction information from a payKey. You'll need to call it from your mobile app. For iOS you could use this tutorial: http://www.raywenderlich.com/13511/how-to-create-an-app-like-instagram-with-a-web-service-backend-part-12
<?
header("Content-Type: application/json");
//DEBUG TO CHECK PAYKEY
//turn php errors on
ini_set("track_errors", true);
//Example payKey (got from iOS app)
$payKey = "<snip>";
//set PayPal Endpoint to sandbox
$url = trim("https://svcs.sandbox.paypal.com/AdaptivePayments/PaymentDetails?payKey=".$payKey."&requestEnvelope.errorLanguage=en_US");
//PayPal API Credentials
//to do: change these for production credentials in the production app
$API_UserName = "<snip>";
$API_Password = "<snip>";
$API_Signature = "<snip>";
//Default App ID for Sandbox
$API_AppID = "APP-80W284485P519543T";
$API_RequestFormat = "NV";
$API_ResponseFormat = "NV";
try
{
//Create payload for this query
$bodyparams = array ("requestEnvelope.errorLanguage" => "en_US");
// convert payload array into url encoded query string
$body_data = http_build_query($bodyparams, "", chr(38)); // Generates body data
//create request and add headers
$params = array("http" => array(
"method" => "POST",
"content" => $body_data,
"header" => "X-PAYPAL-SECURITY-USERID: " . $API_UserName . "\r\n" .
"X-PAYPAL-SECURITY-PASSWORD: " . $API_Password . "\r\n" .
"X-PAYPAL-SECURITY-SIGNATURE: " . $API_Signature . "\r\n" .
"X-PAYPAL-APPLICATION-ID: " . $API_AppID . "\r\n" .
"X-PAYPAL-REQUEST-DATA-FORMAT: " . $API_RequestFormat . "\r\n" .
"X-PAYPAL-RESPONSE-DATA-FORMAT: " . $API_ResponseFormat
));
//create stream context
$ctx = stream_context_create($params);
//open the stream and send request
$fp = #fopen($url, "r", false, $ctx);
//get response
$response = stream_get_contents($fp);
//check to see if stream is open
if ($response === false) {
throw new Exception("php error message = " . "$php_errormsg");
}
//close the stream
fclose($fp);
//parse the ap key from the response
$keyArray = explode("&", $response);
foreach ($keyArray as $rVal){
list($qKey, $qVal) = explode ("=", $rVal);
$kArray[$qKey] = $qVal;
}
//print the response to screen for testing purposes
If ( $kArray["responseEnvelope.ack"] == "Success")
{
foreach ($kArray as $key =>$value){
echo $key . ": " .$value . "<br/>";
}
}
else {
echo 'ERROR Code: ' . $kArray["error(0).errorId"] . " <br/>";
echo 'ERROR Message: ' . urldecode($kArray["error(0).message"]) . " <br/>";
}
}
catch(Exception $e)
{
echo "Message: ||" .$e->getMessage()."||";
}
//End check paykey
?>
I would have attached an image showing all of the fields that you can get at with $kArray but I don't have the reputation. you would want: $kArray["paymentInfoList.paymentInfo(0).transactionId"]
NOTE: the API credentials you should use for sandbox can be found under your "sandbox accounts" at developer.paypal.com. Expand the profile of xxxfacilitator#xxx to get them
We can get transaction details like -
First get access token using your clientId and ClientSecret
$ch = curl_init();
$clientId = PAYPAL_CLIENT_ID; //client Id
$secret = PAYPAL_CLIENT_SECRET; client secrete key
curl_setopt($ch, CURLOPT_URL, "https://api.sandbox.paypal.com/v1/oauth2/token");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, $clientId . ":" . $secret);
curl_setopt($ch, CURLOPT_POSTFIELDS, "grant_type=client_credentials");
$result = curl_exec($ch);
$accessToken = null;
if (empty($result))
die('invalid access token');
else {
$json = json_decode($result);
$accessToken = $json->access_token;
}
curl_close($ch);
After Getting access token, I get transaction detail using following code
$curl = curl_init("https://api.sandbox.paypal.com/v1/payments/payment/<paykey>");
curl_setopt($curl, CURLOPT_POST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Authorization: Bearer ' . $accessToken,
'Accept: application/json',
'Content-Type: application/json'
));
$response = curl_exec($curl);
$result = json_decode($response);
With this we can validate transaction.
remove sandbox work from url when you are using it for live.

Using Facebook Graph API from a mobile application

I have a small card game at Facebook (and few Russian social networks), which gets user's id, first name and avatar through the old REST API.
Now I'm trying to develop the same game as a mobile app with Flex Hero SDK for Android and iPhone. Which means I can't use native SDKs for those platforms, but have to use OAuth as descibed at Facebook page.
I'm trying to write a short PHP script, which would return the user information as XML to my mobile app. My script can get the token already:
<?php
define('FB_API_ID', 'XXX');
define('FB_AUTH_SECRET', 'XXX');
$code = #$_GET['code'];
# this is just a link for me, for development puposes
if (!isset($code)) {
$str = 'https://graph.facebook.com/oauth/authorize?client_id=' . FB_API_ID .
'&redirect_uri=http://preferans.de/facebook/mobile.php&display=touch';
print "<html><body>$str</body></html>";
exit();
}
$req = 'https://graph.facebook.com/oauth/access_token?client_id=' . FB_API_ID .
'&redirect_uri=http://preferans.de/facebook/mobile.php&client_secret=' . FB_AUTH_SECRET .
'&code=' . $code;
$ch = curl_init($req);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$page = curl_exec($ch);
if (curl_errno($ch))
exit('Download failed');
curl_close($ch);
parse_str($page, $data);
#header('Content-Type: text/xml; charset=utf-8');
#print('<?xml version="1.0"? ><app>');
print_r($data);
#print('</app>');
?>
This works well and I get back the token:
Array
(
[access_token] => 262578703638|2.OwBuoa2fT5Zp_yo2hFUadA__.3600.1294904800-587287941|ycUNaHVxa_8mvenB9JB1FH3DcAA
[expires] => 6697
)
But how can I use this token now to find the user's name and avatar and especially I'm confused by how will I get the current user id?
While using REST API I've always known the current user id by calling $userid=$fb->require_login()
See docs at: http://developers.facebook.com/docs/api
Use curl to request: https://graph.facebook.com/me/?access_token=XXXXXXX
The "/me" will get you all of the info you need.
$req = 'https://graph.facebook.com/me/?access_token=' . $access_token;
$ch = curl_init($req);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$page = curl_exec($ch);
if (curl_errno($ch))
exit('Download failed');
curl_close($ch);
$user_object = json_decode($page);
var_dump($user_object);
Will return something like:
object(stdClass)#1 (20) {
["id"]=>
string(10) "1017193642"
["name"]=>
string(19) "Lance Scott Rushing"
["first_name"]=>
string(5) "Lance"
["middle_name"]=>
string(5) "Scott"
["last_name"]=>
string(7) "Rushing"
["link"]=>
string(36) "http://www.facebook.com/LanceRushing"
.....
Since I cannot add comments I'll answer here.
In order to get the profile picture you need to request https://graph.facebook.com/ID/picture. If you want only specific fields you can specify it this way: https://graph.facebook.com/ID?fields=uid,name,etc&access_token=token
Alternatively you can use the PHP SDK to authorise and log in the user so that you don't have to get the token manually - it would simplify your code. For instance, instead of every cURL request you could just do $facebook->api(request); A good description and example are here http://apps.facebook.com/graphapidemo/.

How to tag photos in facebook-api?

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