Examples. Form for adding

For your special benefit, we have prepared training lessons on working with amoCRM mechanisms. These examples will help you to introduce yourself to the system in the shortest time possible and to use it to the maximum.

We have already described the process of developing a widget that adds a contact to amoCRM using a standard html-form. Now, we need to do the same using REST API.

Creating your own web-page

The example below demonstrates creation of a simple html-form for contact adding.

Let’s create a file with html-form and call it index.php

  1. <!DOCTYPE html>
  2.   <meta charset="utf-8">
  3.   <title>Adding contact</title>
  4. </head>
  5.   <div id="wrapper">
  6.     <header>
  7.       <h1>Adding contact</h1>
  8.     </header>
  9.     <div id="contact_form">
  10.       <form action="handler.php" method="post">
  11.         <div class="field">
  12.           <label for="contact_name">Name</label><input id="contact_name" type="text" name="name">
  13.         </div>
  14.         <div class="field">
  15.           <label for="contact_company">Company</label><input id="contact_company" type="text" name="company">
  16.         </div>
  17.         <div class="field">
  18.           <label for="contact_position">Position</label><input id="contact_position" type="text" name="position">
  19.         </div>
  20.         <div class="field">
  21.           <label for="contact_phone">Phone</label><input id="contact_phone" type="tel" name="phone">
  22.         </div>
  23.         <div class="field">
  24.           <label for="contact_email">E-mail</label><input id="contact_email" type="email" name="email">
  25.         </div>
  26.         <div class="field">
  27.           <label for="contact_web">Web-site</label><input id="contact_web" type="url" name="web">
  28.         </div>
  29.         <div class="field">
  30.           <label for="contact_jabber">Jabber</label><input id="contact_jabber" type="text" name="jabber">
  31.         </div>
  32.         <div class="field">
  33.           <label for="contact_scope">Scope</label>
  34.           <select id="contact_scope" name="scope[]" size="5" multiple>
  35.             <option value="it">IT, Telecommunications, Electronics</option>
  36.             <option value="auto">Auto repair, auto</option>
  37.             <option value="bookkeeping">Accounting, Auditing</option>
  38.             <option value="restaurants">Restaurants, fast food</option>
  39.             <option value="economy">Economy, Finances</option>
  40.           </select>
  41.         </div>
  42.         <div>
  43.           <button type="submit">Create contact</button>
  44.           <button type="reset">Clear form</button>
  45.         </div>
  46.       </form>
  47.     </div>
  48.   </div>
  49. </body>
  50. </html>

We will add styles to the form, so it would look or less decent. Let’s create main.css file containing the following:

  1. label
  2. {
  3.   float: left;
  4.   padding-right: 10px;
  5. }
  6.  
  7. #contact_form
  8. {
  9.   float: left;
  10.   margin: 6px 10px;
  11. }
  12.  
  13. .field
  14. {
  15.   clear: both;
  16.   text-align: right;
  17.   line-height: 2em;
  18. }

And enable styles in html-file described above. In order to do so, we must insert the following string into <head> tag, right after </title> tag:

<link rel="stylesheet" type="text/css" href="main.css" media="all">

Programming a logic

For illustration purpose, we will derive separate logical blocks into different files and connect files sequentially. You can develop your own architecture for your application interacting with our API.

Controller

Let’s create handler.php file. It will connect a number of files, each performing a certain task.

  1. <?php
  2. $root=__DIR__.DIRECTORY_SEPARATOR;
  3. require $root.'prepare.php'; # There will be carried out preparatory acts, declarations of functions, etc.
  4. require $root.'auth.php'; # There will be user authentication
  5. require $root.'account_current.php'; # Here we will receive information about account
  6. require $root.'fields_info.php'; # Obtain information about the fields
  7. require $root.'contacts_list.php'; # Obtain contact information
  8. require $root.'contact_add.php'; # There will be adding a contact
  9. ?>

Preparation

