PHP code example of ufee / amoapi

1. Go to this page and download the library: Download ufee/amoapi library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

ufee / amoapi example snippets


\Ufee\Amo\Oauthapi::setOauthStorage(
	new \Ufee\Amo\Base\Storage\Oauth\FileStorage(['path' => '/full/oauth/path'])
);

$redis = new \Redis();
$redis->connect('/var/run/redis/redis.sock');
$redis->setOption(\Redis::OPT_SERIALIZER, \Redis::SERIALIZER_PHP);
$redis->select(5); // switch to specific db

\Ufee\Amo\Oauthapi::setOauthStorage(
	new \Ufee\Amo\Base\Storage\Oauth\RedisStorage(['connection' => $redis])
);

$mongo = new \MongoDB\Client('mongodb://host');
$collection = $mongo->selectCollection('database', 'some_collection');

\Ufee\Amo\Oauthapi::setOauthStorage(
	new \Ufee\Amo\Base\Storage\Oauth\MongoDbStorage(['collection' => $collection])
);

class CustomOauthStorage extends \Ufee\Amo\Base\Storage\Oauth\AbstractStorage
{
	protected function initClient(Oauthapi $client) {
		parent::initClient($client);
		$key = $client->getAuth('domain').'_'.$client->getAuth('client_id');
		if ($data = getClientOauthData($key)) {
			static::$_oauth[$key] = $data;
		}
	}
	public function setOauthData(Oauthapi $client, array $oauth) {
		parent::setOauthData($client, $oauth);
		$key = $client->getAuth('domain').'_'.$client->getAuth('client_id');
		return setClientOauthData($key, $oauth);
	}
}
\Ufee\Amo\Oauthapi::setOauthStorage(
	new CustomOauthStorage()
);

\Ufee\Amo\Oauthapi::setOauthStorage(
	new \Ufee\Amo\Base\Storage\Oauth\AbstractStorage()
);
$amo = \Ufee\Amo\Oauthapi::setInstance([...]);
$first_token = $amo->fetchAccessToken($code);
saveToCustomStorage($first_token);
$last_saved_token = getFromCustomStorage();
$amo->setOauth($last_saved_token);
$amo->onAccessTokenRefresh(function($oauth) {
	saveToCustomStorage($oauth);
});

$amo->setOauthPath('path_to/oauth');
// equal to new method
\Ufee\Amo\Oauthapi::setOauthStorage(
    new \Ufee\Amo\Base\Storage\Oauth\FileStorage(['path' => 'path_to/oauth'])
);

$amo = \Ufee\Amo\Oauthapi::setInstance([
    'domain' => 'testdomain',
    'client_id' => 'b6cf0658-b19...', // id приложения
    'client_secret' => 'D546t4yRlOprfZ...',
    'redirect_uri' => 'https://site.ru/amocrm/oauth/redirect',
    'zone' => 'ru', // or com
    'timezone' => 'Europe/Moscow',
    'lang' => 'ru', // or en
    'user_agent' => '' // ifempty = Amoapi v.<version> (<client_id>)
]);
$amo->setAuth('user_agent', 'MyCustomUserAgent');

$amo = \Ufee\Amo\Oauthapi::getInstance('b6cf0658-b19...');

$first_auth_url = $amo->getOauthUrl($arg = ['mode' => 'popup', 'state' => 'amoapi']);

$oauth = $amo->fetchAccessToken($code);

$amo->setOauth([
	'token_type' => 'Bearer',
	'expires_in' => 86400,
	'access_token' => 'bKSuyc4u6oi...',
	'refresh_token' => 'a89iHvS9uR4...',
	'created_at' => 1597678161
]);

$oauth = $amo->refreshAccessToken($refresh_token = null); // при передаче null используются кешированные oauth данные

