Pages

Wednesday, February 1, 2012

SugarCRM Cookbook: Adding Leads via SOAP

bvdservices.com
Back in 1996 when I first got my start in the CRM world, I remember how impressed I was by a new feature about to roll out in an upcoming release of our software. It was something called "web import," which allowed web site visitors to enter information on a standard web form and the submitted data would then appear in the CRM system without any further user intervention. It was the early days of leveraging the web as a lead generation tool and this feature was nothing short of magical.

Nowadays, it is not so magical and is a standard feature in many CRM packages. In SugarCRM, it manifests itself as something aptly named Web-To-Lead. Through this feature, one can create a web form to embed in a company web site, with the necessary behind the scenes magic that allows for the data to automatically enter the SugarCRM system as a lead.

The drawback of this automated approach is that the resulting web form usually requires some fine tuning in order to seamlessly incorporate it into a company web site. For example, colors, fonts and other cosmetic aspects will likely need some adjustment. If you are using a Content Management System (CMS) such as Drupal or Joomla!, other challenges are likely to present themselves in the process. 

But all this means is that one might need to use a different approach to get the job done and sure enough, SugarCRM provides another method for entering data, more specifically, an Application Programming Interface (API). Through it, one can communicate with SugarCRM to read or write data, among various other things. 

There are two built-in APIs for SugarCRM, one is SOAP based and the second uses REST. The finer details of each are beyond the scope of this post, but for our purposes, we will focus on SOAP and the point that both allow us to interact with SugarCRM in a much more controlled manner, using a wide range of programming languages common to the web world. 

Leveraging the API gives us greater control than the auto-generated form by allowing us full control over which fields are to be populated. Further to this, it allows us to access any part of SugarCRM, opening up the possibility of performing additional tasks at the time the lead enters the system, such as scheduling a follow up call, attaching a document or numerous other things. Lastly, it is also makes it possible for us to build the form using whichever method is already in place for creating the web site and simply tie it to the API -- it is automatically seamless.

So, how do we go about creating a lead via SOAP? Lets take a look. 


This example will assume we are needing to use PHP to write the data to SugarCRM. Three files are involved in the process: lead_soap.php, nusoap.php and soap_config.php

All of the files are available for download from my personal site. You should download them now and open the PHP files contained in the zip archive using your text editor of choice. The rest of this post will discuss the role of each file and how to use them.

lead_soap.php:

This file is the heart of it all. It contains the code that connects to SugarCRM via SOAP and inserts the data into the system. It is important to understand the manner in which one establishes a connection to SugarCRM as well as the manner in which the data is to be prepared. You can see this in line 27 and 36 - 49 respectively. 

Should you wish to modify the code to insert the data into a different module (yet another example of the greater control the API gives us), you can do so by changing the module name in line 38. Module names are case sensitive in some scenarios, so always use the matching case. Also, note that he field list defined in line 36 may also need to be updated to correspond with field names from whichever other module to which you choose to write the data.  

Most of your edits will likely be applied to the section that begins on line 31, where the data is captured from the form, as well as the aforementioned section of code beginning on line 36 that prepares the data for delivery to SugarCRM.

nusoap.php

This is a commonly used SOAP client for PHP. More information is available at the official project page on Sourceforge. For our purposes, all we need to know about this file is that it is used to provide the communication layer to SOAP. There is no need to modify this file.

soap_config.php

This file contains the information pertaining to the SugarCRM instance we wish to connect to, such as the user name and password to use. Update all three variables it contains with those corresponding to your specific needs.

Once you have made the necessary updates to the files, you are ready to put them into action. 

To do so, simply place all three files into the same directory/folder within the file system structure of your web site. It does not matter where you put them, so long as all three are in the same directory/folder and they can be accessed by your web server. 

Lastly, the Submit action on the form that will be used to collect the data should be connected to the file lead_soap.php. Once everything is in place you should be able to visit the form on your web site, submit some data and have it appear in the Leads module as a new record.

Download away and try it out!