We will prepare.php file, where preparative actions will be performed: declaring of functions that we will need further and parsing of incoming data.

  1. function CheckCurlResponse($code)
  2. {
  3.   $code=(int)$code;
  4.   $errors=array(
  5.     301=>'Moved permanently',
  6.     400=>'Bad request',
  7.     401=>'Unauthorized',
  8.     403=>'Forbidden',
  9.     404=>'Not found',
  10.     500=>'Internal server error',
  11.     502=>'Bad gateway',
  12.     503=>'Service unavailable'
  13.   );
  14.   try
  15.   {
  16.     # If the response code is not equal to 200 or 204 - returns an error message
  17.     if($code!=200 && $code!=204)
  18.       throw new Exception(isset($errors[$code]) ? $errors[$code] : 'Undescribed error',$code);
  19.   }
  20.   catch(Exception $E)
  21.   {
  22.     die('Error: '.$E->getMessage().PHP_EOL.'Error code: '.$E->getCode());
  23.   }
  24. }
  25.  
  26. $data=array(
  27.   'name'=>isset($_POST['name']) ? $_POST['name'] : 'ss',
  28.   'company'=>isset($_POST['company']) ? $_POST['company'] : '',
  29.   'position'=>isset($_POST['position']) ? $_POST['position'] : '',
  30.   'phone'=>isset($_POST['phone']) ? $_POST['phone'] : '',
  31.   'email'=>isset($_POST['email']) ? $_POST['email'] : 'sd',
  32.   'web'=>isset($_POST['web']) ? $_POST['web'] : '',
  33.   'jabber'=>isset($_POST['jabber']) ? $_POST['jabber'] : '',
  34.   'scope'=>isset($_POST['scope']) && is_array($_POST['scope']) ? $_POST['scope'] : array()
  35. );
  36.  
  37. $scope_info=array(
  38.   'it'=>'IT, Telecommunications, Electronics',
  39.   'auto'=>'Auto repair, auto',
  40.   'bookkeeping'=>'Accounting, Auditing',
  41.   'restaurants'=>'Restaurants, fast food',
  42.   'economy'=>'Economy, Finances'
  43. );
  44.  
  45. # If no name or e-mail contact - notify
  46. if(empty($data['name']))
  47.   die('Not filled contact name');
  48. if(empty($data['email']))
  49.   die('Not filled contact email');

Authorization procedure

Authorization procedure is described in details in documentation. All you have to do is create auth.php file and copy the code there after replacing authorization data your credentials. The result will be something like this:

  1. # An array of parameters that must be passed by the POST method to the API
  2. $user=array(
  3.   'USER_LOGIN'=>'test@testmail.com', # Your login (email)
  4.   'USER_HASH'=>'7ebefd1d4741106a4daa0e0a673bba2e4dc16054' # Hash to access the API (see profile)
  5. );
  6.  
  7. $subdomain='test'; # Your account (subdomain)
  8. # Create a link for request
  9. $link='https://'.$subdomain.'.amocrm.com/private/api/auth.php?type=json';
  10. $curl=curl_init(); # Save the cURL session handle
  11. # Set the necessary options for cURL session
  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_POST,true);
  16. curl_setopt($curl,CURLOPT_POSTFIELDS,http_build_query($user));
  17. curl_setopt($curl,CURLOPT_HEADER,false);
  18. curl_setopt($curl,CURLOPT_COOKIEFILE,dirname(__FILE__).'/cookie.txt'); #PHP>5.3.6 dirname(__FILE__) -> __DIR__
  19. curl_setopt($curl,CURLOPT_COOKIEJAR,dirname(__FILE__).'/cookie.txt'); #PHP>5.3.6 dirname(__FILE__) -> __DIR__
  20. curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,0);
  21. curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,0);
  22.  
  23. $out=curl_exec($curl); # Initiate a request to the API and stores the response to variable
  24. $code=curl_getinfo($curl,CURLINFO_HTTP_CODE); # Obtain the HTTP-server response code
  25. curl_close($curl); # Close cURL session
  26. CheckCurlResponse($code);
  27. /**
  28.  * Obtain data in JSON-format, therefore, to obtain the data being read,
  29.  * we have to translate the answer into a format understood by PHP
  30.  */
  31. $Response=json_decode($out,true);
  32. $Response=$Response['response'];
  33. if(isset($Response['auth'])) # Flag of authorization is available in the property "auth"
  34.   return 'Authorization successful';
  35. return 'Authorization failed';

Obtaining information on the current account

