Craig Brass Systems Forum: Example Usage - Craig Brass Systems Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • This topic is locked

Example Usage

#1
User is offline   Craig Brass 

  • Staff - Managing Director and Chief Software Architect
  • PipPipPip
  • Group: Management
  • Posts: 349
  • Joined: 17-January 07
Below are two examples demonstrating using the API to get a list of tickets. The first example shows how to use the native PHP class, and the second example shows how to use the SOAP interface.

Native PHP Class

Note: Because Kayako relies on global variables, the below code <b>cannot be used inside a function or class</b>. As such, its use is extremely limited - you will be much better off using the SOAP interface.

<?php

$username = 'username'; //Username for Integration API as defined in /lib/config.php
$password = 'password'; //Password for Integration API as defined in /lib/config.php

require './helpdesk/integrationapi/lib/api.class.php';

$params = array($username,
				$password,
				//Email address of the Kayako user to get tickets for
				'someone@example.com',
				//Number of tickets to show per page
				5,
				//Page number. 1 displays tickets 1-5; 2 displays 6-10; etc.
				1,
				//Column to sort by (lastactivity, lastreplier, ticketstatusid,
				// priorityid, departmentid)
				'lastactivity',
				//TRUE to sort in ascending order, FALSE to sort in descending order
				false
				);
$result = call_user_func_array(array('CBS_KayakoAPI','getSubmittedTickets'), $params);

if ($result < 0) {
	//The API threw an error
	switch ($result->detail) {
		case -1: "The API username and password that you used are not valid"; break;
		case -2: "An invalid email address was supplied"; break;
		case -3: "A non-existent user was specified"; break;
		case -4: "The number per page is not numeric"; break;
		case -5: "The page number is not numeric"; break;
		case -6: "An invalid 'sort-by' field was specified (must be one of: lastactivity, lastreplier, ticketstatusid, priorityid, departmentid)"; break;
		case -7: "An incorrect password type was specified (must be 1 or 0)"; break;
		case -8: "An invalid department ID was specified"; break;
		case -9: "An invalid priority ID was specified"; break;
		case -10: "Required ticket information was missing"; break;
		case -11: "Required comment information was missing"; break;
		case -12: "The reply specified was empty"; break;
		case -13: "The specified ticket could not be found"; break;
		case -14: "The requested ticket is not owned by the specified user"; break;
		case -15: "The new email address specified is already in the database"; break;
		case -16: "Both status and priority were empty"; break;
		case -17: "A non-existent status was specified"; break;
		case -18: "A non-existent priority was specified"; break;
		case -19: "The specified attachment could not be found"; break;
		case -20: "The specified category could not be found"; break;
		case -21: "The specified article could not be found"; break;
		case -22: "The API was unable to fetch the submitted attachment"; break;
		case -23: "A non-existent custom field group was specified"; break;
		case -24: "A non-existent custom field was specified"; break;
		case -25: "An empty value was specified for a custom field marked as \"required\""; break;
		case -26: "An incorrect typeid (ticket ID) value was specified"; break;
		default:
			$msg = 'Unknown Error';
	}
	trigger_error("Kayako API Error: $msg", E_USER_ERROR);
} else {
	//Our request was successful. $result now contains an array of submitted tickets
	?>
	<h1>Successful Request</h1>
	<h2>Submitted Tickets:</h2>
	<pre><?php print_r($result); ?></pre>
	<?php
}

?>


SOAP Interface
<?php

$url = 'http://www.yourdomain.com/helpdesk/integrationapi/index.php?wsdl'; //URL to Integration API
$username = 'username'; //Username for Integration API as defined in /lib/config.php
$password = 'password'; //Password for Integration API as defined in /lib/config.php

require './nusoap/nusoap.php';
$nuSoapClient = new nusoap_client($url, 'wsdl');

