Coder Social home page Coder Social logo

bitrix24-php-sdk's Introduction

Bitrix24 REST API PHP SDK

License Total Downloads Latest Stable Version

A powerful PHP library for the Bitrix24 REST API

Build status

CI\CD status on master
phpstan check
unit-tests status
integration-tests status

Integration tests run in GitHub actions with real Bitrix24 portal

BITRIX24-PHP-SDK ✨FEATURES✨

Support both auth modes:

  • work with auth tokens for Bitrix24 applications in marketplace
  • work with incoming webhooks for simple integration projects for current portal

Domain core events:

  • Access Token expired
  • Bitrix24 portal domain url changed

API - level features

  • Auto renew access tokens
  • List queries with «start=-1» support
  • offline queues

Performance improvements 🚀

  • Batch queries implemented with PHP Generators – constant low memory and low CPI usage
    • batch read data from bitrix24
    • batch write data to bitrix24
    • write and read in one batch package
    • composite batch queries to many entities (work in progress)
  • read without count flag

Low-level tools to devs:

  • Rate-limit strategy
  • Retry strategy for safe methods

Development principles

  • Good developer experience
    • auto-completion of methods at the IDE
    • typed method call signatures
    • typed results of method calls
    • helpers for typical operations
  • Good documentation
    • documentation on the operation of a specific method containing a link to the official documentation
    • documentation for working with the SDK
  • Performance first:
    • minimal impact on client code
    • ability to work with large amounts of data with constant memory consumption
    • efficient operation of the API using batch requests
  • Modern technology stack
  • Reliable:
    • test coverage: unit, integration, contract
    • typical examples typical for different modes of operation and they are optimized for memory \ performance

Architecture

Abstraction layers

- http2 protocol via json data structures
- symfony http client
- \Bitrix24\SDK\Core\ApiClient - work with b24 rest-api endpoints
    input: arrays \ strings
    output: Symfony\Contracts\HttpClient\ResponseInterface, operate with strings
    process: network operations 
- \Bitrix24\SDK\Services\* - work with b24 rest-api entities
    input: arrays \ strings
    output: b24 response dto
    process: b24 entities, operate with immutable objects  

Sponsors

Help bitrix24-php-sdk by boosty.to/bitrix24-php-sdk

Requirements

  • php: >=8.2
  • ext-json: *
  • ext-curl: *

Installation

Add "mesilov/bitrix24-php-sdk": "2.x" to composer.json of your application. Or clone repo to your project.

Examples

Work with webhook

declare(strict_types=1);

use Bitrix24\SDK\Services\ServiceBuilderFactory;
use Monolog\Logger;
use Symfony\Component\EventDispatcher\EventDispatcher;

require_once  'vendor/autoload.php';

$webhookUrl = 'INSERT_HERE_YOUR_WEBHOOK_URL';

$log = new Logger('bitrix24-php-sdk');
$b24ServiceFactory = new ServiceBuilderFactory(new EventDispatcher(), $log);

// init bitrix24-php-sdk service
$b24Service = $b24ServiceFactory->initFromWebhook($webhookUrl);

// work with interested scope
var_dump($b24Service->getMainScope()->main()->getCurrentUserProfile()->getUserProfile());
var_dump($b24Service->getCRMScope()->lead()->list([],[],['ID','TITLE'])->getLeads()[0]->TITLE);

Tests

Tests locate in folder tests and we have two test types. In folder tests create file .env.local and fill environment variables from .env.

Unit tests

Fast, in-memory tests without a network I\O For run unit tests you must call in command line

composer phpunit-run-unit-test

Integration tests

Slow tests with full lifecycle with your test Bitrix24 portal via webhook.

❗️Do not run integration tests with production portals

For run integration test you must:

  1. Create new Bitrix24 portal for development tests
  2. Go to left menu, click «Sitemap»
  3. Find menu item «Developer resources»
  4. Click on menu item «Other»
  5. Click on menu item «Inbound webhook»
  6. Assign all permisions with webhook and click «save» button
  7. Create file /tests/.env.local with same settings, see comments in /tests/.env file.