The procedure of obtaining information on the current account is described in details in documentation. All you have to do is create account_current.php file and copy the code there. The result will be something like this:

  1. $link='https://'.$subdomain.'.amocrm.com/private/api/v2/json/accounts/current'; #$subdomain already announced above
  2. $curl=curl_init(); # Save the cURL session handle
  3. # Set the necessary options for cURL session
  4. curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
  5. curl_setopt($curl,CURLOPT_USERAGENT,'amoCRM-API-client/1.0');
  6. curl_setopt($curl,CURLOPT_URL,$link);
  7. curl_setopt($curl,CURLOPT_HEADER,false);
  8. curl_setopt($curl,CURLOPT_COOKIEFILE,dirname(__FILE__).'/cookie.txt'); #PHP>5.3.6 dirname(__FILE__) -> __DIR__
  9. curl_setopt($curl,CURLOPT_COOKIEJAR,dirname(__FILE__).'/cookie.txt'); #PHP>5.3.6 dirname(__FILE__) -> __DIR__
  10. curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,0);
  11. curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,0);
  12.  
  13. $out=curl_exec($curl); # Initiate a request to the API and stores the response to variable
  14. $code=curl_getinfo($curl,CURLINFO_HTTP_CODE);
  15. curl_close($curl);
  16. CheckCurlResponse($code);
  17. /**
  18.  * Obtain data in JSON-format, therefore, to obtain the data being read,
  19.  * we have to translate the answer into a format understood by PHP
  20.  */
  21. $Response=json_decode($out,true);
  22. $account=$Response['response']['account'];

Obtaining a filtered contact list

The procedure of obtaining a filtered contact list is described in details in documentation. All you have to do is create contacts_list.php file and copy the code there. The result will be something like this:

  1. $link='https://'.$subdomain.'.amocrm.com/private/api/v2/json/contacts/list?query='.$data['email'];
  2. $curl=curl_init(); # Save the cURL session handle
  3. # Set the necessary options for cURL session
  4. curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
  5. curl_setopt($curl,CURLOPT_USERAGENT,'amoCRM-API-client/1.0');
  6. curl_setopt($curl,CURLOPT_URL,$link);
  7. curl_setopt($curl,CURLOPT_HEADER,false);
  8. curl_setopt($curl,CURLOPT_COOKIEFILE,dirname(__FILE__).'/cookie.txt'); #PHP>5.3.6 dirname(__FILE__) -> __DIR__
  9. curl_setopt($curl,CURLOPT_COOKIEJAR,dirname(__FILE__).'/cookie.txt'); #PHP>5.3.6 dirname(__FILE__) -> __DIR__
  10. curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,0);
  11. curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,0);
  12.  
  13. $out=curl_exec($curl); # Initiate a request to the API and stores the response to variable
  14. $code=curl_getinfo($curl,CURLINFO_HTTP_CODE);
  15. curl_close($curl);
  16. CheckCurlResponse($code);
  17. if($out)
  18.   die('Such contact already exists in amoCRM');

Obtaining field information

Let’s create fields_info.php file and process the account information (obtained above) in order to obtain field information.

  1. $need=array_flip(array('POSITION','PHONE','EMAIL','WEB','IM','SCOPE'));
  2. if(isset($account['custom_fields'],$account['custom_fields']['contacts']))
  3.   do
  4.   {
  5.     foreach($account['custom_fields']['contacts'] as $field)
  6.       if(is_array($field) && isset($field['id']))
  7.       {
  8.         if(isset($field['code']) && isset($need[$field['code']]))
  9.           $fields[$field['code']]=(int)$field['id'];
  10.         #SCOPE - non-standard field, so treat it separately
  11.         elseif(isset($field['name']) && $field['name']=='Scope')
  12.           $fields['SCOPE']=$field;
  13.        
  14.         $diff=array_diff_key($need,$fields);
  15.         if(empty($diff))
  16.           break 2;
  17.       }
  18.       if(isset($diff))
  19.         die('In amoCRM missing the following fields: ' . join(', ',$diff));
  20.       else
  21.         die('Unable to get additional fields');
  22.     }
  23.   while(false);
  24. else
  25.   die('Unable to get additional fields');
  26. $custom_fields=isset($fields) ? $fields : false;

Adding a contact

