Inserting leads to Zoho CRM using PHP

Here is a simple PHP class (one  file) which you can use to insert leads to Zoho CRM. It is designed to be hooked up with your site contact form. Instead of emailing the contact form results, they go directly to the CRM and are available for the sales person to call. The code based on the orignal Python based mfabrik.zoho package. PHP curl needed as a requirement.

<?php
/**
 * Simple Zoho CRM inserter.
 *
 * MIT licensed. Copyright 2011 Pete Sevander and Mikko Ohtamaa.
 *
 */

class ZohoException extends Exception { }

class Zoho {

    public function __construct($username, $password, $apikey, $extra_auth_params = array(), $auth_url="https://accounts.zoho.com/login") {
        $this->username = $username;
        $this->password = $password;
        $this->apikey = $apikey;

        $this->ticket = null;
    }

    public function open() {
        $this->ticket = $this->_createTicket();
    }

    public function _createTicket() {

        $params = array(
            "servicename" => "ZohoCRM",
            "FROM_AGENT" => "true",
            "LOGIN_ID" => $this->username,
            "PASSWORD" => $this->password
        );

        //$params = array_map('urlencode', $params);

        $url = "https://accounts.zoho.com/login";

        $body = openUrl($url, $params);

        $data = $this->_parse_ticket_response($body);
        $this->data = $data;

        if (isset($data["WARNING"]) || isset($data['CAUSE'])) {
            $warning = (isset($data["WARNING"])) ? $data["WARNING"] : $data["CAUSE"];
            if ($warning != "null") {
                throw new ZohoException("Could not auth: " . $warning);
            }
        }
        if ($data["RESULT"] != "TRUE") {
            throw new ZohoException("Ticket result was not valid");
        }

        return $data["TICKET"];
    }

    public function _parse_ticket_response($data) {

        $output = array();

        $lines = explode("\n", $data);

        foreach($lines as $line) {
            if (substr($line, 0,1) == "#") {
                continue;
            }
            if ($line == "") {
                continue;
            }
            if (!strstr($line, "=")) {
                continue;
            }
            $line = explode("=", $line);
            $output[$line[0]] = $line[1];
        }

        return $output;
    }

    public function ensure_opened() {
        if ($this->ticket == null) {
            throw new ZohoException("Login first");
        }
    }

    /**
    * https://crm.zoho.com/crm/private/xml/Leads/insertRecords?newFormat=1&apikey=APIkey&ticket=Ticket
    **/
    public function insertRecords($leads, $extra_post_parameters=array()) {
        $this->ensure_opened();

        $xmldata = $this->XMLfy($leads);

        $post = array(
            'newFormat' => 1,
            'ticket' => $this->ticket,
            'apikey' => $this->apikey,
            'version' => 2,
            'xmlData' => $xmldata,
            'duplicateCheck' => 2,
            'wfTrigger' => 'true'
        );

        array_merge($post, $extra_post_parameters);

        // We'll bump created time to make sure that duplicate data entry
        // gets bumped up on the salesdroids list

        // $created = strftime('%Y-%m-%d %H:%M');
        // $post['Created Time'] = $created;

        // XXX: Good idea but Zoho silently ignores changes to the creation time

        $q = http_build_query($post);

        //print_r($post);

        $response = openUrl("https://crm.zoho.com/crm/private/xml/Leads/insertRecords", $q);

        //print_r($response);
        //print_r($xmldata);
        $this->check_successful_xml($response);

        return true;

    }

    public function getRecords($columns ='leads(Name)') {
        $this->ensure_opened();

        $post = array(
            'newFormat' => 1,
            'ticket' => $this->ticket,
            'apikey' => $this->apikey,
            'version' => 2,
            'selectColumns' => $columns,
        );

        $q = http_build_query($post);
        $response = openUrl("https://crm.zoho.com/crm/private/json/Leads/getRecords", $q );

        echo $response;

    }

    public function check_successful_xml($response) {
        $html = new DOMDocument();
        $html->loadXML($response);

        if ($err = $html->getElementsByTagName('error')->item(0)) {
            throw new ZohoException($err->getElementsByTagName('message')->item(0)->nodeValue);
        }

        return true;
    }

