Forums/Documentation/Developers

Zendesk REST API tutorial - PHP edition

Adam
posted this on May 21, 2012 16:03

In this tutorial, you'll create and use a PHP function that can create, read, update, or delete data on your Zendesk using the Zendesk REST API.

This article describes how to use the function as a simple PHP client, but there's also an official PHP client library. Check out this blog post for more details.

If you'd like to use Python or Perl instead, see the Python tutorial or the Perl tutorial.

Installing PHP on your computer

On a Mac, the setup is pretty simple. PHP is pre-installed. You don't need to do anything.

In Windows, the setup is trickier because you need to download and install PHP. You can use the all-in-one XAMPP installer from Apache Friends. XAMPP is an Apache web server distribution that includes both PHP and MySQL. Installing it is easy.

You can also get a stand-alone distribution of PHP from php.net. Click here for the most recent binaries for Windows. This option will require more configuration to get it to work with a local web server.

You'll need the command prompt to perform some of the setup tasks. To open the command prompt, open the Start Menu, type cmd in the search box, and press Enter.



Option 1 - Installing XAMPP for Windows

  1. Download and install XAMPP for Windows. See the instructions.

  2. Enable the cURL extension in PHP by uncommenting the following line (i.e., deleting the opening semi-colon) in the php.ini file in the \xampp\php folder:

    ;extension=php_curl.dll

  3. Start the Apache server with the XAMPP control panel (Start > Programs > Apache Friends > XAMPP > XAMPP Control Panel).
  4. Test the installation by navigating to the c:\xampp\php folder using the command prompt and entering the following PHP command:

    php --help

    If you get an error message, then something is not right. If you get a list of all the PHP options, then PHP is running normally.

Option 2 - Installing a stand-alone distribution of PHP

  1. Download the zip file from php.net or click here for the most recent binaries for Microsoft Windows, and extract it to C:\PHP so that the full path to php.exe is C:\PHP\php.exe.
  2. Update your path variable by entering the following command at the command prompt:

    SET PATH=%PATH%;C:\php

  3. Close and reopen the command prompt window.
  4. Test the installation by entering the following PHP command at the prompt:

    php --help

    If you get an error message, then something is not right. If you get a list of all the PHP options, then PHP is running normally.

Creating a PHP function to access the Zendesk API

In this section, you'll create a PHP function that can perform CRUD operations with the Zendesk REST API. CRUD stands for "Create, Read, Update, and Delete," the four basic API operations. The function relies on cURL, or Client URL Library, a PHP library that lets you connect to and communicate with many different types of servers with many different types of protocols.

To create the function

  1. In a text editor, create a new document and save it as script.php.
  2. Paste the following code in your document. This curl wrapper makes it easier to talk to Zendesk by only requiring you to call one function and have it set all the necessary properties.

  3. Specify values for the following variables:
    • ZDAPIKEY - Specify your API key. The key is listed in Zendesk on the Channels/API page (Admin > Channels > API)
    • ZDUSER - Specify your email address registered with Zendesk
    • ZDURL - Replace "subdomain" in the URL with the subdomain of your Zendesk account. For example, if your URL is https://mondocam.zendesk.com, then replace subdomain with mondocam
  4. Call the curlWrap() function from your scripts. See the next section for details.

Accessing the Zendesk API with the function

Use your newly crafted curlWrap() function to access resources in the Zendesk REST API. The function's specification is as follows:

curlWrap(url, json_payload, action)


The function takes the following arguments:

  • url - Specifies the path of the endpoint after https://{subdomain}.zendesk.com/api/v2. Example: "/groups/{id}/users.json". See the REST API documentation for the URLs you can use.
  • json_payload - Contains the data you want to put or post to Zendesk. Use null if you're not sending anything. The data must be JSON encoded. See "Packaging data for PUT or POST requests" below. 
  • action - Specifies the type of request. Valid values are 'GET', 'POST', 'PUT', and 'DELETE'.

For example, the following statement retrieves a list of recent tickets:

$data = curlWrap("/tickets/recent.json", null, "GET");


For POST or PUT requests, include your JSON-encoded data in the $json argument:

$data = curlWrap("/tickets.json", $json, "POST");


In the examples above, you'll get a variable called $data that contains the response. Because the function decodes the JSON data, the variable contains a PHP data structure, not JSON. See "Accessing data in the response" and "Packaging data for PUT or POST requests" below for more information.

See "Troubleshooting" if you run into problems.

Accessing data in the response

The curlWrap() function converts the JSON in the response into a PHP object and then returns it. To access the data in the object, first consult the Zendesk REST API docs to figure out the structure of the data. For example, according to the List Groups doc, the JSON returned by a call to the "list groups" endpoint has the following structure:

You can deduce from this information that the data returned by the function contains an object consisting of one property named 'groups'. The property contains a list of groups, with each item in the list consisting of an object describing a group. Armed with this information, you can access the information in the response. For example, the following PHP snippet calls the "list groups" endpoint and then accesses and prints the name of the first group (i.e., groups[0]) in the object:

$data = curlWrap("/groups.json", null, "GET");
print("First group = " . $data->groups[0]->name );

See Google for details about the differences between objects and arrays in PHP. The short version is that array values are accessed as array[index] and object properties are accessed as object->property.

Packaging data for PUT or POST requests

Before making a put or post request, you must package the data in a PHP data structure matching the structure of the JSON expected by the API. Then you must encode the data to JSON. Consult the REST API doc for the expected JSON. For example, if you want to create a ticket, the API expects the following JSON:

{ "ticket": { "subject: "My printer is on fire!", "comment": { "body": "The smoke is very colorful." }}}

Accordingly in PHP, package your data as nested associative arrays matching the JSON structure:

$subject = "My printer is on fire!";
$body = "The smoke is very colorful.";
$payload = array('ticket' => array('subject' => $subject, 'comment' => array('body' => $body)));

Next, encode the data structure to JSON:

$json = json_encode($payload);

You should always encode your data to prevent characters like quotes from breaking the JSON. For example, the quotes in the following body would prematurely end the string and cause an error: "body": "Learn <a href="faq.html">more</a>." Encoding the data escapes the quotes. Example: "Learn <a href=\"faq.html\">more</a>."

Finally, make the post request:

$data = curlWrap("/tickets.json", $json, "POST")

Troubleshooting

If you think something went wrong and you want to check the results of an API call, use the var_dump() function. Example:

<?php
$data = curlWrap("/users.json", null, "GET");
var_dump($data);
?>

To catch errors raised by the cURL library, locate the following statement in the curlWrap() function, $output=curl_exec($ch);, and then insert this statement after it:

echo 'Curl output: ' . curl_error($ch);

Make sure to comment out the line when you're done testing.

The first step in resolving a problem is to run the curl call on the command line. This tells you if there's something wrong with the URL or  credentials you're using. To install and use curl from the command line, see the curl website.  See the REST API documentation for sample CURL calls and credentials you can use. With each call, include the -v option (verbose) and include the output in the comments below if you want help from the forum. Before posting, please make sure you remove all passwords, API keys, and IP addresses from any comments, code, or attachments.

If the curl call returns JSON, then there's probably an issue with the PHP code. If you don't get anything, then a problem with the system configuration is more likely.

Several customers have gotten NULL responses when using the curlWrap() function. There are a lot of reasons why this may happen.

Windows XAMPP or WAMP problems

Windows is not the best operating system to develop on when it comes to PHP and cURL. The majority of people on Windows use XAMPP or WAMP (Windows-Apache-MySQL-PHP) and find that the cURL library is not enabled by default. If you use XAMPP for Windows, make sure you enable curl as described in this stackoverflow.com answer.

CA certificate errors

Several Windows users have issues with their root certificates. The problem is usually identified when testing with curl_error($ch) -- see above. Ensure your CA root certificates are up to date. This can be done by running Windows Update. If you find that after updating you're still having issues with null values being returned, do the following:

  1. Go to http://curl.haxx.se/docs/caextract.html and download the cacert.pem file.
  2. Add the following line to the curlWrap() function definition:
    curl_setopt($ch, CURLOPT_CAINFO, "C:/cacert.pem");
  3. Make sure that the C: path listed above points to the file you downloaded in step 1. Use forward slashes even if Windows uses backslashes.

If you're still having trouble, you're welcome to post a comment here. If you're a Zendesk customer, you can submit a ticket to support@zendesk.com.

 

Commenters below! Before posting, please make sure you remove all passwords, API keys, and IP addresses from any comments, code, or attachments.

 

Comments

User photo
Antonio Carranza López

Seems to be incomplete example.

$data = curlWrap("/tickets.json", $json, "POST");

what is $json? seems to be an array of fields but how to define it?

curl_setopt($ch, CURLOPT_POSTFIELDS, $json);


June 21, 2012 07:26
User photo
Adam
Zendesk

Hi Antonio,

 

The $json is if you want to post or put or some data to the API. In order to post or put you need to include the data you are sending (in the JSON format). You can post JSON in PHP by using JSON_ENCODE. Take a look at this article: http://php.net/manual/en/function.json-encode.php

 

Hope this helps,

 

Love Your Zendesk - The Fastest Way to Great Customer Support!

Adam Panzer | Customer Advocate | support@zendesk.com

June 21, 2012 07:41
User photo
Antonio Carranza López

I tryed it but:

$arr = array("subject"=>"Help, my printer is on fire!",
"description"=>"help I need some help",
"recipient"=>"support@company.com"
);

$json = json_encode($arr);

print $json;

$data = curlWrap("/tickets.json", $json, "POST");

var_dump($data);

 

the response was:

{"subject":"Help, my printer is on fire!","description":"help I need some help","recipient":"support@company.com"}object(stdClass)#1 (3) {
["error"]=>
string(13) "RecordInvalid"
["description"]=>
string(24) "Record validation errors"
["details"]=>
object(stdClass)#2 (1) {
["base"]=>
array(1) {
[0]=>
object(stdClass)#3 (2) {
["type"]=>
string(38) "Descripción: no puede estar en blanco"
["description"]=>
string(43) "Base Descripción: no puede estar en blanco"
}
}
}
}

June 21, 2012 08:06
User photo
Adam
Zendesk

Here is a sample:

 

$create = json_encode(array('ticket' => array('subject' => $arr['z_subject'], 'description' => $arr['z_description'], 'requester' => array('name' => $arr['z_name'], 'email' => $arr['z_requester']))), JSON_FORCE_OBJECT);

 

What's the difference?

If you look at what you output from your JSON create:

{"subject":"Help, my printer is on fire!","description":"help I need some help","recipient":"support@company.com"}

Compare that to what my output is:

{"ticket": { "subject": "subject", "description": "description", "requester": { "name": "name", "email": "email@example.com"}}}

Hope this helps,

 

Love Your Zendesk - The Fastest Way to Great Customer Support!

Adam Panzer | Customer Advocate | support@zendesk.com

June 21, 2012 08:13
User photo
Antonio Carranza López

Thanks a lot, now its working fine. So complete code is attached for helping others.

 

Thanks,

June 21, 2012 08:47
User photo
Daniel Baah

how do I edit my post...

July 06, 2012 22:16
User photo
Adam
Zendesk

Hi Daniel,

 

Two things: 

 

1.) You are using a put on /tickets.json. You want to use a GET since you are GETting the list of tickets not modifying them. 

2.) I will delete your post and recreate it without the attachment for security reasons

3.) please regenerate your API key as it was visible publicly. 

4.) Yes, you use your email address that is attached to the admin account that you are using to access the API. 

 

Original Post:

 

A couple questions: f

under ZDUSER: do you just want our email we use to log in? so like 

define("ZDUSER", "sam@me.com"); would work??

Also, Im having trouble getting this to run... So Im trying to print out all of the current ticket id's that I have.. Could you guys check out my file and see what Im doing incorrectly?

 

Code posted:

$data = curlWrap("/tickets.json", null, "PUT");

foreach($data in $tickets){

print $tickests->tickets->id . "</br>";

}

July 10, 2012 10:19
User photo
Adam
Zendesk

also, re-reading this, you spelled tickets wrong in your for loop.

July 12, 2012 12:00
User photo
Jose Ortiz
tcicollege

I'm new to this and was wondering where do I generate my api key kinda lost here

July 17, 2012 05:32
User photo
Adam
Zendesk

Hi Jmortiz,

 

I saw that you submitted a ticket on this question. Do you still need me to follow up? If so, you can go to settings -> channels -> api to generate an api key.

 

Love Your Zendesk - The Fastest Way to Great Customer Support!

Adam Panzer | Customer Advocate | support@zendesk.com

July 17, 2012 08:50
User photo
Jose Ortiz
tcicollege

thank you I found my api key

now I have the issue where it not creating the ticket

my output is

{"ticket":{"subject":"testing","description":"312PPrinter is having the following problem: test","requester":{"name":"Jose Ortiz","email":"email@example.com"}}}{"ticket":{"subject":"testing","description":"312PC26 is having the following problem: test1","requester":{"name":"Jose Ortiz","email":"email@example.com"}}}

but I never see a ticket being created

July 17, 2012 10:56
User photo
Adam
Zendesk

You have two of the same json strings stuck together, but submitting this: 

{"ticket":{"subject":"testing","description":"312PC26 is having the following problem: test1","requester":{"name":"Jose Ortiz","email":"emailaddress"}}}

should work. I removed your email address from both this post and your post you included above. 

 

July 17, 2012 11:01
User photo
Jose Ortiz
tcicollege

so if I can't send multiple arrays

like if I have multiple tickets to create at one time?

July 17, 2012 11:10
User photo
Jose Ortiz
tcicollege

