Making API Calls

From a Browser

Posting an API call to Intacct can be accomplished from a very simple set of HTML loaded into a web browser.

<HTML>
  <form method="post" action="https://api.intacct.com/ia/xml/xmlgw.phtml">
    <textarea rows="20" cols="80" name="xmlrequest">
    </textarea><br/>
    <input type="submit"/>
  </form>
</HTML>

The key to the browser-based call is the form element containing the XML to post needs to be named "xmlrequest".

From a Trigger

You can add a custom Trigger to custom objects on selected events, with optional conditions.  To invoke an Intacct Web Services API call from a trigger, choose the "HTTP Post" trigger type with the appropriate URL for the environment.  In production, this URL is "https://api.intacct.com/ia/xml/xmlgw.phtml".  In the preview environment, the URL is "https://preview.intacct.com/ia/xml/xmlgw.phtml".  To use a trigger, you must first create a document template for the trigger to process.  Look at this sample document to see how to use merge fields to create a dynamic API call from a trigger: Create an Invoice from a Trigger

Using a Programming Language like PHP

All modern languages provide basic facilities for posting API calls over an HTTP(S) connection.  The following sample PHP code demonstrates how to make arbitrary API calls:

<?php
class api_post { 
public static function create($xml) { 
  $createXml = "<create>" . $xml . "</create>"; 
  return api_post::post($createXml); 
} 
public static function xml2_1_method($xml) { 
  return api_post::post($xml); 
} 
private static function post($xml) { 
  global $sessionId; 
  $templateHead = "<?xml version=\"1.0\" encoding=\"UTF-8\"?> 
     <request> <control> <senderid>intacct_dev</senderid> 
     <password>****</password> <controlid>foobar</controlid> 
     <uniqueid>false</uniqueid> <dtdversion>3.0</dtdversion> 
     </control> <operation> <authentication> 
     <sessionid>{1%}</sessionid> </authentication> 
     <content> <function controlid=\"foobar\">"; 
   $templateFoot = "</function> </content> </operation> </request>";         
   $xml = $templateHead . $xml . $templateFoot;         
   $xml = str_replace("{1%}", $sessionId, $xml);         // post!         
   $ch = curl_init();        
   curl_setopt( $ch, CURLOPT_URL, "https://api.intacct.com/ia/xml/xmlgw.phtml" );         
   curl_setopt( $ch, CURLOPT_HEADER, 0 );         
   curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1 );         
   curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );         
   curl_setopt( $ch, CURLOPT_MUTE, 1 );         
   curl_setopt( $ch, CURLOPT_TIMEOUT, 300 ); //Seconds until timeout
   curl_setopt( $ch, CURLOPT_POST, 1 );                 
   $body = "xmlrequest=" . urlencode( $xml );         
   curl_setopt( $ch, CURLOPT_POSTFIELDS, $body );                 
   $response = curl_exec( $ch );                
   curl_close( $ch );                 
   return $response;     
  } 
} 
?>

Using Python

For Python version 3.4. The following example shows posting a call to inspect an object:

# Python version 3.4

import urllib.request

api_url = 'https://api.intacct.com/ia/xml/xmlgw.phtml'

auth_info = {
    'mysenderid':'PutYourSenderIdHere',
    'mysenderpw':'PutYourSenderPasswordHere',
    'myuser':'PutYourUserIdHere',
    'mycompany':'PutYourCompanyIdHere',
    'mypwd':'PutYourUserPasswordHere'
    }

controlerid = {'controlerid':'test'}

payload = """
<content>
  <function controlid="testControlId">
    <inspect>
      <object>USERINFO</object>
    </inspect>
  </function>
</content>
"""

api_request = """<?xml version="1.0" encoding="iso-8859-1"?>
<request>
  <control>
    <senderid>"""+auth_info['mysenderid']+"""</senderid>
    <password>"""+auth_info['mysenderpw']+"""</password>
    <controlid>"""+controlerid['controlerid']+"""</controlid>
    <uniqueid>false</uniqueid>
    <dtdversion>3.0</dtdversion>
  </control>
  <operation>
    <authentication>
      <login>
        <userid>"""+auth_info['myuser']+"""</userid>
        <companyid>"""+auth_info['mycompany']+"""</companyid>
        <password>"""+auth_info['mypwd']+"""</password>
      </login>
    </authentication>
    """+payload+"""
  </operation>
</request>"""

headers = {"Content-type": "application/x-www-form-urlencoded",
           "Accept": "text/plain"}

form = {'xmlrequest':api_request}

url_encoding = urllib.parse.urlencode(form)
binary_data = url_encoding.encode()

request_header = urllib.request.Request(api_url,headers)
request = urllib.request.urlopen(request_header,binary_data)

http_status = str(request.status) + " " + request.reason
print(http_status)

read_request = request.read()
print(read_request.decode())

The following was graciously supplied by one of our members:

import urllib2

auth_info = {
    'senderid':'xyz',
    'password':'xyz',
    'userid':'xyz',
    'companyid':'xyz',
    'userpw':'xyz'
    }
headers = {'Content-type': 'x-intacct-xml-request'}

API_URL = 'https://api.intacct.com/ia/xml/xmlgw.phtml'

req_shell = """<?xml version="1.0" encoding="iso-8859-1"?><request><control>
<senderid>{senderid}</senderid><password>{password}</password><controlid>foobar</controlid>
<uniqueid>false</uniqueid><dtdversion>3.0</dtdversion></control><operation>
<authentication><login><userid>{userid}</userid><companyid>{companyid}</companyid>
<password>{userpw}</password></login></authentication><content>
<function controlid="foobar">{payload}</function></content></operation></request>"""

