CURLOPT_POSTFIELDS format - php

I am trying to pass a json string into a curlopt_postfield.
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
I have a working hard coded example. However I am having trouble making it dynamic.
$test = "84560";
$data = "{\"id\":\"" .$test. "\"}";
$data2 = "{\"id\":\"84560\"}";
curl_setopt($ch, CURLOPT_POSTFIELDS, $data2);
Why does $data2 work and $data fail?
I have tried json encoding, utf8 encoding, and lots of variations of escaping the quotes all to no avail. What am I missing? I do not get an error simply a NULL response.
Here is the full code. Still not able to get it working. Any additional suggestions as I have tried everything I have found.
$test = "84560";
$data = "{\"id\":\"" .$test. "\"}";
$data2 = "{\"id\":\"84560\"}";
$result2 = getJson("results.json?", $data2);
function getJson($endpoint, $postfields)
{
$URL = "https://app.mobilecause.com/api/v2/reports/". $endpoint;
$ch = curl_init();
$headers = [];
$headers[] = "Authorization: Token token=\"[token goes here]\"";
$headers[] = "Accept: application/json";
$headers[] = "Content-Type: application/json";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $URL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
if (curl_errno($ch))
{
echo 'Error:' . curl_error($ch);
}
curl_close ($ch);;
return $result;
}

You should simply try:
<?php
$data = array('id' => 84560);
$json = json_encode($data);
echo $json; // Will print { id: 84560 }

Related

Serialization issue: Object keys <> being stripped by php cURL

I have a web service that I am working with and using PHP/cURL to connect with. When I use postman I get
"ShippingInfo": {
"<ShippingMethodId>k__BackingField": 0,
"<ShippingMethod>k__BackingField": null,
"<ShippingNote>k__BackingField": null,
"<ShippingProvider>k__BackingField": null
},
which is correct but when I dump the values in my Drupal site, I get
"ShippingInfo":{"k__BackingField":0,"k__BackingField":null,"k__BackingField":null,"k__BackingField":null}
It seems to be trimming off the <Shipping*> from the response. Any ideas on why this might be happening and how to make it stop?
Here is my cURL call:
ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$headers = array();
$headers[] = 'tokenvalidate: ' . $this->TOKEN;
$headers[] = 'Content-Type: text/json; charset=UTF-8';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
watchdog('cURL error', curl_errno($ch));
} else {
return $result;
}
curl_close($ch);
This seems to be the only object that is having the issue. All other calls are fine.

ServiceM8 Post JSON via Curl PHP and API