The app I am making a person can drag a machine or multiple machines into our problem section

write what is wrong for each one and send it.

what I want to do is for each one that is that area create a ticket for each one

does that make sense?

July 17, 2012 11:14
User photo
Adam
Zendesk

Each ticket creation needs to be a separate request. 

July 17, 2012 11:16
User photo
Adam
Zendesk

Jose: I removed your original post because you included your api key. Here is what you wrote:

I modified it now my var_dump is

string(165) "{"ticket":{"subject":"testing","description":"312PPrinter is having the following problem: test","requester":{"name":"Jose Ortiz","email":"jmortiz@tcicollege.edu"}}}" 
string(162) "{"ticket":{"subject":"testing","description":"312PC27 is having the following problem: test1","requester":{"name":"Jose Ortiz","email":"jmortiz@tcicollege.edu"}}}"

 

I attached my php file

July 17, 2012 11:24
User photo
Jose Ortiz
tcicollege

oops sorry

so it seems no matter what I create it will not ever send the ticket with multiple request

even if I make a foreach statement

July 17, 2012 12:30
User photo
Adam
Zendesk

Hi Jose,

You can do a foreach statement but you need to put the everything that isn't the curlWrap function in that statement. See below:

foreach(xyz as abc){
$arr = array("z_subject"=>"testing",
	   "z_description"=>$valname . " is having the following problem: " . $problem[$key],
	   "z_recipient"=>"bob@example.com",
	   "z_name"=>"Jose Ortiz",
	   "z_requester"=>"example@example.com"
	  );
$create = json_encode(array('ticket' => array('subject' => $arr['z_subject'], 'description' => $arr['z_description'], 'requester' => array('name' => $arr['z_name'], 'email' => $arr['z_requester']))), JSON_FORCE_OBJECT);
$data = curlWrap("/tickets.json", $create, "POST");
var_dump($create);
print $data->ticket->id. "
"; print "\n"; }

Understand that when you call curlWrap you actually execute the statement. For each ticket you wish to create you need to execute curlWrap with the individual ticket json.

July 17, 2012 12:46
User photo
Jose Ortiz
tcicollege

so I create a new foreach inside the foreach that I already have?

 

foreach($blah ad $key => $valname){
foreach(xyz as abc){
$arr = array("z_subject"=>"testing", "z_description"=>$valname . " is having the following problem: " . $problem[$key], "z_recipient"=>"bob@example.com", "z_name"=>"Jose Ortiz", "z_requester"=>"example@example.com" ); $create = json_encode(array('ticket' => array('subject' => $arr['z_subject'], 'description' => $arr['z_description'], 'requester' => array('name' => $arr['z_name'], 'email' => $arr['z_requester']))), JSON_FORCE_OBJECT); $data = curlWrap("/tickets.json", $create, "POST"); var_dump($create); print $data->ticket->id. "
"; print "\n";
}
}
July 17, 2012 13:01
User photo
Farid Jamae

I am putting the correct API key, user (email address), and the url, but I keep getting back "

Couldn't authenticate you

". Any idea what I might be missing?

July 24, 2012 07:48
User photo
Farid Jamae

I had to use a sandbox url, now I'm able to connect. However, the following call results in "NULL" being returned, even though I can see that there are at least 2 unresolved tickets: 

$data = curlWrap("/tickets.json", null, "GET");

var_dump($data); //this returns as NULL

July 24, 2012 08:55
User photo
Adam
Zendesk

Make sure you have token based authentication turned on by going to channels -> api 

Are you able to pull in a result if you just look the ticket up by ID number? In other words, can you actually get a result if you go to [zd].zendesk.com/api/v2/tickets/123.json?

July 24, 2012 08:56
User photo
Farid Jamae

Hi Adam, thanks for replying. Trying to visit that URL that you sent me, it asks me for username/password. I couldn't get in using my sandbox username and password. 

And on a different note, I'm able to use /views/active.json to get all my views and loop through them and just print out the specific view (unresolved tickets) that I need. However, trying to only call the specific view also results in null as well, i.e. /views/123.json

July 24, 2012 09:19
User photo
Adam
Zendesk

That wasn't *technically* a link. You were supposed to replace [zd] with your zendesk instance and use that in your php script. 

If you are able to get something back from the API then you're doing it right in terms of using PHP and CURL. Now you just need to carefully read the API documentation. Make sure that you have the right method (POST/PUT/GET/DELETE) and make sure you are sending the correct JSON. 

Also test your calls in the command line as well before testing PHP.

July 24, 2012 09:25
User photo
Farid Jamae

Hi Adam, sorry for the multiple questions. 

I am able to get a single view when I use this url: [zd].zendesk.com/api/v2/views/123.json?

However, using this returns null: /views/123.json

*I'm using a sandbox account, so in the function, my ZDURL is defined as https://[zd]12345.zendesk.com

July 24, 2012 10:50
User photo
Adam
Zendesk

@farid: are you using the define statements?

July 24, 2012 10:53
User photo
Farid Jamae

Yes kinda. I actually converted that function file into a class, so I'm using const ZDURL = "https://......", but I can verify that my constant is correctly passed in the class by echoing out self::ZDURL.$url

July 24, 2012 11:03
User photo
Adam
Zendesk

I would say that converting it to a class presents it's own issues and while you're welcome to make changes, I would suggest using the code as-is first, verifying that everything works. In my opinion, it seems, that your define statement isn't working. To get more details try the following:

 

Add a curl setopt for verbose:

curl_setopt($ch, CURLOPT_VERBOSE, 1);

And run the PHP file from the command by doing:

php -f <filename>

Let me know if this helps

Love Your Zendesk - The Fastest Way to Great Customer Support!

Adam Panzer | Customer Advocate | support@zendesk.com

July 24, 2012 11:08
User photo
Farid Jamae

Thanks Adam. Looks like I wasn't defining my ZDURL correctly: 

I had it like this: https://[zd].zendesk.com

Changed it to this: https://[zd].zendesk.com/api/v2

Everything seems to be working now

July 24, 2012 11:45
User photo
Adam
Zendesk

Glad I could help!

July 24, 2012 11:46
User photo
Nicholas Richard

Heya,

I'm having an issue grabbing the information off the .json results. For instance, I'm trying to grab the list of users off my [zd].zendesk.com/api/v2/users.json, and make a drop down list to select a specific user. However, my $data always comes back as NULL. 

This is what I'm using:

function zGetUsers($type)
{
if($type=='0'){
// Select specific user
$data = curlWrap("/users.json", null, "GET");
var_dump($data); // THIS RETURNS NULL
foreach($data as $users){
print $users->id . "<br />";
}

//print "User ids:".$data;
} else if($type=='1'){
// Select group
$data = curlWrap("/groups.json", null, "GET");
//print "1";
} else {
// Show Error
print $error["z1"];
}
}

August 03, 2012 08:40
User photo
Adam
Zendesk

@Nicholas, without posting your credentials, can you post the curlwrap script you are using and the defines (sans password)?

August 03, 2012 09:11
User photo
Nicholas Richard

Sure thing:

define("ZDAPIKEY", "[API KEY]");
define("ZDUSER", "[USER EMAIL]");
define("ZDURL", "https://[URL].zendesk.com/api/v2");

function curlWrap($url, $json, $action)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_MAXREDIRS, 10 );
curl_setopt($ch, CURLOPT_URL, ZDURL.$url);
curl_setopt($ch, CURLOPT_USERPWD, ZDUSER."/token:".ZDAPIKEY);
switch($action){
case "POST":
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
break;
case "GET":
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
break;
case "PUT":
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
default:
break;
}
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
curl_setopt($ch, CURLOPT_USERAGENT, "MozillaXYZ/1.0");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$output = curl_exec($ch);
curl_close($ch);
$decoded = json_decode($output);
return $decoded;
}

