Interations Development

Widgets in the digital pipeline

Widgets can interact with the functionality of the digital pipeline and respond to any of the following events:

  • Incoming email

  • Incoming call

  • Incoming chat message

  • Going to the stage

  • Entering the site (for this event you can configure the pending action)

To interact the widget with a digital funnel, in the manifest.json file, you must specify the scope of the digital_pipeline and the dp / settings block, for more information about the widget structure, see here. The endpoint digital_pipeline must be present in the widget.php file.

When a configured event arrives at endpoint digital_pipeline, the system sends a request containing the data array of the following structure

Example response:
  1. [
  2.     'event' => [
  3.         'type' => 15,
  4.             'type_code' => 'lead_appeared_in_status'
  5.                 'data' => [
  6.                     'id'          => 123124, // lead id
  7.                     'element_type' => 2, // Type of element (2 - lead, 12 - buyer)
  8.                     'status_id'   => 654324, // status of a lead
  9.                     'pipeline_id' => 654324, // pipeline of a lead
  10.                 ],
  11.                 'time' => 1491300016,
  12.     ],
  13.     'action' => [
  14.         'settings' => [
  15.             'widget' => [
  16.                  'settings' => [
  17.                      // Settings of a widget dp
  18.                  ]
  19.             ]
  20.         ]
  21.     ],
  22.     'amouser' => 'example@amocrm.com',
  23.     'amohash' => 'c123ae456cd7891246bffb1e654abb9d',
  24.             ]
List of possible values of type and type_code
Code Type of code Description
1 lead_added Add a lead
14 lead_status_changed Change of the status of the lead
15 lead_appeared_in_status Change the status inside the widget's extended action into several stages*
16 mail_in Incoming email
17 call_in Incoming call
18 site_visit Visiting the site
19 chat Incoming chat message
20 customer_added Adding a customer
21 customer_period_changed Change of the status of the buyer
22 customer_appeared_in_period Change the status inside the widget's extended action into several stages*
Integration with the API

More information about adding leads through the API with a unique visitor ID can be found on this page.

*In that case, when you specify action_multiple - true in the block dp of your manifest.json, then you allow to stretch (set) the action of your widget at once to several stages. If you change the status of the lead / buyer, in the area of the action of your widget stretched to several stages, type_code = 15 will come. At the same time, when the lead / buyer moves to the status in which your widget is activated, type_code = 14 will initially come.

Exchange of digital pipeline data with a widget

In the previous section, we talked about the need to have the endpoint digital_pipeline in the back-end file of your widget.php widget. This is necessary so that when a certain event occurs, your widget can receive information from the digital pipline. We exchange data from our side and your widget by sending notifications about events using WebHook technology (for more details on the technology, see here).

Note that the WebHook from the digital pipeline is sent to the web server only once when the specified event occurs.

In the example, we show an implementation of endpoint functions and methods for working with WebHooks, for a simple widget that sends a text message when a certain event occurs.

Example of integration
  1. protected function endpoint_digital_pipeline() {
  2.     foreach ($this->keys as $key) {
  3.       $this->_request[$key] = $this->check_request($key);
  4.     }
  5.     if (empty($this->_request['action']['settings']['widget']['settings'])) {
  6.       throw new \Exception('Empty widget settings');
  7.     }
  8.     $this->_request['settings'] = $this->_request['action']['settings']['widget']['settings'];
  9.     if (empty($this->_request['event']['data']['id'])) {
  10.       throw new \Exception('Empty entity id');
  11.     }
  12.     if (!in_array($this->_request['event']['type_code'], $this->_avalible_events)) {    // Check if there is a code in the request
  13. events from
  14. a certain array of valid/selected events (_avalible_events) to trigger the widget
  15.       return;
  16.     }
  17.     $this->parse_data();
  18.     $this->init_curl();
  19.     $this->_response = $this->curl_post(self::/* link to your API */ . $this->api_methods['your_widget_hook'], $this-
  20. >_your_widget_hook,
  21. 'X-AMOCRM-REQUEST:Y', FALSE);
  22.     if ((int)$this->_response['code'] === 0) {
  23.       $this->customers_notes_set($this->_request['event']['data'], $this->_request['settings']['message']);
  24.       curl_close($this->_curl);
  25.       return TRUE;
  26.     } else {
  27.       // error message to the user
  28.       $error_message = "Error: " . var_export($this->_response, TRUE);
  29.       $this->customers_notes_set($this->_request['event']['data'], $error_message, FALSE, (int)$this->_response['code']);
  30.       curl_close($this->_curl);
  31.       throw new Helpers\Exception($error_message);
  32.     }
  33.   }

Receiving data from the WebHook digital pipeline

  1. private function check_request($key) {
  2.   return Helpers\Route::param($key) ? Helpers\Route::param($key) : NULL;  // We return either an array or NULL
  3. }

Convert the data that came with WebHook

  1. private function parse_data() {
  2.     $this->_lifepay_hook = [
  3.       'apikey' => self::/* Key of your API */,
  4.       'data'   => json_encode([
  5.         [
  6.           'customerId' => $this->_request['event']['data']['id'],
  7.           'message'    => $this->_request['settings']['message'],
  8.         ],
  9.       ]),
  10.     ];
  11.   }

Sending WebHook

  1. private function curl_post($link, $data, $http_header = 'Content-Type: application/json', $is_json = TRUE) {
  2.   curl_setopt($this->_curl, CURLOPT_URL, $link);
  3.   if ($is_json) {
  4.     $post_fields = json_encode($data);
  5.   } else {
  6.     $post_fields = http_build_query($data);
  7.   }
  8.   curl_setopt($this->_curl, CURLOPT_POSTFIELDS, $post_fields);
  9.   curl_setopt($this->_curl, CURLOPT_HTTPHEADER, [$http_header]);
  10.   $response = json_decode(curl_exec($this->_curl), TRUE);
  11.   if (curl_errno($this->_curl)) {
  12.     $response = 'cURL error: ' . curl_error($this->_curl);
  13.   }
  14.   return $response;
  15. }

Initializing and Configuring cURL

  1. private function init_curl() {
  2.     $this->_curl = curl_init();
  3.     curl_setopt($this->_curl, CURLOPT_POST, TRUE);
  4.     curl_setopt($this->_curl, CURLOPT_SSL_VERIFYPEER, 0);
  5.     curl_setopt($this->_curl, CURLOPT_SSL_VERIFYHOST, 0);
  6.     curl_setopt($this->_curl, CURLOPT_CONNECTTIMEOUT, 2);
  7.     curl_setopt($this->_curl, CURLOPT_TIMEOUT, 2);
  8.     curl_setopt($this->_curl, CURLOPT_FOLLOWLOCATION, TRUE);
  9.     curl_setopt($this->_curl, CURLOPT_HEADER, FALSE);
  10.     curl_setopt($this->_curl, CURLOPT_RETURNTRANSFER, TRUE);
  11.   }

Automatic setting block

When your widget is successfully added and is available for integration, access to its settings will be possible from several areas. First of all, access to the full configuration will be possible standardly, as for all integrations, from the Settings -> Integration section of your account. In the event that your widget is integration with the digital pipeline, then it will be accessed from the settings of the digital pipeline, section leads in the area of declaring automatic actions for all leads.

This element is drawn by us, including the logo and the choice of the condition by which the action of your widget will be executed. On your part, you need to fill the element with quick settings or select actions that will be performed when the user chooses the condition.

For an example, let's describe the front-end part of the widget in script.js, which displays the settings inside the quick setup element. Select the sending of the message, upon the occurrence of any condition selected by the user (see screenshot above).

Example:
  1. dpSettings: function () {
  2.                 var w_code = self.get_settings().widget_code,   //The widget code specified in manifest.json
  3.                     lang = self.i18n('settings'),
  4.                     dp_modal = $(".digital-pipeline__short-task_widget-style_"+w_code)  //due to the substitution
  5. code(w_code) of your
  6. widget, we can refer to the element containing exactly your widget
  7.                         .parent()
  8.                         .parent()
  9.                         .find('[data-action=send_widget_hook]'),
  10.                     message_label = dp_modal.find('[title^='+lang.message.split(" ")[0]+']'),   //Your explanations to the fields,
  11. described in
  12. com.json
  13.                     message_label_new = "<div style='margin-top: 5px;'>" + lang.message + "</div>",
  14.                     message_input = dp_modal.find('input[name=message]'),   //The reference to the entered text
  15.                     message_textarea = self.render(     //Drawing the text input field
  16.                     {ref: '/tmpl/controls/textarea.twig'},
  17.                     {
  18.                         id: 'dp_message',
  19.                         style: {'width': '396px', 'margin-top': '5px', 'margin-bottom': '-3px'},
  20.                         value: message_input.val(),
  21.                         placeholder: lang.message
  22.                     }
  23.                 );
  24.                 message_label.hide().after(message_label_new);
  25.  
  26.                 message_input.hide().after(message_textarea);
  27.  
  28.                 return true;
  29.             }

It's important to remember about declaring the settings in manifest.json, for more information about the widget structure here

  1. "locations": [
  2.     "settings",
  3.     "digital_pipeline"
  4.   ],
  5. "dp": {
  6.     "settings": {
  7.       "message": {
  8.         "name": "settings.message",
  9.         "type": "text",
  10.         "required": true
  11.       }
  12.     }

Macros

Macros are used to automatically substitute data from entity cards into text messages. Thanks to the presence of macros in the integration, you can create universal text messages for a whole list of contacts, without the time spent on substituting data in each individual case.

An example of the implementation of macros from the combat script of the widget Prostor SMS from the company Axelerator, to substitute some information about the contact:

Example of integration:
  1. /* widget.php, back-end part */
  2. /* Declaring an array of macros */
  3. private $macroses = array("{{contact_name}}", "{{contact_phone}}", "{{contact_email}}");
  4. /* We receive and process the data for further use in the substitution. Please note that the extracted data
  5. must
  6. match declared macros to avoid empty substitutions  */
  7. protected function endpoint_digital_pipeline()
  8.   {
  9.     $this->GetData();
  10.     $account = $this->account->current();
  11.     $contact = $this->getContactById($lead["leads"][0]["main_contact_id"]);
  12. $contact_phone = "";
  13.     $contact_email = "";
  14.     foreach($contact["contacts"][0]["custom_fields"] as $field){
  15.       if($field["code"] == "PHONE"){
  16.         $contact_phone = $field["values"][0]["value"];
  17.       }
  18.       if($field["code"] == "EMAIL"){
  19.         $contact_email = $field["values"][0]["value"];
  20.       }
  21.     }
  22. /* The variable $text will contain the finished text, with the replaced variables for the data */
  23.   $text = $this->replaceWord($this->action['settings']['widget']['settings']['message'], $contact["contacts"][0]
  24. ["name"],$contact_phone,
  25. $contact_email);
  26. /* The function of permutation of markers in the text on previously received data */
  27. private function replaceWord($message, $contact_name, $contact_phone, $contact_email)
  28.   {
  29. foreach($this->macroses as $macros){
  30.       if($macros == "{{contact_name}}"){
  31.         $message = str_replace($macros, $contact_name, $message);
  32.       }
  33. if($macros == "{{contact_phone}}"){
  34.         $message = str_replace($macros, $contact_phone, $message);
  35.       }
  36.       if($macros == "{{contact_email}}"){
  37.         $message = str_replace($macros, $contact_email, $message);
  38.       }
  39.     return $message;
  40.   }
  41. /* Function of extracting the data of the element of the entity we are interested in (contact) */
  42. private function getContactById($id) {
  43.     $account = $this->account->current();
  44.     $link = 'https://'.$account['subdomain'].'.amocrm.com/private/api/v2/json/contacts/list?id[]='.$id;
  45.     $curl=curl_init();
  46.     curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  47.     curl_setopt($curl, CURLOPT_USERAGENT, 'amoCRM-API-client/1.0');
  48.     curl_setopt($curl, CURLOPT_URL, $link);
  49.     curl_setopt($curl, CURLOPT_HEADER, false);
  50.     curl_setopt($curl, CURLOPT_COOKIEFILE, dirname(__FILE__).'/cookie.txt');
  51.     curl_setopt($curl, CURLOPT_COOKIEJAR, dirname(__FILE__).'/cookie.txt');
  52.     curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
  53.     curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
  54.     $out=curl_exec($curl);
  55.     $code=curl_getinfo($curl,CURLINFO_HTTP_CODE);
  56.     curl_close($curl);
  57.     $response=json_decode($out,true);
  58.     $response=$response['response'];
  59.     return $response;
  60.   }
  61. private function GetData()
  62.   {
  63.     $event = \Helpers\Route::param("event");
  64.     $this->event = $event;
  65.     $action = \Helpers\Route::param("action");
  66.     $this->action = $action;
  67.     $amouser = \Helpers\Route::param("amouser");
  68.     $this->amouser = $amouser;
  69.     $amohash = \Helpers\Route::param("amohash");
  70.     $this->amohash = $amohash;
  71.   }

Next, you need to add the ability to specify macros in the message text in the quick setup area when you connect the widget in automatic actions for all leads in the digital pipeline.

  1. /* script.js, front-end part */
  2. dpSettings: function () {
  3.   w_code = self.get_settings().widget_code;
  4.   $('.digital-pipeline__edit-bubble').css({'width': '500px'});
  5.   var message_input = $(".digital-pipeline__short-task_widget-style_" +
  6. w_code).parent().parent().find("input[name=message]");
  7.   var message_input_label = message_input.parent().parent();
  8.   var message_textarea = self.render(
  9.     {ref: '/tmpl/controls/textarea.twig'},
  10.       {
  11.         id: 'dp_message',
  12.         value: message_input.val()
  13.       }
  14.   );
  15.   var dp_marker = '<div class="marker-list__block dp_marker_block">' +
  16.     '<p>Contact</p>' +
  17.     '<p class="marker-list__row"><span class="marker-list__tag-bot dp_marker_label" data-marker="{{contact_name}}"><span
  18. class="marker-
  19. list__tag">{{contact_name}}</span></span><span class="marker-list__tag-descr"> - Name of contact</span></p>' +
  20.     '<p class="marker-list__row"><span class="marker-list__tag-bot dp_marker_label" data-marker="{{contact_phone}}"><span
  21. class="marker-
  22. list__tag">{{contact_phone}}</span></span><span class="marker-list__tag-descr"> - Phone number of a contact</span></p>' +
  23.     '<p class="marker-list__row"><span class="marker-list__tag-bot dp_marker_label" data-marker="{{contact_email}}"><span
  24. class="marker-
  25. list__tag">{{contact_email}}</span></span><span class="marker-list__tag-descr"> - Email of contact</span></p>'
  26.     return true;
  27. }

Main Contact

In the event that in your integration there is a function of sending out any information, then it may be useful for you to send information only to the main contact. In entities, the lead and the buyer can have more than one contact, so the implementation of the function of sending information only to the main contact can be useful to users.

For example, one of the options for implementing this feature, for simple integration with a digital pipeline, which sends text messages.

Example of integration
  1. protected function endpoint_digital_pipeline() {
  2.         $model_type = intval(\Helpers\Route::param('event')['data']['element_type']);
  3.         $model_id = intval(\Helpers\Route::param('event')['data']['id']);
  4.         $message_text = \Helpers\Route::param('action')['settings']['widget']['settings']['message'];
  5.         $only_main = false;     //By default, the send to main contact feature will be turned off
  6.         if (!empty(\Helpers\Route::param('action')['settings']['widget']['settings']['only_main'])) {   //If chekbox not
  7. empty,
  8. assign true
  9.             $only_main = in_array(\Helpers\Route::param('action')['settings']['widget']['settings']['only_main'], ['on',
  10. TRUE, '1']);
  11.         }
  12.         $this->event($model_type, $model_id, $message_text, $only_main);
  13.     }
  14. /* Sending the received contacts to an array */
  15. private function event($model_type, $model_id, $message_text, $only_main = false){
  16.         $contacts = $this->getContacts($model_type, $model_id, $only_main);
  17.         foreach ($contacts as $contact) {
  18.             $this->sendMessage($message_text, $contact);    //sendMessage is your message sending function
  19.         }
  20.     }
  21. /* Get contacts function */
  22. private function getContacts($model_type, $model_id, $only_main = false) {
  23.         $contacts = [];
  24.         $links = null;
  25.         switch ($model_type) {  //A conditional construct for defining the type of an entity: a transaction (element_type = 2) or
  26. the customer
  27. (element_type = 12)
  28.             case 2:
  29.                 $links = $this->contacts->links(['deals_link' => $model_id]);
  30.                 break;
  31.             case 12:
  32.                 $links = $this->contacts->links(['customers_link' => $model_id]);
  33.                 break;
  34.         }
  35.         if (!$links) {
  36.             return $contacts;
  37.         }
  38.         $contact_ids = [];
  39.         foreach ($links as $link) {
  40.             $contact_ids[] = intval($link['contact_id']);
  41.             if ($only_main === true) {      //If the user has selected the mailing only to the main contact, after the first
  42. iteration of the loop -
  43. break. Thus, in the $contact_ids array, only the id of the primary contact
  44.                 break;
  45.             }
  46.         }
  47.         if (empty($contact_ids)) {
  48.             return $contacts;
  49.         }
  50.         $contacts = $this->contacts->get(['id' => $contact_ids]);
  51.         return $contacts;
  52.     }

Next, you need to add the ability to select a distribution only to the main contact in the quick setup area, when you connect the widget in automatic actions for all leads in the digital pipeline.

  1. /* script.js, front-end part */
  2. dpSettings: function () {
  3.    var lang = self.i18n('dp.settings');
  4.    var form = $('#widget_settings__fields_wrapper');
  5.    var field_divs = form.find('.widget_settings_block__input_field');
  6.    var textarea_div = field_divs.first();
  7.    textarea_div.html('<textarea name="message" ' +
  8.        'style="height:50px; width: 100%;" ' +
  9.        'id="message" ' +
  10.        'class="text-input text-input-textarea digital-pipeline__add-task-textarea textarea-autosize task-edit__textarea">'
  11. +
  12.        ''+ textarea_div.find('input').val() +
  13.        '</textarea>');
  14.    var checkbox_template = '<label class="control-checkbox">' +
  15.        '<div class="control-checkbox__body">' +
  16.        '<input type="checkbox" id=""/>' +
  17.        '<span class="control-checkbox__helper"></span>' +
  18.        '</div>' +
  19.        '<div class="control-checkbox__text element__text">' +
  20.        '<span class="control-checkbox__note-text">' + lang.only_main.name + '</span>' +
  21.        '</div>' +
  22.        '</div>' +
  23.        '</label>';
  24.    var checkbox_div = field_divs.last();
  25.    checkbox_div.siblings().html('');
  26.    checkbox_div.html(checkbox_template);
  27.    return true;
  28. }

Logging

In the event that, based on the results of your widget, you need to enter the appropriate notification information in the entity card, then we recommend using the addition of a system event. For more information about events and their types, see here.

Events are displayed in the cards along with the tasks, always in chronological order.

To add a system event, you must specify note_type = 25.

In the required text field, JSON is assigned in which two fields are indicated: text and service.

Example of integration
  1. /* Example of request to add a system message to the lead card */
  2. $subdomain='example';
  3. $data['add'] = array(
  4.     array(
  5.         'element_id'=>2789651,
  6.         'element_type'=>2,  //lead - 2, customer - 12
  7.         'note_type'=>25,
  8.         'params'=>array('text' => 'Message successfully added', 'service' => 'Your Service Name')
  9.     ));
  10. $link='https://'.$subdomain.'.amocrm.com/api/v2/notes';
  11. $curl=curl_init();
  12. curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
  13. curl_setopt($curl,CURLOPT_USERAGENT,'amoCRM-API-client/1.0');
  14. curl_setopt($curl,CURLOPT_URL,$link);
  15. curl_setopt($curl,CURLOPT_CUSTOMREQUEST,'POST');
  16. curl_setopt($curl,CURLOPT_POSTFIELDS,json_encode($data));
  17. curl_setopt($curl,CURLOPT_HTTPHEADER,array('Content-Type: application/json'));
  18. curl_setopt($curl,CURLOPT_HEADER,false);
  19. curl_setopt($curl,CURLOPT_COOKIEFILE,dirname(__FILE__).'/cookie.txt'); #PHP>5.3.6 dirname(__FILE__) -> __DIR__
  20. curl_setopt($curl,CURLOPT_COOKIEJAR,dirname(__FILE__).'/cookie.txt'); #PHP>5.3.6 dirname(__FILE__) -> __DIR__
  21. curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,0);
  22. curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,0);
  23. $out=curl_exec($curl);
  24. $code=curl_getinfo($curl,CURLINFO_HTTP_CODE);
  25. $code=(int)$code;
  26. $errors=array(
  27.     301=>'Moved permanently',
  28.     400=>'Bad request',
  29.     401=>'Unauthorized',
  30.     403=>'Forbidden',
  31.     404=>'Not found',
  32.     500=>'Internal server error',
  33.     502=>'Bad gateway',
  34.     503=>'Service unavailable'
  35. );
  36. try
  37. {
  38.     #If the response code is not 200 or 204, we return an error message
  39.   if($code!=200 && $code!=204)
  40.         throw new Exception(isset($errors[$code]) ? $errors[$code] : 'Undescribed error',(int)$code);
  41. }
  42. catch(Exception $E)
  43. {
  44.     die('Error: '.$E->getMessage().PHP_EOL.'Error code: '.$E->getCode());
  45. }
Salesbot connection

In amoCRM there is an opportunity to connect, already implemented, salesbot'a. This bot can be programmed to perform certain actions. It helps to receive data from users via messengers (Telegram, Facebook Messenger, Viber).

Detailed instructions on connecting, functionality, configuration, language and working with our merchant bot in the Salesbot section

Exchange information with external web servers

Each account in amoCRM at the advanced tariff and above has the ability to report on the actions to your web server. These "WebHooks" can be used to update information about leads in your store, send sms notifications or automate leads. Each WebHook can be configured for a specific operation and events.

WebHooks is the notification of third-party applications by sending notifications of events that occurred in amoCRM. For more information on the operation of WebHooks and the digital pipeline, see WebHook