Back to main demo page

Using Marketo's SOAP API and AJAX to retrieve information about a lead

Background links

There are a number of times when you would like to use information from your database to provide a richer visitor environment. There are a number of personalization technologies out there that do the job very well such as Monetate and others if you are willing to pay for the services. If you are working with landing pages then you can use the Marketo landing pages with the dynamic content segmentation to do the job. You can even go so far as to embedded dynamic content on your website using landing pages in iframes if you choose.

Another alternative is to use the Marketo SOAP API to fetch all the visitor attributes so that you can modify your page accordingly. Some scenarios could include:

and the list could go on

SOAP API - Get lead webservice

The webservice is used as a proxy for the javascript to fetch data on-demand based upon an AJAX request. It takes two arguments either by HTTP GET or POST for the lead key type (see below), and the data in order to process the lead data and return a JSON string

Lead KeyDescriptionExample
cookieMarketo's Munchkin cookie999-XXX-999&token:_mch-example.com-1332019507735-45839
emailLead's Email addresstest@example.com
marketoidMarketo Lead Id in the database111111111
sfdcleadidSalesforce's lead record id00QF000000ORENrMAP
sfdcconatactidSalesforce's contact record id003F000000wFbXYIA0

Note: the salesforce ids are 18 characters in length and must include the 3 digit chechsum

Example of webservice url:
http://test.hollebone.ca/ws-marketo-getlead.php?type=cookie&data=344-QYK-228%26token%3A_mch-algonquincollege.com-1332019507735-45839
For the cookie data, it must be urlencoded before being passed to the webservice because Marketo's cookie contains an ampersand (&) which makes the parser splits the cookie value incorrectly

PHP web serivcecode


<?php
/* *********************************************************************************
*  Marketo SOAP API get lead web service
*  *********************************************************************************
*
* test string
* curl -v -d "type=email&data=test@example.com" http://example.com/ws-marketo-getlead.php
*/
// load the Marketo SOAP class
include_once($_SERVER['DOCUMENT_ROOT'] . '/include/class.marketoapi.php');

// Helper method to get a string description for an HTTP status code
// From http://www.gen-x-design.com/archives/create-a-rest-api-with-php/
function getStatusCodeMessage($status) {
    $codes = Array(
        100 => 'Continue',
      101 => 'Switching Protocols',
        200 => 'OK',
      201 => 'Created', 202 => 'Accepted', 203 => 'Non-Authoritative Information', 204 => 'No Content', 205 => 'Reset Content', 206 => 'Partial Content',
        300 => 'Multiple Choices',
      301 => 'Moved Permanently', 302 => 'Found', 303 => 'See Other', 304 => 'Not Modified', 305 => 'Use Proxy', 306 => '(Unused)', 307 => 'Temporary Redirect',
    400 => 'Bad Request',
      401 => 'Unauthorized', 402 => 'Payment Required', 403 => 'Forbidden', 404 => 'Not Found', 405 => 'Method Not Allowed', 406 => 'Not Acceptable', 407 => 'Proxy Authentication Required', 408 => 'Request Timeout',
      409 => 'Conflict', 410 => 'Gone', 411 => 'Length Required', 412 => 'Precondition Failed', 413 => 'Request Entity Too Large', 414 => 'Request-URI Too Long', 415 => 'Unsupported Media Type',
      416 => 'Requested Range Not Satisfiable', 417 => 'Expectation Failed',
        500 => 'Internal Server Error',
      501 => 'Not Implemented', 502 => 'Bad Gateway', 503 => 'Service Unavailable', 504 => 'Gateway Timeout', 505 => 'HTTP Version Not Supported'
    );
    return (isset($codes[$status])) ? $codes[$status] : '';
}

// Helper method to send a HTTP response code/message
function sendResponse($status = 200, $body = '', $content_type = 'text/html') {
    $status_header = 'HTTP/1.1 ' . $status . ' ' . getStatusCodeMessage($status);
    header($status_header);
    header('Content-type: ' . $content_type);
    echo $body;
}