payload = '<read><object>vendor</object><keys/><fields>*</fields><returnFormat>xml</returnFormat></read>'

req = urllib2.Request(API_URL, req_shell.format(payload=payload, **auth_info), headers)
resp = urllib2.urlopen(req).read()

Using PHP5

For PHP 5.x. The following example shows posting a call to get vendors:

<?php

$mysenderid = 'PutYourSenderIdHere';
$mysenderpwd = 'PutYourSenderPasswordHere';
$mycompany = 'PutYourCompanyIdHere';
$myuser = 'PutYourUserIdHere';
$mypwd = 'PutYourUserPasswordHere';

$xmlPostStr = '<?xml version="1.0" encoding="iso-8859-1"?><request><control><senderid>';
$xmlPostStr.= $mysenderid;
$xmlPostStr.= '</senderid><password>';
$xmlPostStr.= $mysenderpwd;
$xmlPostStr.= '</password><controlid>ControlIdHere</controlid><uniqueid>false</uniqueid><dtdversion>3.0</dtdversion></control><operation><authentication><login><userid>';
$xmlPostStr.= $myuser;
$xmlPostStr.= '</userid><companyid>';
$xmlPostStr.= $mycompany;
$xmlPostStr.= '</companyid><password>';
$xmlPostStr.= $mypwd;
$xmlPostStr.= '</password></login></authentication>';
$xmlPostStr.= '<content><function controlid="C1"><read><object>vendor</object><keys/><fields>*</fields><returnFormat>xml</returnFormat></read></function></content></operation></request>';

  	// INITIATE CURL
  	$ch = curl_init();
  	curl_setopt( $ch, CURLOPT_URL, 'https://api.intacct.com/ia/xml/xmlgw.phtml');
  	curl_setopt( $ch, CURLOPT_HEADER, 0 );
  	curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1 );
  	curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
  	curl_setopt( $ch, CURLOPT_TIMEOUT, 300); //Seconds until timeout
  	curl_setopt( $ch, CURLOPT_POST, 1 );
  	
  	// BUILD THE POST BODY
  	$body = "xmlrequest=" . urlencode( $xmlPostStr );
  	curl_setopt( $ch, CURLOPT_POSTFIELDS, $body );
  	
  	// POST AND GET RESPONSE
  	$response = curl_exec( $ch );
	  	
  	curl_close( $ch );
	
  	//PRINT OUT THE RESPONSE
  	echo $response;
  	
?>

Using Java

For JAVA

import java.net.*;
import java.io.*;
import java.security.*;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.SSLSocket;

public class HttpsClient {

    // Intacct XML gateway addresses
    private static String intacctaddrprod = "api.intacct.com";

    public static void main(String[] args) {

        try {
            
            // Check the arguments
              if ((args.length != 1))
                  throw new IllegalArgumentException("Wrong number of arguments.");

            // Read XML file from args[0]
            File infile;
            FileReader infiler;

            infile = new File(args[0]);
            infiler = new FileReader(infile);

            // Make sure the file is valid
            if (!infile.exists()) {
                throw new IllegalArgumentException("File does not exist.");
            }

            if (!infile.isFile()) {
                throw new IllegalArgumentException("Not a valid file.");
            }

            if (!infile.canRead()) {
                throw new IllegalArgumentException("The source file is unreadable.");
            }

            // Read the file into a buffer
            int filesize = (int) infile.length();
            char[] strxml = new char[filesize];
            int chars_read = 0;

            while (chars_read < filesize) {
                chars_read += infiler.read(strxml, chars_read, filesize);
            }
            System.out.println("XML Request:");
            System.out.println(strxml);
            System.out.println("Making Call...");
//            System.out.println(strxml);

            String response;
            response = PostToIntacct(strxml, filesize);
            System.out.println("Done Making Call...");

            System.out.println(response);

        }
        catch (Exception e) {

        }
    }

    
    public static String PostToIntacct(char[] strxml, int length) {

        String response = "";

        try {

            SSLSocketFactory factory = (SSLSocketFactory)SSLSocketFactory.getDefault();
            SSLSocket socket = (SSLSocket)factory.createSocket(HttpsClient.intacctaddrprod, 443);

            PrintWriter to_server = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())));

            to_server.println("POST /ia/xml/xmlgw.phtml HTTP/1.0");
            to_server.println("Host: " + HttpsClient.intacctaddrprod);
            to_server.println("Content-Type: x-intacct-xml-request");
            to_server.println("Content-Length: " + length);
            to_server.println();
            to_server.println(strxml);
            to_server.println();
            to_server.flush();

            // check for errros
            if (to_server.checkError())
                return "SSLSocket:  java.io.PrintWriter error";

            // read the response
            BufferedReader from_server = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String inputLine;
            while ((inputLine = from_server.readLine()) != null)
                response += inputLine;
            System.out.println("raw response:");
            System.out.println(response);

            // find the start of the XML response
            int startpos = response.indexOf("<?");
            response = response.substring(startpos);

            // close the connection
            to_server.close();
            from_server.close();
            socket.close();

        }
        catch (UnknownHostException e) {
            return ("Unknown host");
        }
        catch (IOException e) {
            return ("IO Excpetion");
        }

        return response;
    }

}