IntroductionWorking With RecordsActivity ReportsLocation ServicesWebhook ManagementExamplesBatching Requests

Examples

XML, JSON, Form Encoded

Every kind of item can be created, updated or destroyed with three supported Content-Type formats: XML, JSON and Form-Encoded. The following example of creating web site activity for a contact demonstrates each format.

XML

<?xml version="1.0" encoding="utf-8"?>
<request>
  <parent>{parentId}</parent>
    <data>
        <caption>website created from api</caption>
        <url>http://test.site.com</url>
    </data>
</request>

JSON

{"parent":"{parentId}","data":{"caption":"website created from api","url":"http:\/\/test.site.com"}}

Form-encoded (provided by html form)

parent={parentId}&data%5Bcaption%5D=website+created+from+api&data%5Burl%5D=http%3A%2F%2Ftest.site.com

Example of Batch Processing Activities

This example demonstrates filtering Project Blogs by category tags then adding six new Section activities for each one if they don’t already exist. Most of the example code is for handling communication with the server; the actual API logic is at the end and is fairly small.

<?php
    ini_set('display_errors', '1');
    error_reporting(E_ALL);
    define('USER', '{userEmail}');
    define('TOKEN', '{userApiToken}');
    define('HOST', 'https://secure.solve360.com');
    define('TIMEOUT', 30);
    
    define('SECTION_TYPE_ID', 57);
    
    /*
     * Helper functions
     */
    
    /**
     * Helper function to convert our data array into xml format
     *
     * @param array $data
     * @param SimpleXmlElement $xml
     * @return XML
     */
    function arrayToXml($data, $xml = null)
    {
      if ($xml == null) {
        $xml = simplexml_load_string('<?xml version="1.0" encoding="utf-8"?><data />');
      }
      foreach($data as $key => $value) {
        if (is_array($value)) {
              $node = $xml->addChild($key);
          arrayToXml($value, $node);
        } else {
              $xml->addChild($key, $value);
        }
      }
      
      return $xml->asXML();
    }

    /**
     * Function that makes request to the api and return xml response
     *
     * @param string $uri
     * @param string $restVerb
     * @param array $data
     * @return SimpleXmlElement
     */
    function getXmlResponse($uri, $restVerb, $data = array())
    {
        // Connect to the host
        $errno = null;
        $errstr = null;
        $fp = stream_socket_client("tcp://".HOST.":80", $errno, $errstr, TIMEOUT);
        
        if (!$fp) {
            die("cannot connect to host " . HOST);
        } else {
            if (empty($data)) {
                $data = '';
            } else {
                $data = arrayToXml($data);
            }
        }
        
        // Prepare request body
        $request = "$restVerb $uri HTTP/1.1\r\n";
        $request .= "Host: ".HOST."\r\n";
        // Authorization header
        $request .= "Authorization: Basic ".base64_encode(USER.":".TOKEN)."\r\n";
        // We inform the server that we're sending data in xml format
        $request .= "Content-Type: application/xml\r\n";
        // We inform the server theat we are waiting for xml in response
        $request .= "Accept: application/xml\r\n";
        $request .= "Content-Length: ".strlen($data)."\r\n";
        $request .= "Connection: close\r\n\r\n";
        $request .= $data;
        
//echo $request;
        // Send request to the host
        fwrite($fp, $request); 
        
        $result = '';
        stream_set_timeout($fp, TIMEOUT);
        $info = stream_get_meta_data($fp);
        while (!feof($fp) && !$info['timed_out']) {
            $newLine = stream_get_line($fp, 1024);
            if (trim($newLine, "\r\n ") === '0') {
                break;
            }
            $result .= $newLine;
            $info = stream_get_meta_data($fp);
        }
        
        $headers = substr($result, 0, strpos($result, "\r\n\r\n"));
        $body = substr($result, (strpos($result, "\r\n\r\n") + 4));
        $headers = explode("\r\n", $headers);
        
        // Get xml from response
        $matches = array();
        preg_match("/(<.*>)/s", $body, $matches);
        $xml = $matches[1];

        if ($xml) {
            $xml = simplexml_load_string($xml);
        } else {
            // Something went wrong and we haven't got xml in the response
            die('System error');
        }

        return $xml;
    }
    
    /*
     * Sections example main code
     */

    // We need to know how many blogs we have
    $limit = (int) getXmlResponse('/projectblogs/', 'GET', array('limit' => 1))->count;

    // Let's define categories ids for search
    $categoriesIds = array({categoryId}, {categoryId}); // NOTE: replace categories ids with yours!
    
    // Compose search options
    $searchOptions = array(
        'limit'       => $limit, // we want to get all blogs that are needed at once
        'filterMode'  => 'category', // we need data filtered by category
        'filterValue' => implode(',', $categoriesIds), // cagegories ids as value for filter
        'special'     => 'AND', // we need both categories to be set for a blog
    );
    
    // Get xml with search results
    $resultXml = getXmlResponse('/projectblogs/', 'GET', $searchOptions);

    // Quite if there was an error
    if ($resultXml->status != 'success') {
        mail(USER, 'Error while working with Solve360', 'Error: ' . $resultXml->errors->asXml());
        die('Error while working with Solve360');
    }

    if (count($resultXml) > 2) { // If there are some blogs for our search conditions

        // Let's select blog ids for adding activities sections
        $blogsIds = array();
        foreach ($resultXml as $projectBlog) {
            if (isset($projectBlog->id)) { // if it is not count or status field
                $blogsIds[] = (int) $projectBlog->id;
            }
        }

        // Prepare sections titles
        $sections = array(
            'Calendar',
            'Upcoming',
            'Active',
            'For Managment / Client Liason',
            'For Booking Agents',
            'Archive'
        );
        
        // To save the order, reverse the array
        $sections = array_reverse($sections);

        foreach ($blogsIds as $blogId) {
            $sectionsToAdd = $sections;

            // We should check if the seaction already exists
            $blog = getXmlResponse('/projectblogs/' . (string) $blogId, 'GET');
            foreach ((array) $blog->activities as $blogActivity) {
                if ((int) $blogActivity->typeid == SECTION_TYPE_ID) {
                    foreach ($sectionsToAdd as $sectionKey => $sectionTitle) {
                        if ((string) $blogActivity->fields->title == $sectionTitle) {
                            unset($sectionsToAdd[$sectionKey]);
                        }
                    }
                }
            }

            // Add activities to the blog
            foreach ($sectionsToAdd as $sectionTitle) {
                (getXmlResponse('/projectblogs/separator/', 'POST', array(
                    'parent' => $blogId, 
                    'data'   => array('title' => $sectionTitle)
                )));
            }
        }
        
        echo 'success';
    }