$amo->onAccessTokenRefresh(function($oauth, $query, $response) {
	echo $query->startDate().' - ['.$query->method.'] '.$query->getUrl()."\n";
	print_r($query->post_data);
	echo $query->endDate().' - ['.$response->getCode().'] '. $response->getData(). "\n\n";
	echo "\nRefreshed oauth: \n";
	print_r($oauth);
});
$amo->onAccessTokenRefreshError(function($exc, $query, $response) {
	echo $query->startDate().' - ['.$query->method.'] '.$query->getUrl()."\n";
	print_r($query->post_data);
	echo $query->endDate().' - ['.$response->getCode().'] '. $response->getData(). "\n\n";
	exit('Error refresh token: '.$exc->getMessage().', code: '.$exc->getCode());
});

$resp_code = $amo->ajax()->exchangeApiKey(
	$crm_login, 
	$api_hash, 
	$client_id, 
	$client_secret
);
if ($resp_code === 202) {
	// Запрос принят, код авторизации будет отправлен на redirect_uri
}

$amo = \Ufee\Amo\Amoapi::setInstance([
    'id' => 123,
    'domain' => 'testdomain',
    'login' => 'test@login',
    'hash' => 'testhash',
    'zone' => 'com', // default: ru
    'timezone' => 'Europe/London', // default: Europe/Moscow
    'lang' => 'en' // default: ru
]);

$amo->autoAuth(true); // true/false, рекомендуется true

$amo->queries->logs(true); // to default path

$amo->queries->logs('path_to_log/queries'); // to custom path

$amo->queries->setDelay(0.5); // default: 0.15 sec

\Ufee\Amo\Services\Account::setCacheTime(1800); // default: 600 sec

$amo->queries->onResponseCode(429, function(\Ufee\Amo\Base\Models\QueryModel $query) {
	echo 'Resp code 429, retry '.$query->retries."\n";
});
$amo->queries->listen(function(\Ufee\Amo\Base\Models\QueryModel $query) {
    $code = $query->response->getCode();
    echo $query->startDate().' - ['.$query->method.'] '.$query->getUrl()."\n";
    print_r($query->headers);
    if ($code === 0) {
        echo $query->response->getError()."\n\n";
    } else {
        print_r(count($query->json_data) ? $query->json_data : $query->post_data);
        echo $query->endDate().' - ['.$query->response->getCode().'] '.$query->response->getData()."\n\n";
    }
});

$apiClient->queries->setCacheStorage(
	new \Ufee\Amo\Base\Storage\Query\FileStorage($apiClient, ['path' => 'pull_path_to/cache'])
);

$redis = new \Redis();
$redis->connect('/var/run/redis/redis.sock');
$redis->setOption(\Redis::OPT_SERIALIZER, \Redis::SERIALIZER_PHP); // \Redis::SERIALIZER_IGBINARY recommended
$redis->select(5); // switch to specific db

$apiClient->queries->setCacheStorage(
	new \Ufee\Amo\Base\Storage\Query\RedisStorage($apiClient, ['connection' => $redis])
);

$leads = $amo->leads()->searchByCustomField('Москва', 'Город', 300); // by CF name, max 300
$leads = $amo->leads()->searchByCustomField('Москва', 623425); // by CF id
$companies = $amo->companies()->searchByName('ООО Шарики за Ролики', 100); // by name, max 100
$contacts = $amo->contacts()->searchByEmail('[email protected]', 0); // by email, no max limit
$contacts = $amo->contacts()->searchByPhone('89271002030');

$entity->cf('Имя поля')->reset();
$entity->cf('Организация')->removeBy('name', 'ИП Петров А.А.');

$entity->cf('Имя поля')->getValue();
$entity->cf('Имя поля')->getValues();
$entity->cf('Имя поля')->getEnums();
$entity->cf('Дата')->format('Y-m-d');
$entity->cf('Дата')->getTimestamp();
$entity->cf('Организация')->getValues();

$entity->cf('Имя поля')->setEnum($enum);
$entity->cf('Имя поля')->setEnums($enums);
$entity->cf('Число')->setValue(5);
$entity->cf('Текст')->setValue('Test');
$entity->cf('Мультисписок')->reset()->setValues(['Мужская одежда', 'Аксессуары']);
$entity->cf('День рождения')->setDate('Y-m-d');
$entity->cf('Дата')->setTimestamp(14867456357);
$entity->cf('Дата')->setDate('Y-m-d');
$entity->cf('Переключатель')->enable();
$entity->cf('Переключатель')->disable();
$entity->cf('Полный адрес')->setCountry('Россия');
$entity->cf('Полный адрес')->setRegion('Чувашская республика');
$entity->cf('Полный адрес')->setCity('Чебоксары');
$entity->cf('Полный адрес')->setIndex(428000);
$entity->cf('Телефон')->setValue('987654321', 'Home');
$entity->cf('Телефон')->setValue('123456789');
$entity->cf('Email')->setValue('[email protected]');
$entity->cf('Мгн. сообщения')->setValue('bestJa', 'Jabber');
$entity->cf('Юр. лицо')->setName('Команда F5');
$entity->cf('Юр. лицо')->setAddress('РФ, ЧР, г.Чебоксары');
$entity->cf('Юр. лицо')->setType(1);
$entity->cf('Юр. лицо')->setInn(123);
$entity->cf('Юр. лицо')->setKpp(456);
$entity->cf('Организация')->addValue([
    'name' => 'ИП Петров А.А.',
    'city' => 'Москва',
    '...' => '...'
]);

foreach ($amo->leads as $lead) { ... }
$amo->leads->each(function(&$lead) { ... });
$leadsByCf = $amo->leads->find('name', 'Трубы гофрированные');
$leadsBySale = $amo->leads->filter(function($lead) {
    return $lead->sale > 0;
});
$firstLead = $lead->first();
$lastLead = $lead->last();

$leads->sortBy('sale', 'DESC');
$leads->usort(function($a, $b) {});
$leads->uasort(function($a, $b) {});

$has_contains =  $leads->contains('name', 'Test');
$sale_sum = $leads->sum('sale');
$leads = $leads->transform(function($lead) {
    return [
        'id' => $lead->id,
        'name' => $lead->name
    ];
});
$leads_array = $leads->toArray();

$leads = $amo->leads;
$leads = $amo->leads()->recursiveCall();
$leads = $amo->leads()->call(); // первые 500

$leads = $amo->leads()
             ->modifiedFrom('Y-m-5 09:20:00') // по дате, с 5 числа текущего месяца, с 9:20 утра
             ->modifiedFrom(1528188143) // или по timestamp
             ->maxRows(1000)
             ->listing();

$lead = $amo->leads()->find($id); // array|integer

$lead = $amo->leads()->where('key', $val)->recursiveCall();

$contact = $lead->contact;
$contacts = $lead->contacts;
$company = $lead->company;
$tasks = $lead->tasks;
$notes = $lead->notes;

$leads = [
    $amo->leads()->create(),
    $amo->leads()->create()
];
$leads[0]->name = 'Amoapi v7 - 1';
$leads[1]->name = 'Amoapi v7 - 2';
$amo->leads()->add($leads);

$lead = $amo->leads()->create();
$lead->name = 'Amoapi v7';
$lead->attachTag('Amoapi');
$lead->pipeline_id = $amo->account->pipelines->main();
$lead->status_id = $lead->pipeline->statuses->first();
$lead->responsible_user_id = $amo->account->currentUser->id;
$lead->sale = 100500;
$lead->cf('Число')->setValue(5);
$lead->cf('Текст')->setValue('Test');
$lead->cf('Мультисписок')->reset()->setValues(['Мужская одежда', 'Аксессуары']);
$lead->cf('Дата')->setValue(date('Y-m-d'));
$lead->cf('Переключатель')->disable();
$lead->save();

$lead = $contact->createLead();
$lead->name = 'Amoapi v7';
$lead->save();

$copy = clone $lead;
$copy->name = 'New lead';
$copy->save();

$contacts = $amo->contacts;
$contacts = $amo->contacts()->recursiveCall();
$contacts = $amo->contacts()->call(); // первые 500

$contact = $amo->contacts()->find($id); // array|integer

$contacts = $amo->contacts()->where('key', $val)->recursiveCall();

$leads = $contact->leads;
$company = $contact->company;
$tasks = $lead->tasks;
$notes = $lead->notes;

$contacts = [
    $amo->contacts()->create(),
    $amo->contacts()->create()
];
$contacts[0]->name = 'Amoapi v7 - 1';
$contacts[1]->name = 'Amoapi v7 - 2';
$amo->contacts()->add($contacts);

$contact = $amo->contacts()->create();
$contact->name = 'Amoapi v7';
$contact->attachTags(['Amoapi', 'Test']);
$contact->cf('Телефон')->setValue('987654321', 'Home');
$contact->cf('Телефон')->setValue('123456789');
$contact->cf('Email')->setValue('[email protected]');
$contact->save();

$contact = $lead->createContact();
$contact->name = 'Amoapi v7';
$contact->save();

$copy = clone $contact;
$copy->name = 'New contact';
$copy->save();

$companies = $amo->companies;
$companies = $amo->companies()->recursiveCall();
$companies = $amo->companies()->call(); // первые 500

$company = $amo->companies()->find($id); // array|integer

$companies = $amo->companies()->where('key', $val)->recursiveCall();

$leads = $company->leads;
$contacts = $company->contacts;
$tasks = $lead->tasks;
$notes = $lead->notes;

$companys = [
    $amo->companies()->create(),
    $amo->companies()->create()
];
$companys[0]->name = 'Amoapi v7 - 1';
$companys[1]->name = 'Amoapi v7 - 2';
$amo->companies()->add($companys);

$company = $amo->companies()->create();
$company->name = 'Amoapi v7';
$company->save();

$company = $contact->createCompany();
$company = $lead->createCompany();
$company->name = 'Amoapi v7';
$company->save();

$copy = clone $company;
$copy->name = 'New company';
$copy->save();

$tasks = $amo->tasks;
$tasks = $amo->tasks()->recursiveCall();
$tasks = $amo->tasks()->call(); // первые 500

$task = $amo->tasks()->find($id); // array|integer

$tasks = $amo->tasks()->where('key', $val)->recursiveCall();

$tasks = [
    $amo->tasks()->create(),
    $amo->tasks()->create()
];
$tasks[0]->text = 'Amoapi v7 - 1';
$tasks[0]->element_type = 3;
$tasks[0]->element_id = 34762721;
$tasks[1]->text = 'Amoapi v7 - 2';
$tasks[1]->element_type = 2;
$tasks[1]->element_id = 34762720;
$amo->tasks()->add($tasks);

$task = $amo->tasks()->create();
$task->text = 'Amoapi v7';
$task->element_type = 1;
$task->element_id = 34762725;
$task->save();

$task = $contact->createTask($type = 1);
$task = $lead->createTask($type = 1);
$task = $company->createTask($type = 1);
$task->text = 'Amoapi v7';
$task->element_type = 1;
$task->element_id = 34762725;
$task->save();

$contact = $task->linkedContact;
$lead = $task->linkedLead;
$comapny = $task->linkedCompany;

$notes = $amo->notes;
$notes = $amo->notes()->where('type', 'contact')->recursiveCall();
$notes = $amo->notes()->where('type', 'lead')->call(); // первые 500

$note = $amo->notes()->find($id, 'lead');

$notes = $amo->notes()->where('key', $val)->recursiveCall();

$notes = [
    $amo->notes()->create(), 
    $amo->notes()->create()
];
$notes[0]->note_type = 4;
$notes[0]->text = 'Amoapi v7 - 1';
$notes[0]->element_type = 3;
$notes[0]->element_id = 34762721;
$notes[1]->note_type = 4;
$notes[1]->text = 'Amoapi v7 - 2';
$notes[1]->element_type = 2;
$notes[1]->element_id = 34762720;
$amo->notes()->add($notes);

$note = $amo->notes()->create();
$note->note_type = 4;
$note->text = 'Amoapi v7';
$note->element_type = 1;
$note->element_id = 34762725;
$note->save();

$note = $contact->createNote($type = 4);
$note = $lead->createNote($type = 4);
$note = $company->createNote($type = 4);
$note->text = 'Amoapi v7';
$note->element_type = 2;
$note->element_id = 34762728;
$note->save();

$note->setPinned(true); // true/false

$contents = $note->getAttachment();

$contact = $note->linkedContact;
$lead = $note->linkedLead;
$comapny = $note->linkedCompany;