August 03, 2012 10:18
User photo
Adam
Zendesk

@Nicholas, can you run a phpinfo(); command and tell me if CURL and JSON are included in your PHP install?

August 03, 2012 10:19
User photo
Nicholas Richard

curl

cURL support enabled
cURL Information 7.20.0

json

json support enabled
json version 1.2.1

--------------

I should probably add that I'm running this on a WAMP server.

August 03, 2012 10:59
User photo
Kurtis Gibson
quincy

@Adam

Having the same trouble as Nicholas -- testing $data with isset shows it isn't being set at all.

August 07, 2012 09:53
User photo
Adam
Zendesk

@kg are you also on a windows server platform?

@Nicholas, can you try running this script from the command line and not the web server (ie: php -f <filename>)?

August 07, 2012 10:03
User photo
Kurtis Gibson
quincy

@adam

No, Linux.

August 07, 2012 10:04
User photo
Adam
Zendesk

@kg can you turn on verbose logging and see what's going on? 

 

curl_setopt($ch, CURLOPT_VERBOSE, 1);
August 07, 2012 10:05
User photo
Kurtis Gibson
quincy

@Adam

Sure, here are the results:

(Header information removed, of course)

< HTTP/1.1 500 Internal Server Error
< Server: nginx/1.0.15
< Date: Tue, 07 Aug 2012 17:46:33 GMT
< Content-Type: text/html
< Transfer-Encoding: chunked
< Connection: keep-alive
< Status: 500 Internal Server Error

August 07, 2012 10:47
User photo
Adam
Zendesk

Can you try outputting the JSON and using that in a command line curl call (see the developer documentation if you aren't familiar how to do this).

August 07, 2012 10:50
User photo
Kurtis Gibson
quincy

@Adam

If I use curl it is successful:

curl -u [email removed]/token:[Token removed] https://helpdesk.[domain removed]/users/current.json

yields:

{"created_at": ... through ... "uses_12_hour_clock":true}

We do use a custom dns name of helpdesk.domain.name rather than prefix.zendesk.com -- but that doesn't seem to matter to either curl or the php code.  The JSON I am using is identical, just a simple:

$data = curlWrap("/users/current.json", null, "GET");


Thanks for your help.

August 07, 2012 10:58
User photo
Adam
Zendesk

@kg Just to be clear, we are talking API V2 right? Because the endpoint for that is 

 

GET /api/v2/users/me.json


So you're $data = would be 


$data = curlWrap("/users/me.json", null, "GET");

August 07, 2012 11:01
User photo
Kurtis Gibson
quincy

@Adam

Yes, v2 set as so:

define("ZDAPIKEY", "[API key removed]");
define("ZDUSER", "[email address removed]");
define("ZDURL", "https://helpdesk.domain.name/api/v2");

August 07, 2012 12:42
User photo
Adam
Zendesk

@kg do you still get a null result when you do $data = curlWrap("/users/me.json", null, "GET");

August 07, 2012 13:18
User photo
Kurtis Gibson
quincy

@Adam

Yes, unfortunately.

August 07, 2012 13:20
User photo
Cesar
cazoomi

@Adam

I also get the same output as @kg.  Has anyone figured out what the problem is?  Thanks!

August 09, 2012 07:49
User photo
Kurtis Gibson
quincy

@Cesar

The fix for me was to ensure the line:

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));

 was/is all on one line -- when I copied and pasted the code, the length of the line caused it to go on two lines instead of one.

Hope that helps.

August 09, 2012 07:51
User photo
Cesar
cazoomi

@kg

Nope, that is already in a single line on my end.  Thanks for sharing. :)

August 09, 2012 08:04
User photo
Adam
Zendesk

@Cesar, are you running WAMP? If you don't know what it is then the answer is likely no. Can you tell me what your environment is?

August 09, 2012 09:38
User photo
Cesar
cazoomi

@Adam

I'm running XAMPP on my local machine.  Anyway, I've already figured out the problem.  Thanks! :)

August 09, 2012 10:04
User photo
Julien Blot
totalnorth

@Adam

Hi, I am trying to use your PHP function, but when I do :

$data = curlWrap("/tickets/recent.json", null, "GET");

var_dump($data);

I get the NULL result.

I am pretty confident my API Key, username and URL are correct.

Any IDEA ?

August 10, 2012 14:27
User photo
Adam
Zendesk

@julien have you tried using verbose curl?

curl_setopt($ch, CURLOPT_VERBOSE, 1);

Also, remember to check the JSON output to make sure it's correct. I usually recommend customers try and post the JSON generated by their PHP via CURL directly first then do the php curl second. 