Trying to send a post request to the ServiceM8 Api however when i attempt the request i get back no errors and nothing adding to the ServiceM8 api.
Here is what servicem8 docs suggest:
curl -u email:password
-H "Content-Type: application/json"
-H "Accept: application/json"
-d '{"status": "Quote", "job_address":"1 Infinite Loop, Cupertino, California 95014, United States","company_id":"Apple","description":"Client has requested quote for service delivery","contact_first":"John","contact_last":"Smith"}'
-X POST https://api.servicem8.com/api_1.0/job.json
and here is what i have:
$data = array(
"username" => "**************8",
"password" => "****************",
"job_address" => "1 Infinite Loop, Cupertino, California 95014, United States"
);
$url_send ="https://api.servicem8.com/api_1.0/job.json";
$str_data = json_encode($data);
function sendPostData($url, $post){
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS,$post);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$result = curl_exec($ch);
return $result;
-- UPDATE TO SHOW PREVIOUS ATTEMPTS TO RESOLVE BUT HAD NO LUCK..
<?php
$data = array(
"username" => "*******************",
"password" => "**********",
"job_address" => "1 Infinite Loop, Cupertino, California 95014, United States"
);
$url_send ="https://api.servicem8.com/api_1.0/job.json";
$str_data = json_encode($data);
function sendPostData($url, $post){
$headers= array('Accept: application/json','Content-Type: application/json');
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS,$post);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$result = curl_exec($ch);
curl_close($ch); // Seems like good practice
return $result;
}
echo " " . sendPostData($url_send, $str_data);
?>
adding the headers as i have in that example still does nothing and does not create the record in servicem8 or show an error.
Hopefully someone can help me make the correct Curl request using the PHP libary.
Thanks
First issue is it looks like you are not setting authentication details correctly. To use HTTP basic auth in CURL:
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
Second issue is that job_status is a mandatory field when creating Jobs, so you need to make sure to include that as part of your create request.
Assuming that you receive a HTTP 200 response, then you the UUID of the record you just created is returned in the x-record-uuid header (docs). See this answer for an example of how to get headers from a HTTP response in CURL.
Here's your example code modified to include the above advice:
$data = array(
"job_address" => "1 Infinite Loop, Cupertino, California 95014, United States",
"status" => "Work Order"
);
$url_send = "https://api.servicem8.com/api_1.0/job.json";
$str_data = json_encode($data);
function sendPostData($url, $post, $username, $password) {
$ch = curl_init($url);
if ($username && $password) {
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
}
$headers = array('Accept: application/json','Content-Type: application/json');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 1); // Return HTTP headers as part of $result
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$result = curl_exec($ch);
// $result is the HTTP headers followed by \r\n\r\n followed by the HTTP body
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($result, 0, $header_size);
$body = substr($result, $header_size);
$strRecordUUID = "";
$arrHeaders = explode("\r\n", $header);
foreach ($arrHeaders as $strThisHeader) {
list($name, $value) = explode(':', $strThisHeader);
if (strtolower($name) == "x-record-uuid") {
$strRecordUUID = trim($value);
break;
}
}
echo "The UUID of the created record is $strRecordUUID<br />";
return $body;
}
echo "the response from the server was <pre>" . sendPostData($url_send, $str_data, $username, $password) . "</pre>";

passing value to array from api php

I want to pass value from API to array but I am not able to figureout what code I need to write. currently it returns [1481367,7546218] how can I pass this in array
$content = array($result) ;
Below is the API Code
$Login = 8632465; #Must be Changed
$apiPassword = "Kcfve123*"; #Must be Changed
$data = array("Login" => $Login, "Password" => $apiPassword);
$data_string = json_encode($data);
$ch = curl_init('http://client-api.instaforex.com/api/Authentication/RequestPartnerApiToken');
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);
curl_close($ch);
$apiMethodUrl = 'partner/GetReferralAccounts/'; #possibly Must be Changed
$parameters = $Login; #possibly Must be Changed. Depends on the method param
$ch = curl_init('http://client-api.instaforex.com/'.$apiMethodUrl.$parameters);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false); # Turn it ON to get result to the variable
curl_setopt($ch, CURLOPT_HTTPHEADER, array('passkey: '.$token));
$result = curl_exec($ch);
//$result = trim(preg_replace('[]','',curl_exec($ch)));
curl_close($ch);
If the CURL result is "[1481367,7546218]", then to convert this into an array:
`$content = json_decode($result,TRUE); //Here $result = "[1481367,7546218]"`
Printing the variable $content using var_dump() variable will output:
array(2) {
[0] => int(1481367)
[1] => int(7546218)
}

PHP Post JSON value to next page