$catalogs = $amo->catalogs;

$catalog = $amo->catalogs()->find($id); // array|integer

$catalogs = $amo->catalogs()->where('key', $val)->call();

$elements = $catalog->elements;

$catalogs = [
    $amo->catalogs()->create(),
    $amo->catalogs()->create()
];
$catalogs[0]->name = 'Amoapi v7 - 1';
$catalogs[1]->name = 'Amoapi v7 - 2';
$amo->catalogs()->add($catalogs);

$catalog = $amo->catalogs()->create();
$catalog->name = 'Amoapi v7';
$catalog->save();

$amo->catalogs()->delete($catalogs); // array|integer
$catalog->delete();

$element = $amo->catalogElements()->find($id);
$elements = $amo->catalogElements()->where('catalog_id', 1234)->call();
$elements = $catalog->elements;

$element = $amo->catalogElements()->create();
$element->catalog_id = 1234;

$element = $catalog->createElement();
$element->name = 'Холодильник LG';
$element->cf('Артикул')->setValue('ML-4675');
$element->cf('Количество')->setValue(100);
$element->cf('Цена')->setValue(38500);
$element->save();

$element->cf('Скидка')->setValue(5);
$element->save();

$catalog = $element->catalog;
$leads = $element->leads;

$amo->elements()->delete($elements); // array|integer
$catalog->elements->delete(); // удаление всех товаров каталога
$element->delete();

$lead->attachElement($catalog->id, $element->id, $count = 1);

$customers = $amo->customers;
$customers = $amo->customers()->recursiveCall();
$customers = $amo->customers()->call(); // первые 500

$customer = $amo->customers()->find($id); // array|integer

$customer = $amo->customers()->where('key', $val)->recursiveCall();

$contact = $customer->contact;
$contacts = $customer->contacts;
$company = $customer->company;
$tasks = $customer->tasks;
$notes = $customer->notes;
$transactions = $customer->transactions;

$customer = $amo->customers()->create();
$customer->name = 'Amoapi v7';
$customer->next_date = time();
$customer->next_price = 100;
$customer->responsible_user_id = $amo->account->currentUser->id;
$customer->cf('Число')->setValue(5);
$customer->cf('Текст')->setValue('Test');
$customer->cf('Мультисписок')->reset()->setValues(['Мужская одежда', 'Аксессуары']);
$customer->cf('Дата')->setValue(date('Y-m-d'));
$customer->cf('Переключатель')->disable();
$customer->save();

$customer = $contact->createCustomer();
$customer->name = 'Amoapi v7';
$customer->next_date = time();
$customer->save();

$amo->customers()->delete($customers); // array|integer
$customer->delete();

$transactions = $amo->transactions;
$transactions = $customer->transactions;

$transaction = $amo->transactions()->create();
$transaction->customer_id = 1234;

$transaction = $customer->createTransaction();
$transaction->price = 1500;
$transaction->save();

$transaction->comment = 'Тест';
$transaction->save();

$amo->transactions()->delete($transactions); // array|integer
$customer->transactions->delete(); // удаление всех покупок покупателя
$transaction->delete(); // удаление покупки

$webhooks = $amo->webhooks;

$result = $amo->webhooks()->subscribe('http://site.ru/handler/', ['add_lead', 'update_contact', 'responsible_lead']);

$result = $amo->webhooks()->unsubscribe('http://site.ru/handler/', ['update_contact', 'responsible_lead']);

$contents = $amo->ajax()->getAttachment('AbCd_attach_name.zip');

$amo->ajax()->get($url = '/ajax/example', $args = []);
$amo->ajax()->post($url = '/ajax/example', $data = [], $args = [], $post_type = 'raw OR json');
$amo->ajax()->postJson($url = '/ajax/example', $data = [], $args = []);
$amo->ajax()->patch($url = '/ajax/example', $data = [], $args = []);

$bots = $amo->salesbots()->get($page = 1, $limit = 250);
$bots = $amo->salesbots;

$start = $amo->salesbots()->start($bot_id, $entity_id, $entity_type = 2);
$stop = $amo->salesbots()->stop($bot_id, $entity_id, $entity_type = 2);