    public function XMLfy ($arr) {
        $xml = "<Leads>";
        $no = 1;
        foreach ($arr as $a) {
            $xml .= "<row no=\"$no\">";
            foreach ($a as $key => $val) {
                $xml .= "<FL val=\"$key\">$val</FL>";
            }
            $xml .= "</row>";
            $no += 1;
        }
        $xml .= "</Leads>";
        return $xml;
    }
}

function openUrl($url, $data=null) {
    $ch = curl_init();
    $timeout = 5;

    if($data) {
        curl_setopt($ch,CURLOPT_POST,1);
        curl_setopt($ch,CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch,CURLOPT_VERBOSE, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

       // log output
       //$f = fopen("/tmp/zoho-curl.txt", "wt");
       //curl_setopt($ch,CURLOPT_STDERR, $f);

   }

    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}

?>

And this is how you use it:

<?php

    $ZOHO_USER="yyyyy@xxxxxx.com";
    $ZOHO_PASSWORD="v3ryS3cr3t";
    $ZOHO_API_KEY='GET THIS FROM ZOHO CRM SETTINGS';

    require_once 'Zoho.php';

    $z = new Zoho($ZOHO_USER, $ZOHO_PASSWORD, $ZOHO_API_KEY);

    try {
        $z->open();

        $leads = array(
            'First Name' => 'Mikko',
            'Last Name' => 'Ohtamaa',
            'Company' => 'opensourcehacker.com',
            'Phone' => '+358 12 123 1234',
            'Email' => 'mikko @ foobar dot com',
            'Lead Owner' => 'yyyyy@xxxxxx.com',
        );

        try {
            $z->insertRecords(array($leads));
            $renderForm = false;
            echo '<h3>Contact information sent successfully. We will contact you soon.</h3><br /><strong>Data sent:</strong><dl>';
            foreach ($values as $key => $value) {
                echo '<dt><strong>' . $form->getElement($key)->getLabel() . '</strong></dt>';
                echo '<dd>' . $value . '</dd>';
            }
            echo '</dl>';

        } catch (ZohoException $e) {
            echo '<span>Error inserting data: ' . $e->getMessage() . '</span>';
        } 

    } catch (ZohoException $e) {
        echo '<span>Can\'t connect to Zoho: ' . $e->getMessage() . '</span>';
    }

?>

Some things to note

  • Owner must be given and be valid Zoho user
  • Company and Last Name fields are the only required fields by default
  • Zoho CRM checks duplicates using email field and thus using the same email address for (test) inserts won’t yield to visible results in My Leads view when duplicateCheck=2
  • Creation Time field cannot be changed
  • You can customize fields in Zoho CRM settings

 

\"\" Subscribe to RSS feed Follow me on Twitter Follow me on Facebook Follow me Google+

9 thoughts on “Inserting leads to Zoho CRM using PHP

  1. Hi,
    This really worked well. They have shifting it to auto token now. will you be able to help me there ?

  2. Hi,

    I’ve just managed to update the code to the new Authorisation Code system.

    You need to change the $params values in all the functuions to include the new variables like “scope” & authtoken and set the $url in _createTicket to “https://accounts.zoho.com/apiauthtoken/nb/create”.

    Also change return $data[“TICKET”]; to:
    return $data[“AUTHTOKEN”];

    I just used the info on this page: https://crmkbase.zoho.com/link/replace-api-key-ticket-with-authentication-token

    I think that’s about it. I consider myself very much a PHP newbie and I got it working just by going through each line carefully.

  3. This doesnt work. Please suggest.

    Atleast publish a full working sample end to end for referance.

  4. Hi….
    When i am using this code to create Leads in ZOHO CRM from php form so following error is occurred…..
    Error inserting data: Please use AUTHTOKEN, instead of TICKET and APIKEY.

    so how i solve this error….???

  5. Do you have this in youtube? I want to learn this thing. I have trouble in programming in php.

Leave a Reply

Your email address will not be published. Required fields are marked *