function call($method, $params) {
	global $nuSoapClient;
	$result = $nuSoapClient->call($method, $params);
	if ($nuSoapClient->fault) {
		//The API threw an error
		switch ($result['detail']) {
			case -1: $msg = "The API username and password that you used are not valid"; break;
			case -2: $msg = "An invalid email address was supplied"; break;
			case -3: $msg = "A non-existent user was specified"; break;
			case -4: $msg = "The number per page is not numeric"; break;
			case -5: $msg = "The page number is not numeric"; break;
			case -6: $msg = "An invalid 'sort-by' field was specified (must be one of: lastactivity, lastreplier, ticketstatusid, priorityid, departmentid)"; break;
			case -7: $msg = "An incorrect password type was specified (must be 1 or 0)"; break;
			case -8: $msg = "An invalid department ID was specified"; break;
			case -9: $msg = "An invalid priority ID was specified"; break;
			case -10: $msg = "Required ticket information was missing"; break;
			case -11: $msg = "Required comment information was missing"; break;
			case -12: $msg = "The reply specified was empty"; break;
			case -13: $msg = "The specified ticket could not be found"; break;
			case -14: $msg = "The requested ticket is not owned by the specified user"; break;
			case -15: $msg = "The new email address specified is already in the database"; break;
			case -16: $msg = "Both status and priority were empty"; break;
			case -17: $msg = "A non-existent status was specified"; break;
			case -18: $msg = "A non-existent priority was specified"; break;
			case -19: $msg = "The specified attachment could not be found"; break;
			case -20: $msg = "The specified category could not be found"; break;
			case -21: $msg = "The specified article could not be found"; break;
			case -22: $msg = "The API was unable to fetch the submitted attachment"; break;
			case -23: $msg = "A non-existent custom field group was specified"; break;
			case -24: $msg = "A non-existent custom field was specified"; break;
			case -25: $msg = "An empty value was specified for a custom field marked as \"required\""; break;
			case -26: $msg = "An incorrect typeid (ticket ID) value was specified"; break;
			default:
				$msg = 'Unknown Error';
		}
		die('<div style="color:red;background-color:#faa;"><h1>Kayako API Error</h1><p>'.htmlspecialchars($msg).'</p></div>');
	} elseif ($error = $nuSoapClient->getError()) {
		//The SOAP client was unable to successfully communicate with the remote Kayako API
		die('<div style=\"color:red;background-color:#faa;\"><h1>SOAP Error</h1><pre>' . htmlspecialchars(print_r($error, true)) . '</pre><hr /><pre>' . htmlspecialchars(print_r($nuSoapClient->response,true)) . '</pre></div>');
	}
	return $result;
}

$params = array('user' => $username,
				'password' => $password,
				//Email address of the Kayako user to get tickets for
				'email' => 'someone@example.com',
				//Number of tickets to show per page
				'numPerPage' => 5,
				//Page number. 1 displays tickets 1-5; 2 displays 6-10; etc.
				'page' => 1,
				//Column to sort by (lastactivity, lastreplier, ticketstatusid,
				// priorityid, departmentid)
				'sortBy' => 'lastactivity',
				//TRUE to sort in ascending order, FALSE to sort in descending order
				'orderAsc' => false
				);
$result = call('getSubmittedTickets', $params);

//Our request was successful. $result now contains an array of submitted tickets
?>
<h1>Successful Request</h1>
<h2>Submitted Tickets:</h2>
<pre><?php print_r($result); ?></pre>

This post has been edited by Andrew Gillard: 07 September 2009 - 11:05 AM
Reason for edit: Fixing IPB 2 code

Craig Brass
Managing Director and Chief Software Architect - Craig Brass Systems
0

#2
User is offline   Andrew Gillard 

  • Staff - Lead Developer
  • Pip
  • Group: Developers
  • Posts: 97
  • Joined: 04-March 07
  • Gender:Male
  • Location:Basingstoke, United Kingdom
C#.NET Example Note: I'm not usually a .NET programmer, so please excuse me if there are any problems with the below code, and there may be some random hacks in it, but it runs fine for me, so it should be good enough to at least demonstrate the API. Creating the proxy class .NET requires that you generate a proxy class that interacts with the remote SOAP service. Compared to the PHP code, this seems a bit of a roundabout way of doing things (presumably so that the compiler can check that your code should work...), but it does allow Visual Studio to suggest/auto-complete methods and types, so there are advantages to this method. Creating the class is very easy. Open a Visual Studio Command Prompt (it's in the "Visual Studio Tools" folder inside "Visual Studio " Start menu program group), change directory (`cd`) to the directory where you want to create your project, then run the following two commands, replacing the URL with the URL to your SOAP service:
wsdl http://www.example.com/helpdesk/integrationapi/index.php?wsdl
csc /target:library /out:KayakoIntegrationAPI.dll /target:library kayako_integration_api.cs
You then need to simply import the created DLL into your C# project as a reference and use code along the lines of:
using System;
 
