freshdesk API not working for adding tickets - php

I am trying to create a Freshdesk ticket using freshdesk API in php curl.
followed this documentation link https://github.com/freshdesk/fresh-samples/tree/master/php_samples
But it is not creating ticket
<?php
$fd_domain = "http://test.freshdesk.com";
$token = "apikey";
$password = "xxx";
$email = "aaa#bbb.com";
$data = array(
"helpdesk_ticket" => array(
"description" => "Some details on the issue ...",
"subject" => "TEST Support needed..",
"email" => "tom#outerspace.com",
"priority" => 1,
"status" => 2
),
"cc_emails" => "ram#freshdesk.com,diana#freshdesk.com"
);
$json_body = json_encode($data, JSON_FORCE_OBJECT | JSON_PRETTY_PRINT);
$header[] = "Content-type: application/json";
$connection = curl_init("$fd_domain/helpdesk/tickets.json");
curl_setopt($connection, CURLOPT_RETURNTRANSFER, true);
curl_setopt($connection, CURLOPT_HTTPHEADER, $header);
curl_setopt($connection, CURLOPT_HEADER, false);
curl_setopt($connection, CURLOPT_USERPWD, "$email:$password");
curl_setopt($connection, CURLOPT_POST, true);
curl_setopt($connection, CURLOPT_POSTFIELDS, $json_body);
curl_setopt($connection, CURLOPT_VERBOSE, 1);
$response = curl_exec($connection);
echo $response;
?>
when i run this file in terminal as php file.php But ticket is not running, I am getting the following console results
But I am not sure what is happening.
* Hostname was NOT found in DNS cache
* Trying 107.22.197.253...
* Connected to test.freshdesk.com (107.22.197.253) port 80 (#0)
* Server auth using Basic with user 'aaa#bbb.com'
> POST /helpdesk/tickets.json HTTP/1.1
Authorization: Basic bW9oYW5Ad2h5YWJsZS5jb206bW9oYW4xMjM=
Host: test.freshdesk.com
Accept: */*
Content-type: application/json
Content-Length: 274
* upload completely sent off: 274 out of 274 bytes
< HTTP/1.1 302 Found
< Cache-Control: no-cache
< Content-Type: text/html; charset=utf-8
< Location: https://test.freshdesk.com/helpdesk/tickets.json
< Set-Cookie: helpdesk_node_session=0fbdb53a62fff9b78f57d069a7abfde86bef1e16eefa8710dbcadb99a1723a3a42affa906dd23ceb6e77f20f0a0e703a2cb6d3423cb94ec074f0006dadfe4b02; path=/
< Set-Cookie: _helpkit_session=BAh7CDoPc2Vzc2lvbl9pZCIlMzdmNGI4ZDZkZWMxNmRhNDBkYWI1ZTFiODU2NDFkODhJIhV1c2VyX2NyZWRlbnRpYWxzBjoGRUZJIgGAZmYxMmExZWJjZGFiMTlkMjgxYjlkYmI0NjIwZjdhMjFlYTgxM2YyZWE5M2UzYTk0MTlhYzBhNDA2M2QyMzEwNTdmNDQ4NjVjYmE1MjA1ZjU2ODUzNGI2ZGQ4NTExZjljZGUyZGQxNzViMzNjMzhkZTYxMTc1MDRkMWE2MGMyOTEGOwZUSSIYdXNlcl9jcmVkZW50aWFsc19pZAY7BkZsKwj%2B0TIqAQA%3D--fdc65abdf0bdcf0c38db4837f05b19050ef1a2f0; path=/; HttpOnly
< Status: 302
< X-Runtime: 25
< Content-Length: 117
< Connection: keep-alive
<
* Connection #0 to host test.freshdesk.com left intact
<html><body>You are being redirected.</body></html>
please some help me

Related

PHP - curl post view request body (parameters)

I get an error response for missing parameter when posting cURL POST method,
I'm adding an array of parameters to CURLOPT_POSTFIELDS the following way:
$service = "AutoInsuranceFormPostService";
$method = "autoInsurancePublisherFormPost";
$userAgent = "Mozilla%2F5.0+%28Linux%3B+Android+4.4.4%3B+Z752C+Build%2FKTU84P%29+AppleWebKit%2F537.36+%28KHTML%2C+like+Gecko%29+Chrome%2F36.0.1985.135+Mobile+Safari%2F537.36";
$payload = $encodedPayLoad;
$parameters = array (
'service' => $service,
'method' => $method,
'UserAgent' => $userAgent,
'payload' => $payload
);
With:
curl_setopt($ch,CURLOPT_POSTFIELDS,$parameters);
Since the response is saying missing parameter "service", I figured I need to debug the request body.
I managed to get the headers with:
curl_getinfo($ch)
I also attempted to use:
curl_setopt($ch, CURLOPT_VERBOSE, true);
But unfortunately in both cases I only got the headers and not the body (the parameters values).
Full curl execution function:
function openurl($url, $postvars) {
$ch=curl_init();
curl_setopt($ch, CURLOPT_VERBOSE, true);
$verbose = fopen('php://temp', 'w+');
curl_setopt($ch, CURLOPT_STDERR, $verbose);
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch,CURLOPT_POSTFIELDS,$postvars);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_TIMEOUT, '3');
$result = curl_exec($ch);
rewind($verbose);
$verboseLog = stream_get_contents($verbose);
echo "Verbose information:\n<pre>", htmlspecialchars($verboseLog), "</pre>\n";
return $result;
}
Verbos information:
Content-Length: 6659
Expect: 100-continue
Content-Type: application/x-www-form-urlencoded; boundary=------------------------45b2d9f6776306b0
< HTTP/1.1 100 Continue
< HTTP/1.1 200 OK
< Date: Thu, 12 Jul 2018 16:32:52 GMT
< Server: Apache
< Cache-Control: public
< ORIGIN: S_CACHE
< Vary: User-Agent,Accept-Encoding
< Set-Cookie: _qs_origin=s-cache; path=/;
< Set-Cookie: _qs_deviceType=; path=/;
< Content-Length: 141
< Content-Type: application/json;charset=ISO-8859-1
<
This output is useless for me since I cannot see how the parameters were sent and those cannot fix their format.
The response I get is:
{"Status":"Fail","StatusCode":"400","ResponseMessage":"\"service\" parameter empty! || \"method\" parameter empty! ","SkipMatchingFlag":"No"}
I have been searching for a solution all day long, I've seen a ton of answers on "How to see the RESPONSE body", and "How to see the request HEADERS".
But none for "How to see the request body", so any help would be much appreciated,
Best regards.

Getting error 'No authorization header passed' with PHP's POST CURL request - envato api

I'm getting started with the Enavato API
So far I've created an app, got client_id & client_secret and managed to get the code access_key from the https://api.envato.com/authorization after that I'm using the below php code to make POST curl request
$client_id = '***********';
$client_secret = '***********';
$redirect_uri = urlencode('http://localhost:3000');
if(isset($_GET["code"])) :
$apiUrl = 'https://api.envato.com/token';
$params = array(
'grant_type' => 'authorization_code',
'code' => $_GET["code"],
'redirect_uri' => $redirect_uri,
'client_id' => $client_id,
'client_secret' => $client_secret,
);
$curl = curl_init();
$f = fopen('request.txt', 'w');
curl_setopt($curl, CURLOPT_URL, $apiUrl);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_VERBOSE, true);
curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
curl_setopt($curl, CURLOPT_STDERR, $f);
$result = curl_exec($curl);
fclose($f);
// Check if any error occurred
if(empty($result))
{
// die(curl_errno($curl));
// die(curl_error($curl));
$info = curl_getinfo($curl);
echo '<br><br>';
echo 'Took ' . $info['total_time'] . ' seconds to send a request to ' . $info['url'];
echo '<br><br>';
var_dump($info);
echo '<br><br>';
}
var_dump($result);
// Close handle
curl_close($curl);
endif;
and here is the request.txt dump
* Hostname was found in DNS cache
* Hostname in DNS cache was stale, zapped
* Trying 107.23.230.180...
* Connected to api.envato.com (107.23.230.180) port 443 (#0)
* TLS 1.2 connection using TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256
* Server certificate: *.envato.com
* Server certificate: RapidSSL SHA256 CA - G3
* Server certificate: GeoTrust Global CA
> POST /token HTTP/1.1
Host: api.envato.com
Accept: */*
Content-Length: 699
Expect: 100-continue
Content-Type: multipart/form-data; boundary=------------------------1a95a06d7b815306
< HTTP/1.1 100 Continue
< HTTP/1.1 400 Bad Request
< Access-Control-Allow-Origin: *
< Cache-Control: no-store
< Content-Type: application/json; charset=utf-8
< Date: Sun, 17 May 2015 17:03:41 GMT
< Pragma: no-cache
* Server nginx/1.7.10 is not blacklisted
< Server: nginx/1.7.10
< set-cookie: connect.sid=s%3ARC9gGye-Txp4KLp67M9ESspXijYoUc8i.pT3jYHvu1WyOsSjwsuQzEsy5hLQlc2QpmHkZRm05pXo; Path=/; HttpOnly
< X-Frame-Options: Deny
< X-Powered-By: Express
< Content-Length: 80
< Connection: keep-alive
* HTTP error before end of send, stop sending
<
* Closing connection 0
and finally the error(getting it in JSON)
string(80) "{"error":"invalid_request","error_description":"No authorization header passed"}"
Astonishingly every thing is working with Postman and I'm getting "refresh_token" and "access_token" with a success 200 status code.
I know I'm missing some thing but couldn't find what?
You're using curl_setopt($curl, CURLOPT_POSTFIELDS, $params); with $params being an array. That results in a HTTP POST message with multipart/form-data content type and formatting. But the spec says the content type should be application/x-www-form-urlencoded. You can achieve this by using:
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($params));
You also don't need to urlencode the redirect_uri parameter, since http_build_query will do it for you.
Lastly, do not turn off SSL validation (CURLOPT_SSL_VERIFYHOST, CURLOPT_SSL_VERIFYPEER) since it renders your system insecure.