Finally, make sure if you are running WAMP that you have it enabled properly (http://www.phpmind.com/blog/2011/02/how-to-enable-curl-in-wamp/)

If after all that, you are still having trouble, let's get a ticket started and work on this directly.

August 10, 2012 14:45
User photo
Julien Blot
totalnorth

Thanks for the quick answer.

I am not familiar with curl or json. I am using IIS7 with PHP module. I checked phpinfo() and both curl and json are enabled.

When i put the url https://DOMAIN.zendesk.com/api/v2/tickets/recent.json in my browser i get the correct output.

How can I check the verbose from curl ? and i am not too sure what you mean by the JSON generated by the PHP via curl directly then php curl second ?

Thanks

August 10, 2012 14:55
User photo
Wim La Haye

(Message from author): WARNING: Please do not turn off SSL verify in your script, ie, do not set ssl verify to false.

Hi Adam,

 

I tried using the example script, but keep receiving: "

This is a JSON only API. Please specify the correct Accept header.

 

I use a slightly modified version of your script, because i was receiving an error on the SSL cert. I've attached the script i use.

 

The full curl debug is listed below. I get the same respons wether i call the script via php -f or via the browser.

Do you have any ideas as to what i might change to 'specify the correct header'?

 

Thanks,

 


* About to connect() to <url>.zendesk.com port 443 (#0)
* Trying 108.166.31.242...
* connected
* Connected to <url>.zendesk.com (108.166.31.242) port 443 (#0)
* SSL connection using RC4-SHA
* Server certificate:
* subject: C=US; postalCode=94107; ST=California; L=San Francisco; street=410 Townsend St; O=Zendesk; OU=Zendesk; OU=PremiumSSL Wildcard; CN=*.zendesk.com
* start date: 2011-09-07 00:00:00 GMT
* expire date: 2014-09-06 23:59:59 GMT
* subjectAltName: <url>.zendesk.com matched
* issuer: C=GB; ST=Greater Manchester; L=Salford; O=COMODO CA Limited; CN=COMODO High-Assurance Secure Server CA
* SSL certificate verify result: self signed certificate in certificate chain (19), continuing anyway.
* Server auth using Basic with user '<email>/token'
> GET /api/v2/search.json%3Fquery%3Dorder_by%3Aupdated_at+sort%3Aasc+type%3Aticket+updated%3E1970-01-01 HTTP/1.1
Authorization: Basic <key>==
User-Agent: MozillaXYZ/1.0
Host: <url>.zendesk.com
Accept: */*
Content-type: application/json

< HTTP/1.1 415 Unsupported Media Type
< Server: nginx/1.0.15
< Date: Sat, 11 Aug 2012 19:24:34 GMT
< Content-Type: text/html; charset=utf-8
< Connection: keep-alive
< Status: 415 Unsupported Media Type
< Cache-Control: no-cache
< X-Zendesk-API-Version: v2
< X-Runtime: 38
< Content-Length: 66
<
* Connection #0 to host <url>.zendesk.com left intact
* Closing connection #0

 

<?php

function call($url, $json = '', $action = 'GET')
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_MAXREDIRS, 10 );

// Added urlencode() to prevent a "HTTP/1.1 400 Bad Request" respons
curl_setopt($ch, CURLOPT_URL, 'https://techtwohelpdesk.zendesk.com/api/v2/'.urlencode($url));
curl_setopt($ch, CURLOPT_USERPWD, '<REDACTED>');

switch($action){
case "POST":
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
break;
case "PUT":
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
case "GET":
default:
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
break;
}

curl_setopt($ch, CURLOPT_USERAGENT, "MozillaXYZ/1.0");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_STDERR, fopen(dirname(__FILE__) . '/debug.txt', 'w'));

// Tried both:
//curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json', 'Accept: application/json'));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));

// Added this because i was receiving "SSL certificate problem, verify that the CA cert is OK"
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

$output = curl_exec($ch);
curl_close($ch);

var_dump($output);

$decoded = json_decode($output);
return $decoded;
}

$updated = '1970-01-01';
$url = 'search.json?query=order_by:updated_at sort:asc type:ticket updated>' . $updated;
var_dump(call($url));

August 11, 2012 12:31
User photo
Ted Barnum
Zendesk

Friendly Reminder:

! Please scan your code for User names , email addresses, Passwords, Tokens or anything personal Before Posting, to remove that information ! 

 :)

August 11, 2012 13:04
User photo
Adam
Zendesk

While the urlencode is a good addition, understand that turning off ssl verify is not recommended. You need to keep that on.

Another customer had this issue previously and after running windows update (or whatever update on your OS) and updating the root certificates on his machine he was able to verify our certificates. I'm putting a disclaimer above your code because setting ssl verify to false is not advisable. 

To add multiple headers you'll want to use this format ( FROM http://bit.ly/Npl2D7)

curl_setopt($ch,CURLOPT_HTTPHEADER,array('HeaderName: HeaderValue','HeaderName2: HeaderValue2'));

 

You need both the correct content-type and accept header (they both have the same value: application/json)

My other suggestion is to try your commands out at hurl.it first then get the code working.

August 11, 2012 18:51
User photo
Julien

Hi Adam,

Thanks for your work, turned it into a little class :

https://github.com/ludwigzzz/Zendesk-API

August 20, 2012 07:15
User photo
sanjay Sethi
shopcluescom

Has anybody tried, updating ticket using above method. I am trying using php but no success. Please suggest

 

<?PHP
define("ZDAPIKEY", "token");
define("ZDUSER", "xyz@abc.com");
define("ZDURL", "https://abc.zendesk.com/api/v2");

/* Note: do not put a trailing slash at the end of v2 */

function curlWrap($url, $json, $action)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_MAXREDIRS, 10 );
curl_setopt($ch, CURLOPT_URL, ZDURL.$url);
curl_setopt($ch, CURLOPT_USERPWD, ZDUSER."/token:".ZDAPIKEY);
switch($action){
case "POST":
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
break;
case "GET":
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
break;
case "PUT":
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
default:
break;
}
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
curl_setopt($ch, CURLOPT_USERAGENT, "MozillaXYZ/1.0");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$output = curl_exec($ch);
curl_close($ch);
$decoded = json_decode($output);
return $decoded;
}

$arr = array("z_description"=>"help I need some help");
$update = json_encode(array('ticket' => array('description' => $arr['z_description'])));
$data = curlWrap("/tickets/42320.json", $update, "PUT");
var_dump($data);

print $data->ticket->id;
print "\n";
?>

September 19, 2012 06:24
User photo
Adam
Zendesk

What's the output/return from all this? Are you getting a 422 (http response) or 200?

September 20, 2012 09:39
User photo
Benoit
easyneo

Hi Adam,

I am currently testing the php API with WAMP (curl Extension active).

Im am not familiar with curl and json, hope you can help me.

I am using the same code as you I just changed this variables :

define("ZDAPIKEY", "XXXX");
define("ZDUSER", "benoit@company.net");
define("ZDURL", "https://company.zendesk.com/api/v2");

And added this at the end :

$data = curlWrap("/tickets.json", null, "GET");
echo var_dump($data);

Unfortunately it returns just NULL.

I tried to add :

echo var_dump(curl_getinfo($ch, CURLINFO_HEADER_OUT));

==> boolean false

And to add curl_setopt($ch, CURLOPT_VERBOSE, 1);

Without any changes ...

Do you have any idea ?

Thanks,

BR

October 09, 2012 08:53
User photo
Adam
Zendesk

Hi, which version of PHP are you running?

October 09, 2012 09:31
User photo
Ryan Kiel

Zendesk, please don't link to random github scripts as this one is incomplete and is causing the same NULL issue me and a number of other people had.. The sample script is posting to https:// and most people have curl installs that have outdated ways of handling SSL.. I spent about 4 hours on this issue till I finally ran across this answer

http://stackoverflow.com/a/316732

If you're getting null, you have to get a pem script and set the option in curl to use it.. Please click the link for the correct answer to this problem.. Hopefully Zendesk updates its PHP example script.

October 09, 2012 23:02
User photo
Benoit
easyneo

@Adam : Thanks for this quick answer !

@Ryan, I had the same problem, thx for this answer !

I just had to dl this certificate : http://curl.haxx.se/ca/cacert.pem

And to add this in the php code :

    curl_setopt($ch, CURLOPT_CAINFO, "C:/cacert.pem");

The code is now working perfectly !

October 10, 2012 00:24
User photo
Adam
Zendesk

Hi Ryan, 

 

I'm sorry you had such difficulties with the script though I am glad you found the answer. It would never have occurred to me that this was the problem as, working on a mac, I've never encountered this issue. 

In regards to "random github scripts" which ones are you referring to? There are several github gists which are not scripts in-and-of-themselves, and there are a few customers who have included their own work as well. 

October 10, 2012 07:54
User photo
Shawn Westerhoff
nexxo

Hi Adam:

Great work on this, but I wonder if you could clarify what a single php file would look like, I cannot get the json output to parse correctly.  I am using:

<?php
define("ZDAPIKEY", "XXX");
define("ZDUSER", "XXX");
define("ZDURL", "https://XXX.zendesk.com/api/v2");


/* Note: do not put a trailing slash at the end of v2 */

function curlWrap($url, $json, $action)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_MAXREDIRS, 10 );
curl_setopt($ch, CURLOPT_URL, ZDURL.$url);
curl_setopt($ch, CURLOPT_USERPWD, ZDUSER."/token:".ZDAPIKEY);
switch($action){
case "POST":
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
break;
case "GET":
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
break;
case "PUT":
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
break;
case "DELETE":
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
break;
default:
break;
}

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
curl_setopt($ch, CURLOPT_USERAGENT, "MozillaXYZ/1.0");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$output = curl_exec($ch);
curl_close($ch);
$decoded = json_decode($output);
return $decoded;
}
$data = curlWrap("/tickets.json", null, "GET");