I want to grab json string, set objects and httpheaders in 1.php (for example). Get these values in JSON format and display in next page (2.php).
I tried to use CURL method. I m very new to PHP. Not sure whether CURL method is the best to POST data.. Session or cookie method no need. Is there any other method other than this to POST data?
1.PHP:
<?php
$data = array($item_type = "SubscriptionConfirmation";
$message = "165545c9-2a5c-472c-8df2-7ff2be2b3b1b";
$Token = "2336412f37fb687f5d51e6e241d09c805a5a57b30d712f794cc5f6a988666d92768dd60a747ba6f3beb71854e285d6ad02428b09ceece29417f1f02d6";
$TopicArn = "arn:aws:sns:us-east-1:123456789012:MyTopic";
$Message = "You have chosen to subscribe to the topic arn:aws:sns:us-east-1:123456789012:MyTopic.\nTo confirm ";
$SubscribeURL = "https://sns.us-east-1.amazonaws.com/?Action=ConfirmSubscription&TopicArn=arn:aws:sns:us-east-1:123456789012:MyTopic&Token=2336412f37fb6";
$Timestamp = "2012-04-26T20:45:04.751Z";
$SignatureVersion = "1";
$Signature = "EXAMPLEpH+DcEwjAPg8O9mY8dReBSwksfg2S7WKQcikcNKWLQjwu6A4VbeS0QHVCkhRS7fUQvi2egU3N858fiTDN6bkkOxYDVrY0Ad8L10Hs3zH81mtnPk5uvvolIC1CXGu43obcgFxeL3khZl8IKvO61GWB6jI9b5+gLPoBc1Q=";
$SigningCertURL = "https://sns.us-east-1.amazonaws.com/SimpleNotificationService-f3ecfb7224c7233fe7bb5f59f96de52f.pem";);
$json_data = json_encode($data);
$ch = curl_init('http://example.com');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CAINFO, "/path/to/CA.crt");
curl_setopt($ch, CURLOPT_HTTPHEADER,array(
'Content-Type: application/json',
'Content-Length: ' . strlen($json_data))
);
$output = curl_exec($ch);
$result = json_decode($output);
echo $result;
?>
2.PHP:
How to post 1.php json value to 2.php.. either through CURL or other posting method.. Tried my best.. cant able to figure out the solution.
Thanks
1.php
$data = array(
'test' => 'data',
'new' => 'array');
$json_data = json_encode($data);
// Only work with your example, curl need full url
$request_url = 'http://teshdigitalgroup.com/2.php';
$ch = curl_init($request_url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($json_data))
);
$output = curl_exec($ch);
print_r($output);
AND 2.php
print_r(file_get_contents('php://input'));
// Response 1.php's request HTTP Header
function parseRequestHeaders() {
$headers = array();
foreach($_SERVER as $key => $value) {
if (substr($key, 0, 5) <> 'HTTP_') {
continue;
}
$header = str_replace(' ', '-', ucwords(str_replace('_', ' ', strtolower(substr($key, 5)))));
$headers[$header] = $value;
}
return $headers;
}
print_r(parseRequestHeaders());

Yammer - How to post via api to activity stream? (php)

I am able to "GET" the activity stream but not "POST" to it. It seems its a technical error.
This is the code which works for getting the activity stream:
function getActivityStream()
{
$as=$this->request('https://www.yammer.com/api/v1/streams/activities.json');
var_dump($as);
}
function request($url, $data = array())
{
if (empty($this->oatoken)) $this->getAccessToken();
$headers = array();
$headers[] = "Authorization: Bearer " . $this->oatoken['token'];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url . '?' . http_build_query($data) );
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
return json_decode($output);
}
ok so that works fine...
the code below, returns a Yammer "oops this page could not be found" message:
function putActivityStream()
{
$data=array('type'=>'text', 'text'=>'hello from api test call');
$json=json_encode($data);
$res=$this->post('streams/activites.json',$json);
}
function post($resource, $data)
{
if (empty($this->oatoken)) $this->getAccessToken();
$ch = curl_init();
$headers = array();
$headers[] = "Authorization: Bearer " . $this->oatoken['token'];
$headers[]='Content-Type: application/json';
$url = 'https://www.yammer.com/api/v1/' . $resource;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
return $response;
}
One of the examples from:
http://developer.yammer.com/api/streams.html
POST https://www.yammer.com/api/v1/streams/activities.json
Requests must be content-type: application/json.
{
"type": "text",
"text": "The build is broken."
}
You're going to kick yourself. You have a typo in your code. :)
Change:
$res=$this->post('streams/activites.json',$json);
to
$res=$this->post('streams/activities.json',$json);
Simples.

Categories