Web Services in your own language: Part 1 – PHP

bsoremsugar —  November 11, 2010 — 2 Comments

This article is the first in a series where we will show some simple examples of usage of the SugarCRM Web Services framework with various programming languages. Stay tuned for more examples in the coming weeks, and feel free to sound off in the comments if you are looking for examples in a certain programming language. Coming up next is an example connecting to Sugar Web Services using Ruby.

PHP is one of the most popular web development languages, powering large web properties such as Yahoo! and Facebook, as well as millions of web applications and sites around the world ( including SugarCRM :-) ). During the days of PHP 4, the NuSOAP library was the most popular choice as it was a full featured and well supported library. But with the advent of PHP 5 the new PHP SOAP extension came into being, offering a much faster SOAP solution since it is written in C rather than user-land PHP code. It also offers a cleaner syntax than NuSOAP thanks to the OOP improvements in PHP 5, so making SOAP calls work simply like normal class method calls.

In this blog post, I’ll show an example of using the native PHP SOAP client in PHP 5 to connect to SugarCRM Web Services and perform some simple module actions.

To start off, let’s connect to our Sugar instance. We can make our initial connection by initializing the PHP SoapClient object:

// Connect to the Web Service
$soapClient = new SoapClient("http://localhost/sugarcrm/service/v3_1/soap.php?wsdl");

This opens our connection to the v3_1 API, which is based upon with v2 API introduced in SugarCRM 5.5, but with some minor function changes and a few new functions added. With the connection established, we can now login to the instance.

The first parameter to the login method specifies the user authentication credentials, where we pass the username and password ( and the password is encoded as an MD5 string ) in an array. We’ll wrap our SOAP call inside a try…catch block, since PHP SOAP will throw exceptions if there is an issue with the SOAP request.

// Login
$user_name = 'admin';
$user_password = 'sugar';

try {
    $info = $soapClient->login(
        array(
            'user_name' => $user_name,
            'password'  => md5($user_password),
            )
        );
}
catch (SoapFault $fault) {
    die("Sorry, the service returned the following ERROR: ".$fault->faultcode."-".$fault->faultstring.".");
}

$session = $info->id;
echo "Successful Login! Session ID {$session}n";

Once we have successfully authenticated, we can now create a new record. We’ll begin by making an Account record; to do this we’ll use the set_entry SOAP method. It requires passing the Session ID ( which we got from the login method above ), the module name we are creating a record for, and then the name-value pairs of record data for the new module as an array. The returned ID is the record ID for the newly created Account record.

// Create Account
try {
    $info = $soapClient->set_entry(
        $session,
        'Accounts',
        array(
            array('name' => 'name', 'value' => 'New Account'),
            array('name' => 'description', 'value' => 'This is an account created from a SOAP web services call'),
            )
        );
}
catch (SoapFault $fault) {
    die("Sorry, the service returned the following ERROR: ".$fault->faultcode."-".$fault->faultstring.".");
}

$accountId = $info->id;
echo "Created Account ID {$accountId}n";

We’ll do the same for creating a Contact record; calling the set_entry SOAP method and passing the record data in name-value pairs in the call.

// Create Contact
try {
    $info = $soapClient->set_entry(
        $session,
        'Contacts',
        array(
            array('name' => 'first_name', 'value' => 'Foo'),
            array('name' => 'last_name', 'value' => 'Bar'),
            array('name' => 'description', 'value' => 'This is a contact created from a SOAP web services call'),
            )
        );
}
catch (SoapFault $fault) {
    die("Sorry, the service returned the following ERROR: ".$fault->faultcode."-".$fault->faultstring.".");
}

$contactId = $info->id;
echo "Created Contact ID {$contactId}n";

Now that we have created a new Account and a new Contact, let’s relate them together. We can do this with the set_relationship SOAP method call. This method requires passing the session ID, the primary module for the relationship ( in this case the Accounts module ), the ID for the Accounts record we are relating to, the field name in that module that identifies the relationship to use ( for this example it would be ‘contacts’, you can find this in the module’s vardefs.php file ), and then an array of record IDs to relate to the record. This is a bit complicated; the below code example should help explain this better.

// Relate Contact to Account
try {
    $info = $soapClient->set_relationship(
        $session,
        'Accounts',
        $accountId,
        'contacts',
        array($contactId)
        );
}
catch (SoapFault $fault) {
    die("Sorry, the service returned the following ERROR: ".$fault->faultcode."-".$fault->faultstring.".");
}

The returned data back gives us statistics on the success or failure of adding the relationship, populating numerical values in the ‘created’ and ‘failed’ attributes. For this example, we can check to make sure the ‘created’ attribute has a value of 1 to be sure the relationship was properly created.

if ( $info->created == 1 ) {
    echo "Related Contact ID {$contactId} to Account ID {$accountId}n";
}
else {
    echo "Failed relating Contact ID {$contactId} to Account ID {$accountId}n";
}

With that, we’ve created two records and related them using the web services API using PHP SOAP. Feel free to sound off in the comments if you have questions on more complex examples of using the API, and stay tuned for next time when we’ll see how to interact with SugarCRM web services using Ruby, using a library created by one of our SugarCRM techincal staff members.

2 responses to Web Services in your own language: Part 1 – PHP

  1. 

    Hi,

    how can be executed the set_relation function using .NET?
    The parameters are the following but it would be great if you could give me explanation:
    set_relation (
    session id – this is ok
    module name – this is the programmic name of the primary module of the relation. right? (in your example Accont)
    module id – the id of the record of the primary module for which we are relating to. right?
    link field name – the name of the field in the primary module which gives the relation
    related ids – the record ids of the other (not the primary) module – in your example contact ids

    and there are 2 more parameters in .net which I don’t know what they are:
    sugarService.name_value[] name_value_list
    delete

    please help me to be able to understand the parameters correctly.
    thank you in advance

Trackbacks and Pingbacks:

  1. Sugar Developer Blog » Blog Archive » HOWTO: Search for a record via email address via Web Services - November 12, 2010

    […] Sugar Developer Blog « Web Services in your own language: Part 1 – PHP […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s