var_dump($data)
// (tried this example, failed to parse) print($data->ticket->id);
?>

====
I am most interested in the output options if anyone has examples that works best.  I am looking initially for a very basic listing of open tickets in a specific org so once we see what the output should be we can begin to develop that and will post back our solutions.

October 10, 2012 16:01
User photo
Adam
Zendesk

Hi Nexxo,

 

Your question is a little confusing. The php file is the script.

 

Which version of PHP are you running? Older version do not support the json_decode method. 

October 10, 2012 16:03
User photo
Shawn Westerhoff
nexxo

All php requirements are met, I am just trying to test the script output, and can do so in the same file (one file, just one php file) So the php fiel should be able to output the info to the browser, right?  When I dump the info with var_dump I am getting json output, not decoded.  I understand this will be called from another file but thought I should be able to dump the $data to the browser from here.  If not, do you have an example of a php page that would call the script if that is the issue?

October 10, 2012 16:18
User photo
Shawn Westerhoff
nexxo

Environment is FreeBSD 9:

PHP Version 5.4.5
json support enabled
json version 1.2.1

cURL support enabled
cURL Information 7.24.0
Age 3
Features
AsynchDNS No
Debug No
GSS-Negotiate No
IDN No
IPv6 Yes
Largefile Yes
NTLM Yes
SPNEGO No
SSL Yes
SSPI No
krb4 No
libz Yes
CharConv No
Protocols dict, file, ftp, ftps, gopher, http, https, imap, imaps, pop3, pop3s, rtsp, smtp, smtps, telnet, tftp
Host amd64-portbld-freebsd9.0
SSL Version OpenSSL/0.9.8q
ZLib Version 1.2.5

October 10, 2012 16:21
User photo
Adam
Zendesk

Hmm. 

 

"When I dump the info with var_dump I am getting json output, not decoded."

 

I'm not sure what you mean? The "decoded" part is just a deserialized version of the output (or is it serialized?)

October 10, 2012 17:12
User photo
Shawn Westerhoff
nexxo

I am looking for general info on how to display tickets in a browser using the API.  During testing of the above php script we get the data (displayed in the browser) if we dump it with var_dump but we cannot display that in a clean, simple way yet.  Efforts to understand how to format it lead me to suppose we were not decoding the json correctly. So clearly I am missing a basic element.  In the event this is the script, and we would call the script from another page, I need an example of that page.  Does that make any more sense?  Happy to move to a ticket for this, then post more of a solution back here.

October 10, 2012 17:35
User photo
Adam
Zendesk

Hi Nexxo,

 

The styling of that data is up to you. All this script does is pull the raw data into the page. Using PHP to get everything in tables, for example, is on you. The goal of the API is to provide the data so that you can run your own representation.

October 10, 2012 17:41
User photo
Shawn Westerhoff
nexxo

OK, will do.  I assumed there would be a simple example, shall I post mine once we get somewhere?  Nobody has done this yet?

October 15, 2012 15:15
User photo
Adam
Zendesk

Hi Nexxo,

If you want to post a link to some code that would be fine but this is kind of outside the scope of the doc. You could also post it as a separate topic in the same forum. The comments on this post are already quite long so I want to limit it in scope of the current topic. 

 

Thanks

October 15, 2012 15:37
User photo
rasmi roy

Hi Adam,

I'm trying to send the value to one of the custom field in the ticket . But it doesn't populate in the custom field. Here is my code:

$url = '/tickets.json';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_MAXREDIRS, 10 );
        curl_setopt($ch, CURLOPT_URL, ZDURL.$url);
        curl_setopt($ch, CURLOPT_USERPWD, ZDUSER."/token:".ZDAPIKEY);
            
        $json = json_encode(array('ticket' => array('subject' => $ticket_obj[0],
            'description' => $ticket_obj[1],  
           'custom_fields' =>array(array('id'=>'21797287','value'=> $ticket_obj[2])))), JSON_FORCE_OBJECT);
        
        echo $json;
        curl_setopt($ch, CURLOPT_VERBOSE, 1);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
        curl_setopt($ch, CURLOPT_USERAGENT, "MozillaXYZ/1.0");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        $output = curl_exec($ch);
        if($output == FALSE) {
               return curl_error($ch);
        }
        curl_close($ch);
        $decoded = json_decode($output);
        return $decoded;

The system fields have been populating correctly, but the custom fields doesn't. Can you please explain how to send the values into the custom fields in the ticket using JSON format to Zendesk?

October 19, 2012 15:02
User photo
Adam
Zendesk

Take a look at the developer documentation at http://developer.zendesk.com
The script you are using was updated recently due to a change in how ticket submission works. We refactored it so you no longer use description in your JSON.

Hope this helps,

October 19, 2012 15:09
User photo
rasmi roy

Ok, But i need to know how to assign values into the custom_fields in the tickets using array in JSON . Right now, i'm using :

'custom_fields' =>array(array('id'=>'21797287','value'=> $ticket_obj[2]))

But it doesn't works. It's not populating in the specified custom field.

Thanks!

October 20, 2012 08:13
User photo
rasmi roy

The JSON encode function renders the output as below:

{"ticket":{"subject":"General Issue","description":"PHP test world","custom_fields":[{"id":21797287,"value":"6668889999"}]}}

