ServiceM8 Post JSON via Curl PHP and API - php

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

Related

Calling Watson API from PHP code

I am trying to call Natural Language Understanding Watson API from my PHP code using curl. I have successfully tried curl from terminal. It gives some result on executing this command:
curl -u "my_username":"my_password" "https://gateway.watsonplatform.net/natural-language-understanding/api/v1/analyze?version=2017-02-27&text=I%20still%20have%20a%20dream.&features=sentiment,keywords"
However when I try to use curl in php using this code:
<?php
$url = "https://gateway.watsonplatform.net/natural-language-understanding/api/v1/analyze?version=2017-02-27&text=I%20still%20have%20a%20dream%2C%20a%20dream%20deeply%20rooted%20in%20the%20American%20dream%20%E2%80%93%20one%20day%20this%20nation%20will%20rise%20up%20and%20live%20up%20to%20its%20creed%2C%20%22We%20hold%20these%20truths%20to%20be%20self%20evident%3A%20that%20all%20men%20are%20created%20equal.&features=sentiment,keywords";
$post_args = array(
'version' => '2017-02-27',
'url' => 'https://davidwalsh.name/curl-post',
'features' => 'sentiment,keywords'
);
$headers = array(
'Content-Type:application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERPWD, "my_username:my_password");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
//curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
//curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_args));
$result = curl_exec($ch);
if ($result === FALSE) {
die('Send Error: ' . curl_error($ch));
}
curl_close($ch);
echo $result;
?>
I get this result:
{
"error": "unsupported media type",
"code": 415
}
What should be done?
I can't believe I was stuck here due to a blank space.
Replacing this:
$headers = array(
'Content-Type:application/json'
);
with
$headers = array(
'Content-Type: application/json'
);
worked. Note the blank space between : and application/json.

Passing JSON to PHP CURL [duplicate]

I have been working on building an Rest API for the hell of it and I have been testing it out as I go along by using curl from the command line which is very easy for CRUD
I can successfully make these call from the command line
curl -u username:pass -X GET http://api.mysite.com/pet/1
curl -d '{"dog":"tall"}' -u username:pass -X GET http://api.mysite.com/pet
curl -d '{"dog":"short"}' -u username:pass -X POST http://api.mysite.com/pet
curl -d '{"dog":"tall"}' -u username:pass -X PUT http://api.mysite.com/pet/1
The above calls are easy to make from the command line and work fine with my api, but now I want to use PHP to create the curl. As you can see, I pass data as a json string. I have read around and I think I can probably do the POST and include the POST fields, but I have not been able to find out how to pass http body data with GET. Everything I see says you must attached it to the url, but it doesn't look that way on the command line form. Any way, I would love it if someone could write the correct way to do these four operations in PHP here on one page. I would like to see the simplest way to do it with curl and php. I think I need to pass everything through the http body because my php api catching everything with php://input
PUT
$data = array('username'=>'dog','password'=>'tall');
$data_json = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen($data_json)));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
POST
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
GET
See #Dan H answer
DELETE
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
You can use this small library: https://github.com/ledfusion/php-rest-curl
Making a call is as simple as:
// GET
$result = RestCurl::get($URL, array('id' => 12345678));
// POST
$result = RestCurl::post($URL, array('name' => 'John'));
// PUT
$result = RestCurl::put($URL, array('$set' => array('lastName' => "Smith")));
// DELETE
$result = RestCurl::delete($URL);
And for the $result variable:
$result['status'] is the HTTP response code
$result['data'] an array with the JSON response parsed
$result['header'] a string with the response headers
Hope it helps
For myself, I just encode it in the url and use $_GET on the destination page. Here's a line as an example.
$ch = curl_init();
$this->json->p->method = "whatever";
curl_setopt($ch, CURLOPT_URL, "http://" . $_SERVER['SERVER_NAME'] . $this->json->path . '?json=' . urlencode(json_encode($this->json->p)));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
EDIT: Adding the destination snippet... (EDIT 2 added more above at OPs request)
<?php
if(!isset($_GET['json']))
die("FAILURE");
$json = json_decode($_GET['json']);
$method = $json->method;
...
?>
I was Working with Elastic SQL plugin.
Query is done with GET method using cURL as below:
curl -XGET http://localhost:9200/_sql/_explain -H 'Content-Type: application/json' \
-d 'SELECT city.keyword as city FROM routes group by city.keyword order by city'
I exposed a custom port at public server, doing a reverse proxy with Basic Auth set.
This code, works fine plus Basic Auth Header:
$host = 'http://myhost.com:9200';
$uri = "/_sql/_explain";
$auth = "john:doe";
$data = "SELECT city.keyword as city FROM routes group by city.keyword order by city";
function restCurl($host, $uri, $data = null, $auth = null, $method = 'DELETE'){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $host.$uri);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if ($method == 'POST')
curl_setopt($ch, CURLOPT_POST, 1);
if ($auth)
curl_setopt($ch, CURLOPT_USERPWD, $auth);
if (strlen($data) > 0)
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
$resp = curl_exec($ch);
if(!$resp){
$resp = (json_encode(array(array("error" => curl_error($ch), "code" => curl_errno($ch)))));
}
curl_close($ch);
return $resp;
}
$resp = restCurl($host, $uri); //DELETE
$resp = restCurl($host, $uri, $data, $auth, 'GET'); //GET
$resp = restCurl($host, $uri, $data, $auth, 'POST'); //POST
$resp = restCurl($host, $uri, $data, $auth, 'PUT'); //PUT
set one more property curl_setopt($ch, CURLOPT_SSL_VERIFYPEER , false);

web API POST curl returns 'not found anything matching the request URI'

i try to access a web api with json encoded and $POST method in php. After a few tries, i get this message:
Not Found - The server has not found anything matching the request URI
.You can get technical details here. Please continue your visit at our
home page.
Why? thank you, my code is:
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
//DADOS DE ACESSO
$id = "xxx";
$retailerName = "xxx";
$key = "xxx";
//PRODUTO
//vars of product:fictional data
$upc = "799366289999";
$amount = "20.00";
//URL DE ACESSO
$function = "requestActivateCode";
//usado pra criar a canonical
$resPath = "/v1/activateCode";
$url = "https://111.222.333.444/v1/";
$urlCall = $url.$function;
//HTTP HEADERS
$date = gmdate("M, d Y H:i:s \G\M\T", time());
$contentType = "Content-Type: application/json; charset=UTF-8";
$accept = "Accept: application/json";
$xIncommDateTime = substr(substr_replace(date('c'), substr(round(microtime(), 3), 1, 8), 19, 0), 0, -6) . "Z";
//authorization
$type = "application/json; charset=UTF-8";
$canonical = ($xIncommDateTime) + ($type) + ($resPath);
$signature = hash_hmac ('sha1', $key, $canonical);
$idEncoded = base64_encode($id);
$signatureEncoded = base64_encode($signature);
$authorization = "Incomm ". $idEncoded .':'. $signatureEncoded;
$header = array("Date: ".$date, $contentType, $accept, "X-Incomm-DateTime: ".$xIncommDateTime, "Authorization: ".$authorization);
//PARAMS example
$params = array("RetailTransactionRequest" =>
array(
"code" => "0000002381237220",
"amount" => $amount,
"upc" => $upc,
"transactionID" => "1234",
"dateTime" => $xIncommDateTime,
"retailerName" => $retailerName
)
);
$request = json_encode($params);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $urlCall);
//curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
//curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
//curl_setopt($ch, CURLOPT_SSLVERSION, 1);
//curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
curl_setopt($ch, CURLOPT_PORT, 443);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,0);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
echo curl_setopt($ch, CURLINFO_HEADER_OUT, true); // enable tracking
$result = curl_exec($ch);
echo $result;
$headerSent = curl_getinfo($ch, CURLINFO_HEADER_OUT ); // request headers
echo "<pre>";
print_r($headerSent);
echo "</pre>";
if($result === false)
{
echo 'Curl error: ' . curl_error($ch);
}
else
{
echo 'Operation completed without any errors';
echo "<pre>";
print_r($result);
echo "</pre>";
}
In netstat -l ip my port 443 is listening, but the host in ping dont. I want to know how to solve the problem, thank you
If the code is exactly what is shown I don't think that your server's ip address is correct. Instead of using the IP address (111.222.333.444) used in the example, substitute the IP address of your site or the domain name of your site.
$url = "https://111.222.333.444/v1/"

Posting JSON data to API using CURL

When I'm posting json data to API using curl - I'm not getting any output. I would like to send email invitation to recipient.
$url_send ="http://api.address.com/SendInvitation?";
$str_data = json_encode($data);
function sendPostData ($url, $post) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
return curl_exec($ch);
}
And here is JSON $str_data
[
{
"authorizedKey" : "abbad35c5c01-xxxx-xxx",
"senderEmail" : "myemail#yahoo.com",
"recipientEmail" : "jaketalledo86#yahoo.com",
"comment" : "Invitation",
"forceDebitCard" : "false"
}
]
And calling function:
$response = sendPostData($url_send, $str_data);
This is the API: https://api.payquicker.com/Help/Api/POST-api-SendInvitation
Try adding curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
And changing http_build_query($post) to $post
The implementation:
<?php
$data = array(
"authorizedKey" => "abbad35c5c01-xxxx-xxx",
"senderEmail" => "myemail#yahoo.com",
"recipientEmail" => "jaketalledo86#yahoo.com",
"comment" => "Invitation",
"forceDebitCard" => "false"
);
$url_send ="http://api.payquicker.com/api/SendInvitation?authorizedKey=xxxxx";
$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_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);
?>
The response I get is:
{"success":false,"errorMessage":"Object reference not set to an instance of an object.","status":"N/A"}
But maybe it will work with valid data....
Edit:
For posting xml,
it's the same as on their site, except in a string:
$xml = '
<SendInvitationRequest xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/PQApi.Models">
<authorizedKey>80c587b9-caa9-4e56-8750-a34b17dba0a2</authorizedKey>
<comment>sample string 4</comment>
<forceDebitCard>true</forceDebitCard>
<recipientEmail>sample string 3</recipientEmail>
<senderEmail>sample string 2</senderEmail>
</SendInvitationRequest>';
Then:
sendPostData($url_send, $xml)
You have to add header:
$headers= array('Accept: application/json','Content-Type: application/json');
And:
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
Otherwise ...
HTTP Status 415 - Unsupported Media Type
... may happen.
You don't need to add headers as you already do json_encode.
just print_r (curl_getinfo($ch)); and see the content type info in it.

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