The procedure of adding a contact/contacts is described in details in documentation. Let’s create contact_add.php file. It will perform forming of the array with collected data as well as the very process of adding contact to amoCRM.

  1. $contact=array(
  2.       'name'=>$data['name'],
  3.       'custom_fields'=>array(
  4.         array(
  5.           'id'=>$custom_fields['EMAIL'],
  6.           'values'=>array(
  7.             array(
  8.               'value'=>$data['email'],
  9.               'enum'=>'WORK'
  10.             )
  11.           )
  12.         )
  13.       )
  14.     );
  15.    
  16. if(!empty($data['company']))
  17.   $contact+=array('company_name'=>$data['company']);
  18. if(!empty($data['position']))
  19.   $contact['custom_fields'][]=array(
  20.     'id'=>$custom_fields['POSITION'],
  21.     'values'=>array(
  22.       array(
  23.         'value'=>$data['position']
  24.       )
  25.     )
  26. );
  27. if(!empty($data['phone']))
  28.   $contact['custom_fields'][]=array(
  29.     'id'=>$custom_fields['PHONE'],
  30.     'values'=>array(
  31.       array(
  32.         'value'=>$data['phone'],
  33.         'enum'=>'OTHER'
  34.       )
  35.     )
  36. );
  37. if(!empty($data['web']))
  38.   $contact['custom_fields'][]=array(
  39.     'id'=>$custom_fields['WEB'],
  40.     'values'=>array(
  41.       array(
  42.         'value'=>$data['web']
  43.       )
  44.     )
  45.   );
  46. if(!empty($data['jabber']))
  47.   $contact['custom_fields'][]=array(
  48.     'id'=>$custom_fields['IM'],
  49.     'values'=>array(
  50.       array(
  51.         'value'=>$data['jabber'],
  52.         'enum'=>'JABBER'
  53.       )
  54.     )
  55.   );
  56. if(!empty($data['scope']))
  57. {
  58.   foreach($data['scope'] as &$enum)
  59.     $enum=trim($scope_info[$enum]);
  60.   unset($enum);
  61.   $intersect=array_intersect($custom_fields['SCOPE']['enums'],$data['scope']);
  62.   foreach($intersect as $v)
  63.     $values[]=$v;
  64.  
  65.   $scope=array(
  66.     'id'=>(int)$custom_fields['SCOPE']['id'],
  67.     'values'=>$values
  68.   );
  69.      
  70.   $contact['custom_fields'][]=$scope;
  71. }
  72. $set['request']['contacts']['add'][]=$contact;
  73.  
  74. # Create a link for request
  75. $link='https://'.$subdomain.'.amocrm.com/private/api/v2/json/contacts/set';
  76. $curl=curl_init(); # Save the cURL session handle
  77. # Set the necessary options for cURL session
  78. curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
  79. curl_setopt($curl,CURLOPT_USERAGENT,'amoCRM-API-client/1.0');
  80. curl_setopt($curl,CURLOPT_URL,$link);
  81. curl_setopt($curl,CURLOPT_CUSTOMREQUEST,'POST');
  82. curl_setopt($curl,CURLOPT_POSTFIELDS,json_encode($set));
  83. curl_setopt($curl,CURLOPT_HTTPHEADER,array('Content-Type: application/json'));
  84. curl_setopt($curl,CURLOPT_HEADER,false);
  85. curl_setopt($curl,CURLOPT_COOKIEFILE,dirname(__FILE__).'/cookie.txt'); #PHP>5.3.6 dirname(__FILE__) -> __DIR__
  86. curl_setopt($curl,CURLOPT_COOKIEJAR,dirname(__FILE__).'/cookie.txt'); #PHP>5.3.6 dirname(__FILE__) -> __DIR__
  87. curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,0);
  88. curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,0);
  89.  
  90. $out=curl_exec($curl); # Initiate a request to the API and stores the response to variable
  91. $code=curl_getinfo($curl,CURLINFO_HTTP_CODE);
  92. CheckCurlResponse($code);
  93.  
  94. /**
  95.  * Obtain data in JSON-format, therefore, to obtain the data being read,
  96.  * we have to translate the answer into a format understood by PHP
  97.  */
  98. $Response=json_decode($out,true);
  99. $Response=$Response['response']['contacts']['add'];
  100.  
  101. $output='Added contacts IDs:'.PHP_EOL;
  102. foreach($Response as $v)
  103.   if(is_array($v))
  104.     $output.=$v['id'].PHP_EOL;
  105. return $output;

Download a sample of submission forms

Download