amoCRM API PHP Library

repository·master·Indexed 41 days ago

https://github.com/amocrm/amocrm-api-php

A service-oriented PHP library for interacting with the amoCRM API. It provides a model-and-collection based interface for managing entities such as leads, contacts, and companies, with built-in support for OAuth 2.0, long-lived tokens, and batch processing. Requires PHP 7.1 or higher.

Tokens
18.6K
Snippets
52
Records
63
Agent score
51%

What's inside amoCRM

  1. Understand the service-oriented approach and data models

    master

    The library follows a service-oriented architecture. Each entity in amoCRM has a corresponding service. Data is managed through models and collections.

    Key concepts:

    • Services: Used to interact with specific entities.
    • Models: Represent individual data entities.
    • Collections: Groups of models.
    • Data Transformation: Models and collections provide two ways to view data:
      • toArray(): Returns the object as a standard PHP array.
      • toApi(): Returns the data in the specific format required by the amoCRM API for requests.
  2. Access amoCRM services via the API client

    master

    The library organizes API methods into service objects. To interact with a specific resource (like leads, contacts, or companies), call the corresponding method on the main API client instance. This returns a service object that contains the methods for that resource.

    $leadsService = $apiClient->leads();
  3. Work with custom entity fields

    master

    Custom fields are available for several services: leads, contacts, companies, customers, catalogElements, and segments.

    To access custom fields on a model, use the getCustomFieldsValues() method. This returns a CustomFieldsValuesCollection or null if no values exist.

    Inside the collection, you will find models that inherit from BaseCustomFieldValuesModel. These models provide methods to manage field data:

    • getFieldId() / setFieldId()
    • getFieldType()
    • getFieldCode() / setFieldCode()
    • getFieldName() / setFieldName()
    • getValues() / setValues()

    Note that getValues() returns a BaseCustomFieldValueCollection containing BaseCustomFieldValueModel objects. Because different field types (Text, Numeric, Checkbox, etc.) require different data structures, the library provides specific model and collection classes for each type located in the following namespaces:

    • Field value models: \AmoCRM\Models\CustomFieldsValues\ValueModels
    • Field value collections: \AmoCRM\Models\CustomFieldsValues\ValueCollections
    • Custom field models: \AmoCRM\Models\CustomFieldsValues
    // Create an entity model
    $lead = new LeadModel();
    $lead->setId(1);
    
    // Create a collection of custom fields
    $leadCustomFieldsValues = new CustomFieldsValuesCollection();
    
    // Create a model for a specific field type (e.g., Text)
    $textCustomFieldValuesModel = new TextCustomFieldValuesModel();
    $textCustomFieldValuesModel->setFieldId(123);
    
    // Add values to the field model
    $textCustomFieldValuesModel->setValues(
        (new TextCustomFieldValueCollection())
            ->add((new TextCustomFieldValueModel())->setValue('Text'))
    );
    
    // Add the field model to the entity's custom fields collection
    $leadCustomFieldsValues->add($textCustomFieldValuesModel);
    
    // Set the custom fields on the entity
    $lead->setCustomFieldsValues($leadCustomFieldsValues);
  4. Work with entity tags

    master

    Tags are managed via the tags service. When creating the service, specify the entity type (e.g., EntityTypesInterface::LEADS, CONTACTS, COMPANIES, or CUSTOMERS).

    To interact with tags, use the getTags() and setTags() methods on the specific entity model.

    Important: When updating tags, you must pass the entire collection of tags to setTags(), otherwise existing tags may be lost.

    To remove all tags from an entity, pass a \AmoCRM\Collections\NullTagsCollection object to setTags().

    // Example: Adding/Changing tags on a lead
    $lead = new LeadModel();
    $lead->setId(1);
    
    // Create a collection with new tags and set it
    $lead->setTags((new TagsCollection())
        ->add((new TagModel())->setName('tag'))
        ->add((new TagModel())->setId(123123))
    );
    
    // OR using fromArray
    $lead->setTags(TagsCollection::fromArray([
        ['name' => 'tag'],
        ['id' => 123],
    ]));
    
    // Example: Removing all tags
    $lead->setTags((new NullTagsCollection()));
  5. Use Long-Lived Tokens for authorization

    master

    For long-lived tokens, instantiate the client without credentials, create a \AmoCRM\Client\LongLivedAccessToken object, and set it in the client along with the account domain. These tokens remain valid until they expire or are revoked (revocation results in a 401 error).

    $apiClient = new \AmoCRM\Client\AmoCRMApiClient();
    $longLivedAccessToken = new LongLivedAccessToken($accessToken);
    
    $apiClient->setAccessToken($longLivedAccessToken)
        ->setAccountBaseDomain('example.amocrm.ru');
  6. Set up the examples environment

    master

    The repository includes an examples/ directory. To run these examples, you must create a .env file in that directory with your integration credentials.

    Required .env variables:

    • CLIENT_ID: Your integration's UUID.
    • CLIENT_SECRET: Your integration's secret key.
    • CLIENT_REDIRECT_URI: The exact redirect URI specified when creating your integration (e.g., https://example.com/examples/get_token.php).

    Running the examples:

    1. Start the local server using composer serve.
    2. Navigate to http://localhost:8181/examples/get_token.php in your browser to obtain an Access Token.
    3. If you need to expose your local server to the internet (for webhooks or callbacks), use a service like ngrok.io.

    Note: Ensure you update entity IDs within the examples to match your own amoCRM account data for correct functionality.

    CLIENT_ID="UUID интеграции"
    CLIENT_SECRET="Секретный ключ интеграции"
    CLIENT_REDIRECT_URI="https://example.com/examples/get_token.php"
    composer serve
  7. Redirect users for OAuth authorization

    master

    You can authorize users via two methods:

    1. Render an OAuth Button: Use getOAuthButton to generate a button for your UI.
    2. Direct Redirect: Use getAuthorizeUrl to get the URL to redirect the user to. You can specify the mode parameter: post_message (redirects in an open window) or popup (redirects in the parent window).

    After the user authorizes, use getAccessTokenByCode in your redirect URI handler to exchange the $_GET['code'] for an access token.

    // Method 1: Button
    $apiClient->getOAuthClient()->getOAuthButton([
        'title' => 'Установить интеграцию',
        'compact' => true,
        'class_name' => 'className',
        'color' => 'default',
        'error_callback' => 'handleOauthError',
        'state' => $state,
    ]);
    
    // Method 2: Direct URL
    $authorizationUrl = $apiClient->getOAuthClient()->getAuthorizeUrl([
        'state' => $state,
        'mode' => 'post_message',
    ]);
    header('Location: ' . $authorizationUrl);
    
    // In your redirect handler:
    $accessToken = $apiClient->getOAuthClient()->getAccessTokenByCode($_GET['code']);
  8. Handle account subdomain changes

    master

    If an account's subdomain changes, you can retrieve the current domain information using the access token. Use the returned AccountDomainModel to update your API client's base domain.

    use AmoCRM//Models/AccountDomainModel;
    
    // Get the domain model using the access token
    $accountDomain = $apiClient->getOAuthClient()->getAccountDomain($accessToken);
    
    // Update the API client with the new subdomain
    $apiClient->setAccountBaseDomain($accountDomain->getSubdomain());
  9. Configure Access Tokens and Account Domain

    master

    After initializing the client, you must provide an access token (an instance of \League\OAuth2\Client\Token\AccessToken) and set the account's base domain (e.g., SUBDOMAIN.amocrm.ru).

    You can use onAccessTokenRefresh to handle logic when a token is automatically refreshed, such as saving the new token to your database.

    $apiClient->setAccessToken($accessToken)
            ->setAccountBaseDomain($accessToken->getValues()['baseDomain'])
            ->onAccessTokenRefresh(
                function (\League\OAuth2\Client\Token\AccessTokenInterface $accessToken, string $baseDomain) {
                    saveToken(
                        [
                            'accessToken' => $accessToken->getToken(),
                            'refreshToken' => $accessToken->getRefreshToken(),
                            'expires' => $accessToken->getExpires(),
                            'baseDomain' => $baseDomain,
                        ]
                    );
                });
  10. Clear custom field values

    master

    To nullify (clear) the value of a custom field, use the \AmoCRM\Models\CustomFieldsValues\ValueCollections\NullCustomFieldValueCollection object when calling setValues() on a field model.

    // Create an entity model
    $lead = new LeadModel();
    $lead->setId(1);
    
    // Create a collection of custom fields
    $leadCustomFieldsValues = new CustomFieldsValuesCollection();
    
    // Create a model for a specific field type (e.g., Text)
    $textCustomFieldValuesModel = new TextCustomFieldValuesModel();
    $textCustomFieldValuesModel->setFieldId(123);
    
    // Nullify the values
    $textCustomFieldValuesModel->setValues(
        (new NullCustomFieldValueCollection())
    );
    
    // Add the field model to the entity's custom fields collection
    $leadCustomFieldsValues->add($textCustomFieldValuesModel);
    
    // Set the custom fields on the entity
    $lead->setCustomFieldsValues($leadCustomFieldsValues);
  11. Respect amoCRM API limits and security best practices

    master

    When using the library, adhere to the following operational guidelines:

    Batch Processing

    To ensure optimal performance and avoid hitting API limits, do not create or modify more than 50 entities at once when using methods that support batch processing.

    Error Handling and Security

    • Error Handling: Always implement error handling logic when making API calls.
    • Token Security: Protect your token storage carefully. A token leak can lead to a complete loss of access to the account.