Send SOAP request using CURL

I am sending a soap request using PHP curl(). I need to print my request, so that I can have a look into my request and understand weather it is going in a right format.
Here is my code:
$parameters = "<?xml version='1.0' encoding='UTF-8'?>
<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' xmlns:ejb='http://ejb.gateway.ebpp.fawryis.com/'>
<soapenv:Header/>
<soapenv:Body>
<ejb:process>
//...
</ejb:process>
</soapenv:Body>
</soapenv:Envelope>";
$url='//URL to the service';
$curl = curl_init();
curl_setopt ($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl,CURLOPT_ENCODING,'utf-8');
curl_setopt($curl,CURLOPT_HTTPHEADER,array (
'SOAPAction:""',
'Content-Type: text/xml;
charset=utf-8',
));
curl_setopt ($curl, CURLOPT_POST, 1);
curl_setopt ($curl, CURLOPT_POSTFIELDS, $parameters);
$result = curl_exec($curl);
I get a wrong data sent error from the API side which means I am not sending a correct format.
Can anyone please let me know how to do that?
Update:
Verbose information
* About to connect() to 10.2.250.4 port 9081 (#0)
* Trying 10.2.250.4...
* connected
* Connected to 10.2.250.4 (10.2.250.4) port 9081 (#0)
> POST /CoreWeb/ApplicationBusinessFacadeService HTTP/1.1
Host: 10.2.250.4:9081
Accept: */*
Accept-Encoding: utf-8
SOAPAction:""
Content-Type: text/xml;
charset=utf-8
Content-Length: 1087
Expect: 100-continue
< HTTP/1.1 100 Continue
< Content-Length: 0
< Date: Thu, 20 Mar 2014 14:04:19 GMT
< Server: WebSphere Application Server/7.0
< HTTP/1.1 200 OK
< Date: Thu, 20 Mar 2014 14:04:19 GMT
< Server: WebSphere Application Server/7.0
< Content-Type: text/xml; charset=utf-8
< Content-Language: en-US
< Content-Length: 914
<
* Connection #0 to host 10.2.250.4 left intact
Your Header is broken into two lines:
'Content-Type: text/xml;
charset=utf-8',
Make it in one line. May be it is causing the problem for you.
'Content-Type: text/xml;charset=UTF-8',
UPDATE:
curl_setopt($curl,CURLOPT_HTTPHEADER,array (
'SOAPAction:""',
'Content-Type: text/xml;charset=utf-8',
'Expect:'
));

PHP Curl post with file attachment; custom content-type header

I have to post a file to a server along side with a few post params. The documentation I received from this server admin shows an example of what the post request is supposed to look like (* NOTE the custom content type for the POST "multipart/x-api-remote-integration"):
POST /gateway/remote_send HTTP/1.0
Content-Type: multipart/x-api-remote-integration; boundary=ABC1234
Content-Length: 323
--ABC1234
Content-Type: application/x-www-form-urlencoded
profile_name=username&profile_pw=password1234&attached_type=action_1
--ABC1234
Content-Type: text/csv
Content-Disposition: attachment; filename="attachment.csv"
row1
row2
row3
--ABC1234--
Below is the php code:
<?php
function post(){
$base_api_url = "https://hostserver.com/gateway/remote_send";
$filename = realpath("/home/username/tests/test1234qwerty.csv");
$payload['profile_name'] = "username";
$payload['profile_pw'] = 'password1234';
$payload['attached_type'] = 'action_1';
$payload['filename'] = "#" . $filename . ";type=text/csv;";
$curl_options = array(
CURLOPT_URL => $base_api_url,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => http_build_query( $payload ),
CURLOPT_HTTP_VERSION => 1.0,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_VERBOSE => true,
CURLOPT_HEADER => false,
);
$curl = curl_init();
curl_setopt_array( $curl, $curl_options );
$result = curl_exec( $curl );
curl_close ($curl);
echo $result;
}
post();
From what I am receiving back from the server, it seems that the post fields are being received properly. However it's the file that is not being received. I'm not sure what I did wrong. Any input is greatly appreciated.
EDIT: Attaching Verbose response:
* About to connect() to hostserver.com port 443 (#0)
* Trying x.x.x.x... * connected
* successfully set certificate verify locations:
* CAfile: none
CApath: /etc/ssl/certs
* SSL connection using DHE-RSA-AES256-SHA
* ******** REDACTED ************
* SSL certificate verify ok.
> POST /gateway/remote_send HTTP/1.0
Host: hostserver.com
Accept: */*
Content-Length: 110
Content-Type: application/x-api-remote-integration
* upload completely sent off: 110out of 110 bytes
< HTTP/1.1 200 OK
< Date: Mon, 19 Aug 2013 16:00:38 GMT
< Server: Apache/2.2.15 (Red Hat)
< Pragma: no-cache
< CacheControl: no-cache
< Cache-Control: no-cache
< Expires: -1
< Connection: close
< Content-Type: multipart/x-api-remote-integration; boundary=remote_send-52124126
<
* Closing connection #0
HTTP/1.1 200 OK
Date: Mon, 19 Aug 2013 16:00:38 GMT
Server: Apache/2.2.15 (Red Hat)
Pragma: no-cache
CacheControl: no-cache
Cache-Control: no-cache
Expires: -1
Connection: close
Content-Type: multipart/x-vcg-remote-api; boundary=remote_send-52124126
--remote_send-52124126
Content-Type: application/x-www-form-urlencoded
result=invalid_filename
--remote_send-52124126--
I know the username and pw data is being read correct by the server as I have tested with erroneous info and received credential error instead.
When you tell cURL to upload a file, the Content-Type header is automatically set to multipart/form-data. For a request like in your documentation, you would have to upload the file manually.
<?php
$url = 'https://hostserver.com/gateway/remote_send';
$payload = array(
'profile_name' => 'username',
'profile_pw' => 'password1234',
'attached_type' => 'action_1'
);
$file = realpath('/home/username/tests/test1234qwerty.csv');
// build multipart
$payload = http_build_query($payload);
$params = "--ABC1234\r\n"
. "Content-Type: application/x-www-form-urlencoded\r\n"
. "\r\n"
. $payload . "\r\n"
. "--ABC1234\r\n"
. "Content-Type: text/csv\r\n"
. "Content-Disposition: attachment; filename=\"attachment.csv\"\r\n"
. "\r\n"
. file_get_contents($file) . "\r\n"
. "--ABC1234--";
$first_newline = strpos($params, "\r\n");
$multipart_boundary = substr($params, 2, $first_newline - 2);
$request_headers = array();
$request_headers[] = 'Content-Length: ' . strlen($params);
$request_headers[] = 'Content-Type: multipart/x-api-remote-integration; boundary='
. $multipart_boundary;
// send the request now
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
curl_setopt($ch, CURLOPT_HTTPHEADER, $request_headers);
$reply = curl_exec($ch);
Does that work?

Error 401 using curl in PHP to access REST API

I am trying to execute a curl command that I can execute successfully in the terminal but it fails in PHP script with the following error:
HTTP/1.1 401 Unauthorized Access-Control-Allow-Origin: * Access-Control-Request-Method: * Cache-Control: no-cache Content-Type: application/json; charset=utf-8 Date: Mon, 06 Feb 2012 00:38:56 GMT Server: nginx/1.0.4 Set-Cookie: _parse_session=XXXXXX; domain=.parse.com; path=/; expires=Sun, 06-Feb-2022 00:38:56 GMT; HttpOnly Status: 401 Unauthorized WWW-Authenticate: Basic realm="Parse" X-Runtime: 0.002486 X-UA-Compatible: IE=Edge,chrome=1 Content-Length: 24 Connection: keep-alive {"error":"unauthorized"}
This is the command executed in terminal that executes successfully:
curl -H "Accept: application/json" -H "X-Parse-Application-Id: XXXXXXX" -H "X-Parse-REST-API-Key: XXXXXXXXX" -X GET "https://api.parse.com/1/classes/XXXXXX"
This is the PHP code:
$fields = array('Accept: '=>'application/json',
'X-Parse-Application-Id:' => 'XXXXX',
'X-Parse-REST-API-Key:' => 'XXXXX');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.parse.com/1/classes/XXXX');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
curl_setopt($ch, CURLOPT_HEADER, $fields);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt(CURLOPT_USERPWD, 'XXXXXX');
$result = curl_exec($ch);
curl_close($ch);
The interesting note is that when executed in the terminal authentication info is not required.
Help will be appreciated.
Thanks
Your header fields shouldn't have the : in the array defnition:
'X-Parse-REST-API-Key:' => 'XXXXX');
^---remove these
That makes the : part of the field name, so you're actually sending:
X-Parse-REST-API-Key:: XXXXX
^^---note the doubled colons
Your header is set using CURLOPT_HTTPHEADER, not CURLOPT_HEADER which expects a boolean value

Categories