namespace KayakoApiTest {
    class Program {
        const string username = "admin";
        const string password = "password";
        const string email = "me@example.com";
        const int ticketId = 1;
 
        static void Main(string[] args) {
            try {
                Console.WriteLine("Connecting to Kayako...");
                Console.WriteLine();
 
                kayako_integration_api api = new kayako_integration_api();
 
                //Show list of deparments
                Console.WriteLine("getDepartmentList()");
                department[] dList = api.getDepartmentList(username, password);
                for (int i = 0; i < dList.Length; i++) {
                    Console.WriteLine(" * " + dList[i].title);
                }
                Console.WriteLine();
 
                //Show list of priorities
                Console.WriteLine("getPriorityList()");
                priority[] pList = api.getPriorityList(username, password);
                for (int i = 0; i < pList.Length; i++) {
                    Console.WriteLine(" * " + pList[i].title);
                }
                Console.WriteLine();
 
                //Show list of statuses
                Console.WriteLine("getStatusList()");
                status[] sList = api.getStatusList(username, password);
                for (int i = 0; i < sList.Length; i++) {
                    Console.WriteLine(" * " + sList[i].title);
                }
                Console.WriteLine();
 
                //Show total number of submitted tickets
                Console.WriteLine("getTotalSubmittedTickets()");
                int totalSubmittedTickets = api.getTotalSubmittedTickets(username, password, email);
                Console.WriteLine(" * Submitted ticket total: " + totalSubmittedTickets);
                Console.WriteLine();
 
                //Now list each department's custom fields
                Console.WriteLine("getDepartmentCustomFields()");
                for (int i = 0; i < dList.Length; i++) {
                    customfieldgroup[] groups = api.getDepartmentCustomFields(username, password, dList[i].id);
                    if (groups != null) {
                        Console.WriteLine(" #" + dList[i].id + ": " + dList[i].title);
                        for (int ii = 0; ii < groups.Length; ii++) {
                            Console.WriteLine("  * #" + groups[ii].id + " - " + groups[ii].title);
 
                            customfield[] fields = groups[ii].fields;
                            for (int iii = 0; iii < fields.Length; iii++) {
                                Console.WriteLine("   * " + fields[iii].title + 
                                    " (description: " + fields[iii].description + ") " +
                                    "[type: " + customFieldTypeIdToName(fields[iii].fieldtype) + "] " +
                                    "[required: " + (fields[iii].isrequired ? "yes" : "no") + "]");
                                if (fields[iii].fieldtype >= 4 && fields[iii].fieldtype <= 7) {
                                    Console.WriteLine("     Options:");
                                    string[] optionValues = fields[iii].options.Split('\n');
                                    int[] optionOrders = stringArrayToIntArray(fields[iii].optionorders.Split('\n'));
                                    int[] optionselects = stringArrayToIntArray(fields[iii].optionsselected.Split('\n'));
 
                                    for (int iv = 0; iv < optionValues.Length; iv++) {
                                        Console.WriteLine("      #" + optionOrders[iv] + ": " + 
                                            optionValues[iv] + " (selected: " + 
                                            (optionselects[iv] == 1 ? "yes" : "no") + ")");
                                    }
                                }
                            }
                            Console.WriteLine();
                        }
                        Console.WriteLine();
                    }
                }
 
                //Show our test ticket
                submittedTicket ticket = api.getSubmittedTicket(username, password, email, ticketId);
                DateTime startDate = UnixTimeStampToDateTime(ticket.startdate);
                Console.WriteLine("Ticket ID #1 [" + ticket.mask + "] - " + ticket.subject + 
                    " (posted: " + startDate.ToLongDateString() + ")");
                Console.WriteLine("Custom Fields:");
                for (int i = 0; i < ticket.custom.Length; i++) {
                    Console.WriteLine(" * Group ID #" + ticket.custom[i].id + " - " + ticket.custom[i].title);
                    for (int ii = 0; ii < ticket.custom[i].fields.Length; ii++) {
                        Console.WriteLine("   * " + ticket.custom[i].fields[ii].name + ": " + 
                            ticket.custom[i].fields[ii].value);
                    }
                    Console.WriteLine();
                }
                Console.WriteLine("Posts:");
                for (int i = 0; i < ticket.posts.Length; i++) {
                    DateTime postDate = UnixTimeStampToDateTime(ticket.posts[i].date);
                    Console.WriteLine(ticket.posts[i].fullname + " said, at " + postDate.ToLongDateString() + ":");
                    Console.WriteLine(ticket.posts[i].contents);
                    Console.WriteLine();
                }
                Console.WriteLine();
 
                //Submit a ticket?
                Console.WriteLine("Do you want to submit a ticket? [yN]");
                string ticketResponse = Console.ReadLine();
                if (ticketResponse == "y") {
                    Console.WriteLine("Attempting to submit a ticket...");
                    submitTicketCustomField[] customs = new submitTicketCustomField[8];
                    customs[0] = new submitTicketCustomField { id = 1, value = "Example Value 1" };
                    customs[1] = new submitTicketCustomField { id = 2, value = "Example Value 2" };
                    customs[2] = new submitTicketCustomField { id = 3, value = "Multi\r\nLine\r\nExample" };
                    customs[3] = new submitTicketCustomField { id = 4, value = "MyPassword" };
                    customs[4] = new submitTicketCustomField { id = 5, value = 
                        "Check Value 1\nCheck Value 2\nCheck Value 4\nCheck Value 5" };
                    customs[5] = new submitTicketCustomField { id = 6, value = "Radio Val 1" };
                    customs[6] = new submitTicketCustomField { id = 7, value = "Select Val 4" };
                    customs[7] = new submitTicketCustomField { id = 8, value = "Select Value 2\nSelect Value 3" };
                    submittedAttachment[] attachments = new submittedAttachment[0];
 
                    int departmentId = 1;
                    int priorityId = 3;
 
                    ticketSubmission result = api.submitTicket(username, password, email, departmentId, priorityId, 
                        "My Name", "Subject!", "Message!", attachments, true, 0, "", customs);
                    Console.WriteLine("Ticket submitted. ID #" + result.id + " (Mask: " + result.mask + ")");
                } else {
                    Console.WriteLine("Okay, not submitting a ticket.");
                }
            } catch (System.Web.Services.Protocols.SoapException ex) {
                Console.WriteLine("SOAP Exception: " + ex.Detail.InnerText);
            }
 
            Console.WriteLine("Press enter to exit.");
            Console.ReadLine();
        }
 
        static private string customFieldTypeIdToName(int id) {
            switch (id) {
                case 1: return "text";
                case 2: return "text area";
                case 3: return "password";
                case 4: return "checkbox";
                case 5: return "radio";
                case 6: return "select";
                case 7: return "select multiple";
                default: return "unknown";
            }
        }
 
        /**
         * @url http://stackoverflow.com/questions/249760/how-to-convert-unix-timestamp-to-datetime-and-vice-versa 
         */
        public static DateTime UnixTimeStampToDateTime(double unixTimeStamp) {
            // Unix timestamp is seconds past epoch
            System.DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0);
            dtDateTime = dtDateTime.AddSeconds(unixTimeStamp).ToLocalTime();
            return dtDateTime;
        }

        public static int[] stringArrayToIntArray(string[] input) {
            int[] outArr = new int[input.Length];
            for (int i = 0; i < input.Length; i++) {
                outArr[i] = Convert.ToInt32(input[i]);
            }
            return outArr;
        }
    }
}

This post has been edited by Andrew Gillard: 07 September 2009 - 11:03 AM
Reason for edit: Fixing IPB 2 code

Andrew Gillard
Lead Developer - Craig Brass Systems
0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • This topic is locked

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users