Tuesday 19 August 2008

Connecting to Sage CRM with PHP

I was recently requested to find a way to integrate an online signup form with Sage CRM to allow for signups to be automatically added. I decided to use PHP to do this as its SOAP integration is very easy to use:

Below is example code that shows how to log into Sage using its SOAP interface and pass requests to it:

Note: this example is PHP5 only.

//allow for exceptions to be thrown from sage
try
{
//define connection options, this allows for recording messages sent and received
$options = array('trace' => 1);

$client = new SoapClient("http://localhost/crm/eware.dll/webservice/webservice.wsdl", $options);

//username and password for sage (the user has to have web service access enabled)
$login_details = array('username' => 'username',
'password' => 'password');

//login to sage
$response = $client->logon($login_details);

//create header to send on future requests
$header = "<sessionheader><sessionid>".$response->result->sessionid."</sessionid></sessionheader>";
$session_var = new SoapVar($header, XSD_ANYXML, null, null, null);
$session_header = new SoapHeader('http://tempuri.org/type', 'SessionHeader', $session_var);

//apply header to client
$client->__setSoapHeaders(array($session_header));

//define lead data (or pull in from elsewhere), this is only some of the fields
//I will go into further detail on the fields in another blog post
$lead_data = array('companyname' => 'company name',
'companyaddress1' => 'address1',
'personfirstname' => 'first name',
'personlastname' => 'last name',
'status' => 'In Progress');

//create soap variable to send
$lead = new SoapVar($lead_data, XSD_ANYTYPE, "lead", "http://tempuri.org/type");

//send request to sage
$response = $client->add(array('entityname' => 'lead', 'records' => $lead));

//check response
if (isset($response->result->records->crmid))
{
//worked, the lead id can be found in $response->result->records->crmid
}
else
{
//failed, display
echo "RESPONSE:\n" . $client->__getLastResponse() . "\n";
}
}
catch (Exception $e)
{
//something went wrong, display request and response
echo "REQUEST:\n" . $client->__getLastRequest() . "\n";
echo "RESPONSE:\n" . $client->__getLastResponse() . "\n";

echo $e->getMessage();
}


Any questions/feedback please leave a comment

2 comments:

Müschel said...
This comment has been removed by the author.
Müschel said...

Cool, thanks for this great script, works perfectly.

I tried to costumize it for sending a query to the CRM in order to get the information of allowed salutation, but failed.
My idea was to use the "query" and "next" functions to get all the salutations.
Do you have an example script ready for such a situation?

Thanking you in anticipation!

greetings

müschel