I have no idea why it's not storing in the custom field in the Zendesk ticket.

October 21, 2012 09:07
User photo
Adam
Zendesk

Hi @rasmi: The description field is no longer. You need to use "comment": { "value": "blablablababl"}

October 22, 2012 15:45
User photo
rasmi roy

Hi Adam, I'm not asking about the comment field. I'm asking about the custom_field. Thanks!

October 23, 2012 09:10
User photo
Adam
Zendesk

Hi Rasmi,

I get that but you won't be able to submit the ticket if the comment field 
isn't correct. The custom fields look fine to me. Fix the other issues and 
the submission should work.

October 23, 2012 12:49
User photo
rasmi roy

Hi Adam,

I tried the comment field instead of the description field, but the custom_field still not populating. Here is the output:

{"ticket":{"subject":"General Issue","comment":{"value":"PHP test world"},"custom_fields":[{"id":21797287,"value":"6668889999"}]}}

The comment and subject fields have been populating correctly, but not the custom field.

October 24, 2012 10:55
User photo
Adam
Zendesk

@Rasmi: What happens if you run this as a straight curl call and skip PHP. 

October 24, 2012 10:57
User photo
rasmi roy

I'm attaching the screenshot of the configuration for my custom field here :

October 24, 2012 10:58
User photo
Adam
Zendesk

@rasmi: when you put the JSON in a straight curl call, from the command line, with no PHP, does it work? If it doesn't  do you see a place in the headers where it says it stripped out some of your parameters?

October 24, 2012 11:02
User photo
rasmi roy

Hi Adam,

Tried as per you said, but it's failing to authenticate . See below:

rroy@ip-10-0-0-251:~$ curl https://tdmobility.zendesk.com/api/v2/tickets.json \

>   -d '{\"ticket\":{\"subject\":\"$subject\", \"comment\": { \"value\":\"$comments\" }}}' \

>   -H \"Content-Type: application/json\" -v -u $email_address:$password -X POST

* About to connect() to tdmobility.zendesk.com port 443 (#0)

*   Trying 108.166.31.242... connected

* successfully set certificate verify locations:

*   CAfile: none

  CApath: /etc/ssl/certs

* SSLv3, TLS handshake, Client hello (1):

* SSLv3, TLS handshake, Server hello (2):

* SSLv3, TLS handshake, CERT (11):

* SSLv3, TLS handshake, Server finished (14):

* SSLv3, TLS handshake, Client key exchange (16):

* SSLv3, TLS change cipher, Client hello (1):

* SSLv3, TLS handshake, Finished (20):

* SSLv3, TLS change cipher, Client hello (1):

* SSLv3, TLS handshake, Finished (20):

* SSL connection using RC4-SHA

* Server certificate:

*        subject: C=US; postalCode=94107; ST=California; L=San Francisco; street=410 Townsend St; O=Zendesk; OU=Zendesk; OU=PremiumSSL Wildcard; CN=*.zendesk.com

*        start date: 2011-09-07 00:00:00 GMT

*        expire date: 2014-09-06 23:59:59 GMT

*        subjectAltName: tdmobility.zendesk.com matched

*        issuer: C=GB; ST=Greater Manchester; L=Salford; O=COMODO CA Limited; CN=COMODO High-Assurance Secure Server CA

*        SSL certificate verify ok.

* Server auth using Basic with user ''

> POST /api/v2/tickets.json HTTP/1.1

> Authorization: Basic Og==

> User-Agent: curl/7.22.0 (x86_64-pc-linux-gnu) libcurl/7.22.0 OpenSSL/1.0.1 zlib/1.2.3.4 libidn/1.23 librtmp/2.3

> Host: tdmobility.zendesk.com

> Accept: */*

> Content-Length: 81

> Content-Type: application/x-www-form-urlencoded

* upload completely sent off: 81out of 81 bytes

< HTTP/1.1 401 Unauthorized

< Server: nginx/1.0.15

< Date: Wed, 24 Oct 2012 20:10:21 GMT

< Content-Type: application/json; charset=utf-8

< Connection: keep-alive

< Status: 401 Unauthorized

* Authentication problem. Ignoring this.

< WWW-Authenticate: Basic realm="Web Password"

< Content-Length: 38

< X-Zendesk-Origin-Server: app32.sys.zendesk.com

{"error":"Couldn't authenticate you"}

* Connection #0 to host tdmobility.zendesk.com left intact

* getaddrinfo(3) failed for application:80

* Couldn't resolve host 'application'

* Closing connection #1

curl: (6) Couldn't resolve host 'application'

* Closing connection #0

* SSLv3, TLS alert, Client hello (1):

October 24, 2012 13:17
User photo
Adam
Zendesk

You are using a capital H when you need to use a small "h". It's dropping your header for content-type.

October 24, 2012 13:19
User photo
rasmi roy

Hi Adam,

It was my mistake. I forgot to remove the PHP variables from the curl command line. But i re-ran the command with appropriate values. It's still not populating the custom_field. Here is the output:

url https://tdmobility.zendesk.com/api/v2/tickets.json \
> -d '{"ticket":{"subject":"TEST TEST","comment":{"value":"Test World PHP"},"custom_fields":[{"id":21797287,"value":"111-222-7777"}]}}' \
> -H "Content-Type: application/json" -v -u {email}:{password} -X POST
* About to connect() to tdmobility.zendesk.com port 443 (#0)
*   Trying 108.166.31.242... connected
* successfully set certificate verify locations:
*   CAfile: none
  CApath: /etc/ssl/certs
* SSLv3, TLS handshake, Client hello (1):
* SSLv3, TLS handshake, Server hello (2):
* SSLv3, TLS handshake, CERT (11):
* SSLv3, TLS handshake, Server finished (14):
* SSLv3, TLS handshake, Client key exchange (16):
* SSLv3, TLS change cipher, Client hello (1):
* SSLv3, TLS handshake, Finished (20):
* SSLv3, TLS change cipher, Client hello (1):
* SSLv3, TLS handshake, Finished (20):
* SSL connection using RC4-SHA
* Server certificate:
*        subject: C=US; postalCode=94107; ST=California; L=San Francisco; street=410 Townsend St; O=Zendesk; OU=Zendesk; OU=PremiumSSL Wildcard; CN=*.zendesk.com
*        start date: 2011-09-07 00:00:00 GMT
*        expire date: 2014-09-06 23:59:59 GMT
*        subjectAltName: tdmobility.zendesk.com matched
*        issuer: C=GB; ST=Greater Manchester; L=Salford; O=COMODO CA Limited; CN=COMODO High-Assurance Secure Server CA
*        SSL certificate verify ok.
* Server auth using Basic with user 'rroy@tdmobility.com'
> POST /api/v2/tickets.json HTTP/1.1
> Authorization: Basic
> User-Agent: curl/7.22.0 (x86_64-pc-linux-gnu) libcurl/7.22.0 OpenSSL/1.0.1 zlib/1.2.3.4 libidn/1.23 librtmp/2.3
> Host: tdmobility.zendesk.com
> Accept: */*
> Content-Type: application/json
> Content-Length: 128
>
* upload completely sent off: 128out of 128 bytes
< HTTP/1.1 201 Created
< Server: nginx/1.0.15
< Date: Wed, 24 Oct 2012 21:12:49 GMT
< Content-Type: application/json; charset=utf-8
< Connection: keep-alive
< Status: 201 Created
< Cache-Control: no-cache
< X-Zendesk-API-Version: v2
< X-Zendesk-API-Warn: Removed restricted keys ["custom_fields"] from parameters according to whitelist
< Location: https://tdmobility.zendesk.com/api/v2/tickets/69.json
< X-Runtime: 415
< Content-Length: 3223
< X-Zendesk-Origin-Server: app14.sys.zendesk.com
< X-Zendesk-User-Id: 241001716
<
{"ticket":{"url":"https://tdmobility.zendesk.com/api/v2/tickets/69.json","id":69,"ext... TEST","description":"Test World PHP","priority":null,"status":"open","recipient":null,"requester_id":241001716,"submitter_id":241001716,"assignee_id":241001716,"organization_id":21876987,"group_id":20266067,"collaborator_ids":[],"forum_topic_id":null,"problem_id":null,"has_incidents":false,"due_at":null,"tags":["test"],"fields":[{"id":21551886,"value":""}],"custom_fields":[{"id":21551886,"value":""}],"satisfaction_rating":null},"audit":{"id":8480017522,"ticket_id":69,"created_at":"2012-10-24T21:12:49Z","author_id":241001716,"via":{"channel":"api","source":{"from":{},"to":{},"rel":null}},"metadata":{"system":{"client":"curl/7.22.0 (x86_64-pc-linux-gnu) libcurl/7.22.0 OpenSSL/1.0.1 zlib/1.2.3.4 libidn/1.23 librtmp/2.3","ip_address":"107.21.37.121","location":"Seattle, WA, United States","latitude":47.5839,"longitude":-122.2995},"custom":{}},"events":[{"id":8480017532,"type":"Comment","body":"Test World PHP","html_body":"<p>Test World PHP</p>","public":true,"trusted":true,"attachments":[]},{"id":8480017542,"type":"Create","value":"TEST TEST","field_name":"subject"},{"id":8480017552,"type":"Create","value":241001716,"field_name":"requester_id"},{"id":8480017562,"type":"Create","value":null,"field_name":"status"},{"id":8480017572,"type":"Create","value":null,"field_name":"priority"},{"id":8480017582,"type":"Create","value":null,"field_name":"type"},{"id":8480017592,"type":"Create","value":["test"],"field_name":"tags"},{"id":8480017602,"type":"Notification","via":{"channel":"rule","source":{"to":{},"from":{"id":28105477,"title":"Notify all agents of received request"},"rel":"trigger"}},"subject":"[{{ticket.account}}] {{ticket.title}}","body":"A ticket (#{{ticket.id}}) by {{ticket.requester.name}} has been received. It is unassigned.\nReview it by clicking the link below:\nhttp://{{ticket.url}}\n\n{{ticket.comments_formatted}}","recipients":[239987947,241001716,224232197]},{"id":8480017612,"type":"Notification","via":{"channel":"rule","source":{"to":{},"from":{"id":28105407,"title":"Notify requester of received request"},"rel":"trigger"}},"subject":"Request received: {{ticket.title}}","body":"Your request (#{{ticket.id}}) has been received and is being reviewed by our support staff.\n\nTo add additional comments, reply to this email or click the link below:\nhttp://{{ticket.url}}\n\n{{ticket.comments_formatted}}","recipients":[241001716]},{"id":8480017622,"type":"Change","via":{"channel":"rule","source":{"to":{},"from":{"id":31176238,"title":"Test"},"rel":"trigger"}},"value":241001716,"field_name":"assignee_id","previous_value":null},{"id":8480017632,"type":"Change","via":{"channel":"rule","source":{"to":{},"from":{"id":31176238,"title":"Test"},"rel":"trigger"}},"value":20266067,"field_name":"group_id","previous_value":null},{"id":8480017642,"type":"Change","via":{* Connection #0 to host tdmobility.zendesk.com left intact
* Closing connection #0
* SSLv3, TLS alert, Client hello (1):
"channel":"rule","source":{"to":{},"from":{"id":31176238,"title":"Test"},"rel":"trigger"}},"value":null,"field_name":"status","previous_value":null}]}}

October 24, 2012 14:18
User photo
Adam
Zendesk

< X-Zendesk-API-Warn: Removed restricted keys ["custom_fields"] from parameters according to whitelist

 

It's not custom_fields it's just fields

October 24, 2012 14:41
User photo
rasmi roy

Hi Adam,

It works!! Thank you so much for your assistance Adam. I really appreciate your tech support. Thanks!

October 25, 2012 07:11
User photo
Ousmane Ndia

I don't understand how to pass parameters into the request.. e.g : I want to get all tickets with open status...

how to ?

October 30, 2012 08:57
User photo
Ousmane Ndia

 In the browser with : search.json?query=type:ticket%20status:solved I can get the good results.

But with php it does not work : curlWrap("/search.json?query=type:ticket status:open", null, "GET");

October 31, 2012 03:55
User photo
rasmi roy

Hi Adam,

Is it possible to retrieve all the comments on a particular ticket from the Zendesk ? Right now, i'm getting only the first comment on the ticket.

Thanks!

November 08, 2012 12:51
User photo
Adam
Zendesk

take a look at the ticket audit records on developer.zendesk.com

November 08, 2012 13:08
User photo
rasmi roy

Ok, Thanks!

November 09, 2012 08:35
User photo
rasmi roy

Hi Adam,

Even if i have created a ticket as an end-user from our system, the Zendesk ticket comment field has been displaying as created by me. Can you please tell me why is that showing as created by me? How you're determining the requester is the end-user or agent? Based on the ip address or what else?

November 09, 2012 09:03
User photo
rasmi roy

Hi Adam,

Also i would like know how do get the author's name /requester name from the audit from the Zendesk.

November 09, 2012 11:51
User photo
Adam
Zendesk

Hi Rasmi, 

In regards to first question, you'll need to look at the requests endpoint to do what you want to do. In regards to the latter question, check the page on developer.zendesk.com and click on rest-api. Scroll down to the Side-Loading Beta for more details on how to achieve this.

November 09, 2012 11:59
User photo
matt r

I am having trouble with the example above simply dumping recent tickets json. The .php file runs fine via command line but running the script in a browser fails with a null result. I've combed through all of the above looking for a solution any other ideas?

November 12, 2012 22:44
User photo
matt r

Oh, I'm on a Mac running MAMP....

November 12, 2012 22:45