44 comments:

  1. Nice article shared here which is quite helpful to everyone. I like it very much. It is really full of information.

    Search Engine Optimization services

    ReplyDelete
  2. Hi there

    I am not a programmer, so please help me with this.

    I can change it to contacts, and to accounts seperately.

    But how do i add accounts and contacts into one file and creating a relationship?

    Thanking you in advance

    paul

    ReplyDelete
  3. Hello,

    Is there a way to write file contents into the database as blob using sugarcrm API.

    ReplyDelete
    Replies
    1. Sugar does not have a built-in method for doing that. All files (note attachments, email attachments, documents, etc) are always stored as actual files in the cache/upload or /upload folder (depending on your version of sugar)

      Delete
  4. Is this method works for sugar on demand? I'm trying to do same thing but connecting to suganondemand

    ReplyDelete
    Replies
    1. Yes, it works for OnDemand and on premise. You just need to put the proper URL into the configuration file. Also, you might want to consider replacing the references to $_GET with $_REQUEST. The latter is more universal.

      Delete
    2. Angel, thanks for your quick response. I added my info into the soap_config file and now looks like this:
      $soap_url = 'https://company.sugarondemand.com';
      $soap_user = 'admin';
      $soap_pass = 'XXXXXXXXXX';

      But, when I try to send the new lead info to sugarCRM on-demand, I'm getting this error: Deprecated: Function ereg() is deprecated in ..../nusoap.php on line 565 and other lines. I also replace the $_GET for $_REQUEST but still getting same error, I will really appreciate your answer, thanks. Red

      Delete
    3. That error/message pertains to your PHP configuration on the server hosting the code being executed to add the lead: soap_lead.php

      See here for more info: http://stackoverflow.com/questions/4297501/function-ereg-is-deprecated

      Delete
  5. Hi, I have an e-commerce and its users want to integrate with those of sugar but I do not understand how to recover data from e-commerce and send them to sugar. Help please

    ReplyDelete
    Replies
    1. I am not really sure how to help you. Your e-commerce solution likely has some type of API you can use to pull data from it. If not, you would need to figure out another way of accessing the data, possibly by directly interacting with the SQL server.

      Either way, that's the first thing you need to sort out and it will vary based on the solution you are using. Next, you need to define what it is you want to pull.

      Lastly, Sugar offers a variety of ways to pull data from other systems. You can do it as part of a logic hook, a custom action in a custom controller or a Scheduler job for example. Not knowing how you intend to use the data, it makes it a bit difficult for me to make a potential solution.

      Delete
    2. My purpose is to integrate prestashop users with Sugar CRM. The two systems are on different servers. As I can accomplish this with web service?.

      Delete
    3. I've never worked with Prestashop, so again, my hands are tied as far as providing help.

      The only helpful suggestion I can give you is to read the documentation for Prestashop to see if it includes some sort of API.

      Delete
  6. Angel thanks pors your answers. It solved the problem that I had with prestashop and integrate contacts. My problem now is that the SET entry does not validate that the new contact was already entered. As I can validate that the new contact that I am entering sugar is not repeated?

    ReplyDelete
    Replies
    1. That is correct. set_entry() doesn't have any built-in duplicate checking features, it is only for adding new records or editing existing records. Use get_entry_list() or search_by_module() to search for existing records. That would give you the ID value of the record, which you in turn can use in set_entry to update an existing record.

      Delete
    2. And in the example you expusiste of leads that would be like? because I realized that the id of the contacts are automatically generated. How would the search in that case?. Sorry for this trouble and my English. I'm speaking. It would be possible to explain to me with some code only those sentences.

      Delete
    3. Search based on the person's last name or other value. get_entry_list() allows you to define a custom WHERE clause for the search.

      Delete
    4. Thank you. but could you help me with the statement that assemble and do not understand how to define each parameter. I have it but I do not return anything. And I intend to return all the contacts that have an email = a pablo.andres.hg@hotmail.com


      $get_entry_list = array(
      'session' => $session_id,
      'module_name' => 'Contacts',
      'query' => 'email1 = pablo.andres.hg@hotmail.com',
      '$order_by' => 'first_name',
      'link_name_to_fields_array' => array(array('name' => 'email_addresses',
      'value' => array('id', 'email_address',
      'opt_out', 'primary_address'))),
      'max_results' => '100',
      'deleted' => '0');

      $result = $soapclient->call('get_entry_list',$get_entry_list);

      Delete
    5. This comment has been removed by the author.

      Delete
  7. Angel wath is the difference between using http://localhost/sugar/soap.php?wsdl and http://localhost/sugar/service/v2/soap.php?wsdl ?.

    My code works using http://localhost/sugar/soap.php?wsdl but in the documentation of talk of using sugar service/v2/soap.php

    ReplyDelete
    Replies
    1. /soap.php is the original version of the SOAP API. /service/vN/soap.php is the newer version of the SOAP API. The newer one is supposed to be faster and allows for custom methods, but doesn't differ in functionality, although some of the parameters on the methods can be different.

      Delete
  8. i am new to development world i want to know is it possible to sync sugarcrm task to outlook 2010 with c# code?

    ReplyDelete
    Replies
    1. Yes, it is certainly possible. I don't have any experience working with the Outlook API, so I couldn't tell you how to insert data into it, but the Sugar API certainly allows you to read the Task data from its database.

      Delete
    2. Consequently, there are multiple Outlook links available on SugarForge.org. Why don't you use one of those as opposed to recreating the wheel?

      Delete
  9. Great guide! It really helps me. Thanks for sharing.

    ReplyDelete
  10. Angel,
    Your articles are always extremely helpful and I am hoping that you could help me out with something that goes along with this article.
    We have a client that has a WordPress Site and has a SugarCRM site. I have created a plugin that captures user data on the WordPress site and inputs into the leads module on the CRM side using SOAP.

    That works perfectly and I am extremely happy with it. The issue that I am having is that the usual actions that fire when a new lead is created aren't firing. The main thing is that the Sugar user is not being notified that a new lead is being created for them. If I go into the CRM and manually create a lead the user gets an email. When a new lead is created via SOAP the user doesn't get an email.

    Is it something in my setup or is it a SOAP issue? I have a process manager that I can use to send an email to the user but I have to set up a work around so the user actually gets the email. I was hoping you would be able to shed some light on this issue. We have CE v 6.4 installed.

    Thanks
    Alex

    ReplyDelete
    Replies
    1. Alex,

      Thank you for your feedback. Always happy to help.

      Which user/pass are you using when you call the login() method? I suspect it matches the user that you are assigning the Lead to. Reason I mention this is that assignment notifications only go out if the assigned user of a record isn't also the user that is currently logged into the system.

      i.e. You can't send yourself assignment notifications.

      I suspect that when you are creating the records via the interface, you are logging in as a user other than the one that you are assigning it to.

      Delete
    2. Angel,

      Thanks for the response, sorry for taking so long to reply.

      I actually found the answer when looking for an answer to something else in she sugar forum.

      I went into soap/SoapSugarUser.php and inside the set_entry function I added

      $admin = new Administration ();
      $admin-> retrieveSettings ();

      and then I changed $seed->save();
      to

      $seed->save($admin->settings['notify_on']);

      Now whenever a new lead is created the user receives an email with the information.

      Delete
  11. hola angel cordial saludo y gracias por tu blog, es de mucha ayuda, te cuento que ya logre añadir un contacto por medio del soap al sugarcrm, lo que quiero hacer ahora es realizar una consulta via web services a otro servidor que tambien usa soap y que la informacion que me arroje el servidor, guardarla en un modulo de sugar, sera posible hacer eso??????? agradesco tu pronta respuesta

    ReplyDelete
    Replies
    1. Hola, gracias por sus comentarios, me alegra que le ayuda la información.

      Si, lo es posible. La idea seria igual al proceso de agregar el contacto. Solo tendria que actualizar el codigo para referirse al nombre del modulo donde desea ingresar el dato que recibe del otro servidor, y tambien actualizar la lista de los nombres de los campos para que correspondan con ese modulo.

      Delete
  12. Hi Angel,
    I got an error from the link of the example files on your site. Are still available?

    Thanks in advance,

    Danilo

    ReplyDelete
    Replies
    1. Hi Danilo,

      Apologies, my hosting provider recently performed a server migration for me and it looks like it has affected my siste and in turn the link to those files. I will give it a look. Thank you for bringing it to my attention.

      Delete
  13. Angel,
    We have a production site running sugar 6.4.0 and we are looking to upgrade. I duplicated the site on the same server and upgraded to 6.5.13.

    Everything looks pretty good and it seems that all of our customization is still there, the only problem is that the SOAP connection that I have created to insert leads into the CRM no longer works. Now when I try to connect via SOAP I get "no operations defined in the WSDL document!" for an error.

    I have tried switching to a REST connection but I get the same result, I can connect and insert to the production site but not the dev site.

    Here is a link to a question I posted on the sugar forums:

    http://forums.sugarcrm.com/f3/updating-sugar-broke-soap-connection-87393/

    It has the SOAP code that I am using on the production site. I don't know if it makes a difference or not but the dev site isn't a live site. I have edited my host file so I can reach it.

    I am hoping you can point me in the right direction on this.

    Thanks,
    Alex

    ReplyDelete
    Replies
    1. Alex,

      Apologies, but I've never come across that error.

      What happens if you put the URL for the SOAP or REST endpoint into your browser?

      Delete
  14. putting mydomain.com/service/v4/rest.php in my browser outputs the file to my screen. Putting soap instead of rest, it shows me the WSDL for the service. If I use v4_1 I get a 404 error.

    ReplyDelete
    Replies
    1. That's not indicative of a problem per se. I don't recall which version introduced v4_1, but if you are using an older version of Sugar, it may just be that you are using a version that didn't yet have it.

      Which URL are you using in production?

      Delete
  15. For the production site (v6.4.0) I was just using mydomain.com/soap.php?wsdl and it was working fine. On my dev site (v6.5.13) it doesn't work. On my production site I can use the /service/v4/soap.php?wsdl or /service/v4/rest.php and it will insert records but none of them work on the dev site.

    ReplyDelete
  16. hola angel cordial saludo y como siempre agradeciendote por tu interes de ayudar y prontas respuestas, queria saber si depronto tienes algun ejemplo donde se escriba informacion a un modulo de sugar, pero que tambien se escriba en la relacion que tenga el modulo con otro modulo ya sea de tipo uno a uno, uno a muchos o muchos a muchos, muchas gracias por tu atencion. saludos

    ReplyDelete
    Replies
    1. Hola,

      No tengo un ejemplo a la mano, pero seria via el metodo set_realationship(). Lo parametros que se tienen que proveer son los nombres de los dos modulos involucrados, igual que el ID de los registros de esos modulos que uno desea ligar.

      Delete
  17. hola angel coordial saludo, escribo para agradecerte por la informacion, me ayudo mucho la informacion que me diste, para solucionar mi problema, te queria hacer otra consulta, queria preguntarte si es posible generar un campo en sugar del tipo entero y que ese campo se llene de acuerdo a una consulta directo a la bd de sugar, ej: campo llamado "sesiones" y que en su interno tenga una cconsulta a la bd del tipo "SELECT SUM(mensaje_c='Sesion') as total FROM qwer_info_detallada_cstm" y que muestre el total osea sesion=4 si el total de las sesiones son 4,no se si entendiste pero agradeceria una pronta respuesta. saludos y mil gracias por tus aportes

    ReplyDelete
  18. Hi,

    the download is not available any more :-(

    Can you re-upload it ?

    Cheers,
    Fabian

    ReplyDelete
  19. I'd also love to download the example files. Could you kindly re-upload them?

    Thanks!

    ReplyDelete
  20. Is there any further reading you would recommend on this?

    Amela
    Lead conversion

    ReplyDelete

Your comments, feedback and suggestions are welcome, but please refrain from using offensive language and/or berating others. Thank you in advance.