Wondering why this code doesn't update my product. I have tested in the chrome rest console and works great. However, when testing the curl in php it doesn't update. I have tested doing a simple GET request for product count with curl in php and it responded fine. Just the PUT is giving me fits. Anything stand out?
<?php
$baseUrl = https://apikey:password#hostname/admin/';
$variant =
array('inventory_quantity' => 20
);
$ch = curl_init($baseUrl.'variants/19175889219.json'); //note product ID in url
$data_string = json_encode(array('variant'=>$variant)); //json encode the product array
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); //specify the PUT verb for update
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); //add the data string for the request
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //set return as string true
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
); //set the header as JSON
$server_output = curl_exec ($ch); //execute and store server output
curl_close ($ch); //close the connection
echo $data_string;
echo $server_output;
?>
Related
Im trying to create a simple api that will post json to an endpoint using curl and php. its giving me an error whereby its saying unsupported media type and i need help seeing what it is i might be doing wrong, here is the code
<?php
$data = array("saleAmount"=>"2000","cashBack"=>"800","posUser"=>"John","tenderType"=>"SWIPE","currency"=>"RTGS","transactionId"=>'0001');
$payload = json_encode($data);
echo $payload;
// prepare curl
$ch = curl_init('http://localhost:9111/api/requests');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/jsonp',
'Content-Length: ' . strlen($payload))
);
// Submit the POST request
$result = curl_exec($ch);
echo json_encode($result);
// Close cURL session handle
curl_close($ch);
?>
The issue is that your API is expecting a different media type than the one you are providing in your quest.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/415
Make sure that your API supports the content-type application/json
$url="";//path of api
$ch=curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json')
);
$data = array("saleAmount"=>"2000","cashBack"=>"800","posUser"=>"John","tenderType"=>"SWIPE","currency"=>"RTGS","transactionId"=>'0001');
$data=json_encode($data);
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_POST,true);
curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
$response=curl_exec($ch);
print_r($response);die;
curl_close($ch);
Append your url in $url and check this once.
I just got API access for one of the website on the internet, and as a new api developer i got into troubles understanding how should i start and with what, So hope you guys guide me . They don't have Documents or tutorials Yet.
If anyone can give me a small example on how to send Http post request that includes Header and body? As what they are mentioning in the API page:
All requests must include an Authorization header with siteid and
apikey (with a colon in between) and it must match with the siteid and
apikey in the request body
In the body the Parameter content type will be application/json. They have also provided a Base URL.
The response will be as application/json.
What should i do? is the request can be sent using AJAX? or there is PHP code for this? i have been reading a lot about this subject but none enter my head. Really hope you guys help me out .
Please let me know if you need more information so i can provide it to you.
EDIT : Problem solved and just posting the small editing that i did to the code that was provided in the correct answer that i marked .
Thanks to Mr. Anonymous for the big help that he gave me . His answer was so so close, all what i had to do is just edit his code a little bit and everything went good .
I will list the finial code down bellow in case any other developer had this issue or wanted to do an HTTP request .
First what i did is that i stored the data that i wanted to send over the HTTP in a file with a JSON type :
{
"criteria": {
"landmarkId": 181,
"checkInDate": "2018-02-25",
"checkOutDate": "2018-02-30"
}
}
Second thing as what guys can see what Mr. Anonymous posted .
<?php
header('Access-Control-Allow-Origin: *');
$SiteID= 'My Site Id';
$ApiId= 'My Api Id';
$url = 'Base URL';
// Here i will get the data that i created in Json data type
$data = file_get_contents("data.json");
// I guess this step in not required cause the data are already in JSON but i had to do it for myself
$arrayData = json_decode($data, true);
$ch = curl_init();
//curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "$SiteID:$ApiID");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Connection: Keep-Alive',
'Authorization: $SiteID:$ApiId'
));
curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($arrayData));
$result = curl_exec($ch);
curl_close($ch);
print_r($result);
?>
Try this
$site_id = 'your_site_id';
$api_key = 'your_api_key';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://api-connect-url');
curl_setopt($ch, CURLOPT_POST, 1);
############ Only one of the statement as per condition ###########
//if they have asked for post
curl_setopt($ch, CURLOPT_POSTFIELDS, "$site_id=$api_key" );
//or if they have asked for raw post
curl_setopt($ch, CURLOPT_POSTFIELDS, "$site_id:$api_key" );
####################################################################
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ["$site_id:$api_key"] );
$api_response = curl_exec ($ch);
curl_close ($ch);
As asker need to send JSON Payload to API
$site_id = 'your_site_id';
$api_key = 'your_api_key';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://api-connect-url');
curl_setopt($ch, CURLOPT_POST, 1);
//send json payload
curl_setopt($ch, CURLOPT_POSTFIELDS, "{
"criteria":{
"cityId":9395,
"area":{
"id":0,
"cityId":0
},
"landmarkId":0,
"checkInDate":"2017-09-02",
"checkOutDate":"2017-09-03",
"additional":{
"language":"en-us",
"sortBy":"PriceAsc",
"maxResult":10,
"discountOnly":false,
"minimumStarRating":0,
"minimumReviewScore":0,
"dailyRate":{
"minimum":1,
"maximum":10000
},
"occupancy":{
"numberOfAdult":2,
"numberOfChildren":1
},
"currency":"USD"
}
}
}"
);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ["$site_id:$api_key", 'Content-Type:application/json'] );
$api_response = curl_exec ($ch);
curl_close ($ch);
I'm trying to upload spherical images on street view using Publish Api.
Upload of image data and place association works well, but whenever i try to upload heading and gps position data to the image server responds "OK" but then no heading nor position were associated to the image.
Here is the php code i use for the last step of info upload, i really don't know where i am wrong.
$data['uploadReference']['uploadUrl']=$upload_url;
$data['pose']['heading']=$heading_north;
$data['pose']['latLngPair']=$latLngPair;
$data['captureTime']['seconds']=time();
$data['places']['placeId']=$placeid;
$data_string = json_encode($data);
$ch = curl_init('https://streetviewpublish.googleapis.com/v1/photo?key='.$_GOOGLE_API['api_key']);
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(
'authorization: Bearer '.$_GOOGLE_API['access_token'],
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$result = curl_exec($ch);
curl_close ($ch);
EDIT:
I've implemented the second step as suggested but nothing changes..
Curl response still doesn't contains any error..
$ch = curl_init('https://streetviewpublish.googleapis.com/v1/photo/'.$photo_id.'?key='.$_GOOGLE_API['api_key'].'&updateMask=pose.heading');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'authorization: Bearer '.$_GOOGLE_API['access_token'],
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$json_response=curl_exec($ch);
curl_close ($ch);
echo $json_response;
EDIT2: this procedure works but google apis are slow and edited data will show up in minutes..
EDIT3 (SOLVED): GET photos (list) has some chache issue. to get the correct value just updated you need to request GET photo (single) to force an effective cache update.
Try to set the values in a second step with photo.update. Don't forget to set the updateMask for the values.
I am trying to post a file and some data using curl to a local go server hosted on the same machine:
// initialise the curl request
$request = curl_init('http://localhost:9049/api');
// send a file
curl_setopt($request, CURLOPT_POST, true);
curl_setopt(
$request,
CURLOPT_POSTFIELDS,
array(
'company' => 'compname',
'user' => 'compuser',
'srv'=> 0,
'colTxt' => 'col1|col2|col3',
'upfile' => '#' . $_FILES['upfile']['tmp_name']
. ';filename=' . $_FILES['upfile']['name']
. ';type=' . $_FILES['upfile']['type']
));
// output the response
curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
$res = curl_exec($request);
// close the session
curl_close($request);
Unfortunately the above code is giving an empty response, have tried many various methods, but still an empty response.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
$result=curl_exec ($ch);
curl_close ($ch);
Even the curl_getinfo($ch) is empty, so it is getting hard to diagnose. Although there doesn't seem to be a network problem as i can post a file using curl from the command line and it worked perfectly fine. Any idea on what i might be missing?
Thanks.
Have a look here for details on using curl to upload files with the curlfile class
I'm trying to setup the application server part of C2DM push messaging using this code - https://github.com/lytsing/c2dm-php.
I have completed the app side of things and have registered an email address with Google - every time I run the code (on a server with php/cURL installed) i get the error 'get auth token error'. It driving me nuts as I've no idea where to begin to solve the problem.
The only lines I have changed in the code are - in the s2dm.php file -
'source' => 'com.phonegap.chillimusicapp',
and I added my email/password into the post.php file -
$result = $c2dm->getAuthToken("email#googlemail.com", "password");
Any advice would be great!
Cheers
Paul
Try using below sample code, It is working fine.
<?php
define("C2DM_ACCOUNT_EMAIL","[C2DM_EMAIL]");
define("C2DM_ACCOUNT_PASSWORD","[C2DM_PASSWORD]");
define("C2DM_CLIENT_LOGIN_URL","https://www.google.com/accounts/ClientLogin");
define("C2DM_MSG_SEND_URL","https://android.apis.google.com/c2dm/send");
function sendPushNotification($device_reg_id,$msg){
$auth_id=get_auth_id(); // To get Auth ID
$post_fields=array(
'collapse_key=ck_1',
'registration_id='. trim($device_reg_id),
'data.payload='. trim($msg),
);
$data_str=implode('&', $post_fields);
$headers = array(
'Authorization: GoogleLogin auth='.trim($auth_id),
'Content-Type: application/x-www-form-urlencoded',
'Content-Length: '.trim(strlen($data_str)),
'Connection: close'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,C2DM_MSG_SEND_URL);
curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_str);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);
curl_close ($ch);
// print_r($server_output);
}
function get_auth_id(){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,C2DM_CLIENT_LOGIN_URL);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "Email=".C2DM_ACCOUNT_EMAIL."&Passwd=".C2DM_ACCOUNT_PASSWORD."&accountType=GOOGLE&source=Google-cURL-Example&service=ac2dm");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);
curl_close ($ch);
// print_r($server_output);
$parts=explode("Auth=",$server_output);
$auth_id=$parts[1];
// echo $auth_id;
return $auth_id;
}
$reg_id = "[DEVICE_REG_ID]";
sendPushNotification($reg_id,"Hello World...!! Jay is testing C2DM...");
FYI! No need to call get_auth_id() every time you send notification, You can call once and store auth_id somewhere in config file also.