class MarketoGetLeadService {
    // Main method to fetch data from Marketo via SOAP
    function get_lead() {
    $LeadType  ='';
    $LeadValue ='';
    $req_type  = '';
    $req_data  = '';
    if (isset($_REQUEST['type'])) {
      $req_type = $_REQUEST['type'];
      if (isset($_REQUEST['data'])) {
        $req_data  = $_REQUEST['data'];
        if ($req_type == 'email' || $req_type == 'cookie' || $req_type == 'marketoid' || $req_type == 'sfdcleadid' || $req_type == 'sfdccontactid') {
          switch ($req_type) {
            case 'email':
              $LeadType   = 'EMAIL';
              if(preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/", $req_data)) {
                $LeadValue = $req_data;
              }
              break;
            case 'cookie':
              $LeadType   = 'COOKIE';
              if (isset($_GET['data']) || isset($_POST['data'])) {
                $LeadValue =  urldecode($req_data);
              } elseif (isset($_COOKIE['_mkto_trk'])) {
                $LeadValue = $_COOKIE['_mkto_trk'];
              }
              break;
            case 'marketoid':
              $LeadType   = 'IDNUM';
              $LeadValue = $req_data;
              break;
            case 'sfdcleadid':
              $LeadType   = 'SFDCLEADID';
              $LeadValue = $req_data;
              break;
            case 'sfdccontactid':
              $LeadType   = 'SFDCCONTACTID';
              $LeadValue = $req_data;
              break;
            default:
              $LeadType   = '';
              $LeadValue  = '';
          }
          if ((strlen($LeadType) > 0) && (strlen($LeadValue) > 0)) {
            $marketo_api = new MarketoAPI();
            try {
              $result = $marketo_api->getLead_with_exception($LeadType, $LeadValue);
              // If the response looks valid we check for a valid email address in the response.
              if (TRUE === $marketo_api->doesResponseLookValid($result)){
                sendResponse(200, json_encode($result->result->leadRecordList->leadRecord));
                return true;
              }
              // either returns $result as false or sends an email
              sendResponse(400, json_encode($result));
              return false;
            }
            catch (Exception $e) {
              if (isset($e->detail->serviceException->code) && $e->detail->serviceException->code == '20103') {
                // Code 20103 means the LeadKey value did not match any lead
                sendResponse(400, json_encode($e->detail));
                return false;
              } else {
                // other error types
                sendResponse(400, json_encode($e));
                return false;
              }
            }
          } else {
            $data = array('result' => false, 'reason' => 'no valid key value (data) provided');
            sendResponse(400, json_encode($data));
            return false;
          }
        } else {
          $data = array('result' => false, 'reason' => 'no valid lead key found');
          sendResponse(400, json_encode($data));
          return false;
        }
      } else {
        $data = array('result' => false, 'reason' => 'no key type specified');
        sendResponse(400, json_encode($data));
        return false;
      }
    }
  }
}
// This is the first thing that gets called when this page is loaded
// Creates a new instance of the MarketoGetLeadService class and calls the get_lead method
$api = new MarketoGetLeadService;
$api->get_lead();
?>
	

AJAX Call

To facilitate the webservice callout, I will use my favorite javascript library as the AJAX framework is one of the best available.

jQuery code


<script type="text/javascript" language="Javascript" src="
function getLead(type, leadkey){
  var lead = new Object();
  jQuery('#LeadTable').html('... requesting data ...');
  jQuery.ajax({
    type:   'POST',
    url:    'http://example.com/ws-marketo-getlead.php',
    data:   'type=' + type + '&' + ((type == 'cookie')?'data=' + escape(leadkey) : 'data=' + leadkey),
    async:  false,
    cache:  false,
    success: function(data, status, xhr){
      lead.json     = data;
      try {
        lead.key      = JSON.parse(data);
        lead.status   = 200;
        lead.response = 'Ok';
        lead.error    = false;
      }
      catch (ex) {
        lead.key      = '';
        lead.status   = -1;
        lead.response = ex.message;
        lead.error    = true;
      }
    },
    error: function(xhr, status, error){
      lead.key      = '';
      lead.response = xhr.responseText;
      lead.status   = xhr.status;
      lead.error    = true;
    }
  });

  ... do something with the JSON string ...

  return false;
}
</script>
	

Demo

Lead Key Data
Activity Filter Data
 Include  Exclude

Lead Data



Lead Activity


Back to main demo page