APP_ENV=dev
BITRIX24_WEBHOOK=https:// your portal webhook url
INTEGRATION_TEST_LOG_LEVEL=500
  1. call in command line
composer composer phpunit-run-integration-tests

PHP Static Analysis Tool – phpstan

Call in command line

 composer phpstan-analyse

Submitting bugs and feature requests

Bugs and feature request are tracked on GitHub

License

bitrix24-php-sdk is licensed under the MIT License - see the MIT-LICENSE.txt file for details

Authors

Maksim Mesilov - [email protected]

See also the list of contributors which participated in this project.

Need custom Bitrix24 application?

[email protected] for private consultations or dedicated support

Documentation

Bitrix24 API documentation - Russian

Bitrix24 API documentation - English

Register new Bitrix24 account

bitrix24-php-sdk's People

Contributors

alexeyshockov avatar andreybolonin avatar aracon avatar b24io-sdk avatar bbreukelen avatar camaxtly avatar damianoporta avatar darkridder avatar dipech avatar dnech avatar drumrock avatar gilyazov avatar gitter-badger avatar karlsoncomplete avatar kopecny-shockworks avatar leonvv avatar mborodov avatar mesilov avatar mrdeff avatar nook-ru avatar oaprilepa avatar resident234 avatar slepic avatar umanshield avatar valga avatar waleev avatar xujyx avatar yugene avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

bitrix24-php-sdk's Issues

Move to Guzzle from curl

Guzzle (or may be other wrapper, but this one is the widely used in community) has more readable API than curl.

What do you think about it?

getting " Interface 'Bitrix24\Contracts\iBitrix24' not found" Error

Hello

Hope you are well!

I have installed the Bitrix SDK on my server and i am using below example but i am getting Interface 'Bitrix24\Contracts\iBitrix24' not found error. Can you please suggest why i am getting this issue.

require('../vendor/mesilov/bitrix24-php-sdk/src/bitrix24.php');
// init lib
$obB24App = new \Bitrix24\Bitrix24(false);
$obB24App->setApplicationScope($arParams['B24_APPLICATION_SCOPE']);
$obB24App->setApplicationId($arParams['B24_APPLICATION_ID']);
$obB24App->setApplicationSecret($arParams['B24_APPLICATION_SECRET']);

// set user-specific settings
$obB24App->setDomain($arParams['DOMAIN']);
$obB24App->setMemberId($arParams['MEMBER_ID']);
$obB24App->setAccessToken($arParams['AUTH_ID']);
$obB24App->setRefreshToken($arParams['REFRESH_ID']);

// get information about current user from bitrix24
$obB24User = new \Bitrix24\User\User($obB24App);
$arCurrentB24User = $obB24User->current();

Best Regards

Undefined index: error

Please, check this in mesilov/bitrix24-php-sdk/src/bitrix24.php:871:

if (in_array($requestResult['error'], array('expired_token', 'invalid_token', 'WRONG_TOKEN'), false)) {

I fix this problem like this:

if (isset($requestResult['error']) && in_array($requestResult['error'], array('expired_token', 'invalid_token', 'WRONG_TOKEN'), false)) {

Генерация лида

Добрый день! возможно ли использовать вашу библиотеку для генерации лида? если да можно ли увидеть пример?

Fix errors after change REST API to support self hosted version

REST API go to Bitrix24 self hosted version (such wow)

  1. The app can't tell your client_secret to the data server (portal/box)
  2. The application can't trust the payment status received from the data server (portal/box)

To address these issues, the authorization server OAuth 2.0 is now separated from the server data (i.e., portal) and shall be made on an individual resource https://oauth.bitrix.info/

Obtaining and renewal of authorization
In existing queries should be in all the calls to /oauth/token at the portal to replace the address of the portal on https://oauth.bitrix.info/. As a bonus: you can (and should) be removed from the request scope - tokens will now always be issued for the full set of application permissions. The first step is sending the user to /oauth/authorize portal - remains unchanged, but in one of the next updates will be made the ability to send the user to https://oauth.bitrix.info/oauth/authorize/ there he chose the portal that he needs to log in.

In response, upon receiving the token, the additional fields appear:

array ( 'access_token' => 'ejruymyaqc4y6ctf4gs742bqokh1ca9j', 'expires_in' => 3600, 'scope' => 'im,log,user', 'domain' => 'sigurd.bitrix24.com', 'server_endpoint' => 'https://oauth.bitrix.info/rest/', 'client_endpoint' => 'https://sigurd.bitrix24.com/rest/', 'member_id' => 'a223c6b3710f85df22e9377d6c4f7553', 'refresh_token' => 'n2k23ubc07us4ppnwbwmyifojvuvl77f', 'ts' => 1463567261, )

Client_endpoint parameter contains the full url of the entry point to the REST on the portal, together with the Protocol and the path.
Server_endpoint parameter contains the full url to an entry point to REST on the authorization server. Yes, the authorization server also has its own REST API, but more on that below.

Requests to the REST with authorization for client_id+client_secret
After updating these requests to the portals to work longer. Introduced this feature was recently used poorly, and decided for her not to make a fuss.

Payment application status on the portal/box.
Previously, the app could update it, pulling the REST method /rest/app.info. You can now do the same thing, but using the REST API of the authorization server.

The application can make requests to the methods https://oauth.bitrix.info/rest/ using the authorization token as issued to any portal and authorization for client_id + client_secret. While two methods are available:

  • /rest/app.info

When you call with a valid token issued by any portal/box, the response will contain data about the token (the application code and the expiry time) and installation information (version, status, resolution, address, member_id):

{
"result": {
"client_id": "local.573afbb2db36b4.30304560", 
"expires": "2016-05-18T14:29:42+02:00", 
"install": {
"installed": true, 
"member_id": "a223c6b3710f85df22e9377d6c4f7553", 
"scope": "disk,im", 
"status": "L", 
"uri": "http://b24.sigurd.bx", 
"version": "1"
}, 
 "scope": "app"
}
}

  • /rest/app.stat

When you call with a valid token and client_id + client_secret the application can obtain the filtered list of units with their own versions and statuses.

{
"result": [
{
"CLIENT": "b24.sigurd.bx", 
"DATE_CHANGE": "2016-05-17T13:08:34+02:00", 
"DATE_FINISH": "", 
"DATE_INSTALL": "2016-05-17T13:08:34+02:00", 
"INSTALLED": true, 
"STATUS": "L", 
"VERSION": "1"
}
], 
"total": 1
}

Information on their payment status in the portal, obtained from any of these methods, the application may be trusted, unlike similar data portal.

Fatal error

Fatal error: Class 'Monolog\Logger' not found in D:\xampp\htdocs\bitrix\api\index.php on line 6

I've just made a index.php file , and write the code that you have written and it is showing this error

How to start using the library

Hello,
I have downloaded your library but i do not understand what data should i pass to:

$obB24App->setDomain($arParams['DOMAIN']); // this should be {domain}.bitrix24.com right ?
$obB24App->setMemberId($arParams['MEMBER_ID']);
$obB24App->setAccessToken($arParams['AUTH_ID']);
$obB24App->setRefreshToken($arParams['REFRESH_ID']);

Could you give me more information?
Thank you!

Add bitrix24 events

https://github.com/mesilov/bitrix24-php-sdk/blob/master/src/classes/event/event.php#L21

BX24.callMethod('events', {});

{"result":["ONAPPUNINSTALL","ONAPPINSTALL","ONAPPUPDATE","ONAPPPAYMENT","ONAPPTEST","ONCRMLEADADD","ONCRMLEADUPDATE","ONCRMLEADDELETE","ONCRMDEALADD","ONCRMDEALUPDATE","ONCRMDEALDELETE","ONCRMCOMPANYADD","ONCRMCOMPANYUPDATE","ONCRMCOMPANYDELETE","ONCRMCONTACTADD","ONCRMCONTACTUPDATE","ONCRMCONTACTDELETE","ONCRMQUOTEADD","ONCRMQUOTEUPDATE","ONCRMQUOTEDELETE","ONCRMCURRENCYADD","ONCRMCURRENCYUPDATE","ONCRMCURRENCYDELETE","ONCRMPRODUCTADD","ONCRMPRODUCTUPDATE","ONCRMPRODUCTDELETE","ONCRMACTIVITYADD","ONCRMACTIVITYUPDATE","ONCRMACTIVITYDELETE","ONUSERADD","ONTASKADD","ONTASKUPDATE","ONTASKDELETE","ONTASKCOMMENTADD","ONTASKCOMMENTUPDATE","ONTASKCOMMENTDELETE","ONVOXIMPLANTCALLINIT","ONVOXIMPLANTCALLSTART","ONVOXIMPLANTCALLEND"]}

Disk

Подскажите когда в планах выпуск методов по работе с Диском?

Custom timeout

Hello
i am getting:

Operation timed out after 5001 milliseconds with 0 bytes received (cURL error code: 28)

I think we should implement a timeout setting to change its value if needed.

Increase ITEMS_PER_PAGE_LIMIT

I tried to overwrite the ITEMS_PER_PAGE_LIMIT in Bitrix24Entity class from 50 to 200. Looks like it's no effect. I called getList() method but it still returns 50 results. I just wanted to increase the maximum results.

Webhooks support

Not so long ago, B24 development team announced new functionality - incoming webhooks.

Tell me, pls, do you plan to support them in your project? Perhaps a separate project is planned?

Peer certificate cannot be authenticated with known CA certificates

Fatal error: Uncaught Bitrix24\Exceptions\Bitrix24IoException: in try[0] cURL error (code 60): Peer certificate cannot be authenticated with known CA certificates
in /var/www/u0490668/data/www/chifanba.ru/bitrix24-transaction/vendor/mesilov/bitrix24-php-sdk/src/bitrix24.php:509
Stack trace:
#0 /var/www/u0490668/data/www/chifanba.ru/bitrix24-transaction/vendor/mesilov/bitrix24-php-sdk/src/bitrix24.php(1112): Bitrix24\Bitrix24->executeRequest('https://b24mmit...', Array)
#1 /var/www/u0490668/data/www/chifanba.ru/bitrix24-transaction/vendor/mesilov/bitrix24-php-sdk/src/bitrix24.php(1048): Bitrix24\Bitrix24->_call('user.current', Array)
#2 /var/www/u0490668/data/www/chifanba.ru/bitrix24-transaction/vendor/mesilov/bitrix24-php-sdk/src/classes/user/user.php(28): Bitrix24\Bitrix24->call('user.current', Array)
#3 /var/www/u0490668/data/www/chifanba.ru/bitrix24-transaction/index.php(31): Bitrix24\User\User->current()
#4 {main}
thrown in /var/www/u0490668/data/www/chifanba.ru/bitrix24-transaction/vendor/mesilov/bitrix24-php-sdk/src/bitrix24.php on line 509

Why do I need a loader?

What kind of imprinted this project, this is the only normal solution, but the author managed to write it with his claws and spoil the idea! I have a project without a loader (autoloader) - and your code without autoloader is not possible to use! As you only Team Lead hands are not torn off ....

add auth scenario support

Hello

Hope you are well!

Can you please explain what should I pass in below mentioned code:

$obB24App->setDomain($arParams['DOMAIN']);
$obB24App->setMemberId($arParams['MEMBER_ID']);
$obB24App->setAccessToken($arParams['AUTH_ID']);
$obB24App->setRefreshToken($arParams['REFRESH_ID']);

I have checked my Bitrix account too but I did not find the sufficient information.

Regards,
Tripti

Clock in/out function

is there any way to clock in/out employee using API

i looking to a way to integrate Bitrix with our Face/Finger print attendance system

Add method im.message.add

I could see this method exists by calling methods but there is no documentation about im.message.add.

Basically I want to add a message to private/public group chats. If you have any information on this please share. thanks.

Move from classmap autoloader to PSR

I checked structure of project files, and it seems that moving to PSR autoloader can be done without a lot of pain.

Do you plan this? Or maybe there are special reasons for the classmap autoloader?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.