Using PHP to call an Apex Web Service

I had the 'pleasure' the other day of integrating Drupal with using PHP. I didn't want to write all of my SOQL queries and business logic in my PHP scripts so I whipped up a quick Apex class and exposed it as a web service. I found a great blog post by Scott Hemmeter that really helped me out calling the service with PHP so I thought I would share the code and other observations.

First you will need to download the PHP Toolkit. The toolkit contains all of the PHP code necessary to make web service calls against your org. Please note that the contained Partner and Enterprise WSDLs are for Production/Developer orgs, so if you are running against a Sandbox, you will need to download the appropriate WSDL from that Sandbox.

For this example, I took my Person wrapper class and exposed it as a web serivce. It exposes a method that allows you to search for Contacts and Leads by email address and returns a List of generic Person objects.

global class PersonService {

 global class Person {

  webservice String id;
  webservice String firstName;
  webservice String lastName;
  webservice String company;
  webservice String email;
  webservice String phone;
  webservice String sObjectType;


 webService static List<person> searchByEmail(String email) {

  // list of Person objects to return
  List<person> people = new List<person>();

  // issue the sosl search
  List<list<sobject>> searchResults = [FIND :email IN EMAIL FIELDS RETURNING
   Contact (Id, Account.Name, Email, Phone, FirstName, LastName),
   Lead (Id, Company, FirstName, LastName, Email, Phone)];

  // cast the results by sObjec type
  List<contact> contacts = ((List<contact>)searchResults[0]);
  List<lead> leads = ((List<lead>)searchResults[1]);

  // a each contact found as a Person
  for (Integer i=0;i<contacts.size();i++) {
   Person p = new Person(); = contacts[i].Id;
   p.firstName = contacts[i].FirstName;
   p.lastName = contacts[i].LastName; = contacts[i].Account.Name; = contacts[i].Email; = contacts[i].Phone;
   p.sObjectType = 'Contact';

  // a each lead found as a Person
  for (Integer i=0;i<leads.size();i++) {
   Person p = new Person(); = leads[i].Id;
   p.firstName = leads[i].FirstName;
   p.lastName = leads[i].LastName; = leads[i].Company; = leads[i].Email; = leads[i].Phone;
   p.sObjectType = 'Lead';

  System.debug('Returning people: '+people);

  return people;


Log into and donwload the WSDL file for the PersonService class (Setup -> Develop -> Apex Classes). Also, make sure the profile calling the Web servcie has access to this class.

The PHP page looks like the following:


require_once ('sfdc/SforcePartnerClient.php');
require_once ('sfdc/SforceHeaderOptions.php');

// credentials
$sfdcUsername = "YOUR-USERNAME";
$sfdcPassword = "YOUR-PASSWORD";
// the email address to search for. could also use a post/get variable
$searchEmail = '';

$sfdc = new SforcePartnerClient();
// create a connection using the partner wsdl
$SoapClient = $sfdc->createConnection("sfdc/partner.wsdl.xml");
$loginResult = false;

try {
 // log in with username, password and security token if required
 $loginResult = $sfdc->login($sfdcUsername, $sfdcPassword.$sfdcToken);
} catch (Exception $e) {
 global $errors;
 $errors = $e->faultstring;
 echo "Fatal Login Error <b>" . $errors . "</b>";

// setup the SOAP client modify the headers
$parsedURL = parse_url($sfdc->getLocation());
define ("_SFDC_SERVER_", substr($parsedURL['host'],0,strpos($parsedURL['host'], '.')));
define ("_WS_NAME_", "PersonService");
define ("_WS_WSDL_", "sfdc/" . _WS_NAME_ . ".wsdl.xml");
define ("_WS_ENDPOINT_", 'https://' . _SFDC_SERVER_ . '' . _WS_NAME_);
define ("_WS_NAMESPACE_", '' . _WS_NAME_);

$client = new SoapClient(_WS_WSDL_);
$sforce_header = new SoapHeader(_WS_NAMESPACE_, "SessionHeader", array("sessionId" => $sfdc->getSessionId()));

echo _SFDC_SERVER_."br";
echo _WS_NAME_."br";
echo _WS_WSDL_."br";
echo _WS_ENDPOINT_."br";
echo _WS_NAMESPACE_."p";

try {

 // call the web service via post
 $response = $client->searchByEmail($wsParams);
 // dump the response to the browser

// this is really bad.
} catch (Exception $e) {
 global $errors;
 $errors = $e->faultstring;
 echo "Ooop! Error: <b>" . $errors . "</b>";


The PHP page should look something like the following: