darvinstudio/darvin-bitrix24-bundle
## Getting Started
### Minimal Setup
1. **Installation**:
```bash
composer require darvinstudio/darvin-bitrix24-bundle
Enable the bundle in config/bundles.php:
return [
// ...
Darvin\Bitrix24Bundle\DarvinBitrix24Bundle::class => ['all' => true],
];
Configuration:
Add Bitrix24 credentials to config/packages/darvin_bitrix24.yaml:
darvin_bitrix24:
client_id: '%env(BITRIX24_CLIENT_ID)%'
client_secret: '%env(BITRIX24_CLIENT_SECRET)%'
domain: 'yourdomain.bitrix24.com'
redirect_uri: 'https://your-app.com/bitrix24/callback'
First Use Case: Create a lead in Bitrix24 via a Symfony controller:
use Darvin\Bitrix24Bundle\Lead\LeadFactoryInterface;
use Darvin\Bitrix24Bundle\Client\ClientInterface;
public function createLead(ClientInterface $client, LeadFactoryInterface $leadFactory)
{
$lead = $leadFactory->createLead('Test Lead', [
'NAME' => 'John Doe',
'PHONE' => ['VALUE' => '+123456789'],
]);
$result = $client->sendLead($lead);
return new JsonResponse($result);
}
CRM Operations: Use factories to create commands for leads, contacts, deals, etc.:
// Add a lead with products
$lead = $leadFactory->createLead('Lead Name');
$productRow = new ProductRow(1, 100, 1); // ID, QUANTITY, PRICE
$request = $this->leadCommandFactory->createAddCommand($lead);
$request->addProductRow($productRow);
$this->client->send($request);
Batch Processing: Group multiple commands into a single request for efficiency:
$request = new Request();
$request->addCommand($this->leadCommandFactory->createAddCommand($lead1));
$request->addCommand($this->leadCommandFactory->createAddCommand($lead2));
$this->client->send($request); // Executes both in one API call
Event-Driven Integration:
Listen to Symfony events (e.g., KernelEvents::TERMINATE) to sync data post-action:
public function onKernelTerminate(RequestEvent $event)
{
$lead = $this->leadFactory->createFromRequest($event->getRequest());
$this->client->sendLead($lead);
}
Dependency Injection: Prefer constructor injection for services:
public function __construct(
private ClientInterface $client,
private LeadFactoryInterface $leadFactory
) {}
Webhook Handling:
Use Symfony’s HttpFoundation to validate and process Bitrix24 webhooks:
public function handleWebhook(Request $request, ClientInterface $client)
{
$data = json_decode($request->getContent(), true);
$client->validateWebhook($data); // Custom validation logic
// Process data (e.g., update local DB)
}
Error Handling: Wrap client calls in try-catch blocks to handle Bitrix24 API errors:
try {
$result = $this->client->send($request);
} catch (Bitrix24ApiException $e) {
$this->logger->error('Bitrix24 API Error: ' . $e->getMessage());
throw new \RuntimeException('Failed to sync with Bitrix24', 0, $e);
}
Testing:
Mock the ClientInterface in unit tests:
$mockClient = $this->createMock(ClientInterface::class);
$mockClient->method('send')
->willReturn(['success' => true]);
$this->controller->setClient($mockClient);
Authentication:
client_id and client_secret are correctly set in the config.Rate Limiting: Bitrix24 API has rate limits (e.g., 100 requests/minute). Batch commands to avoid hitting limits:
// Bad: 50 individual requests
foreach ($leads as $lead) {
$this->client->sendLead($lead);
}
// Good: 1 batched request
$request = new Request();
foreach ($leads as $lead) {
$request->addCommand($this->leadCommandFactory->createAddCommand($lead));
}
$this->client->send($request);
Data Mapping:
PHONE[VALUE]). Incorrect mapping will fail silently or return errors.LeadFactory to ensure consistent field formatting:
$lead = $leadFactory->createLead('Name', [
'PHONE' => ['VALUE' => '+12345'], // Correct format
'WRONG_FIELD' => 'value', // Will be ignored
]);
Deprecation:
Webhook Security:
public function validateWebhook(Request $request)
{
$signature = $request->headers->get('X-Bitrix-Signature');
if (!hash_equals($signature, $this->generateExpectedSignature($request->getContent()))) {
throw new \RuntimeException('Invalid webhook signature');
}
}
Enable Debug Mode:
Set DARVIN_BITRIX24_DEBUG: true in .env to log raw API responses:
DARVIN_BITRIX24_DEBUG=1
Logging: Configure Monolog to log Bitrix24 errors:
# config/packages/monolog.yaml
handlers:
bitrix24:
type: stream
path: "%kernel.logs_dir%/bitrix24.log"
level: error
channels: ["bitrix24"]
Common Errors:
401 Unauthorized: Check client_id/client_secret or OAuth token.400 Bad Request: Validate field names and data types (e.g., PHONE[VALUE] must be a string).500 Internal Server Error: Bitrix24-side issue; check their status page or contact support.Custom Commands: Extend the bundle by creating custom command factories:
// src/Command/CustomCommandFactory.php
class CustomCommandFactory implements CommandFactoryInterface
{
public function createCustomCommand(array $data): CommandInterface
{
return new CustomCommand($data);
}
}
Register the service in services.yaml:
services:
App\Command\CustomCommandFactory:
tags: ['darvin_bitrix24.command_factory']
Override Models:
Extend Lead, Contact, or other models to add custom fields:
class CustomLead extends Lead
{
public function __construct(string $title, array $fields = [])
{
$fields['CUSTOM_FIELD'] = 'custom_value'; // Add custom field
parent::__construct($title, $fields);
}
}
Event Listeners: Listen to Bitrix24 events (e.g., lead creation) via Symfony’s event dispatcher:
public static function getSubscribedEvents()
{
return [
'bitrix24.lead.created' => 'onLeadCreated',
];
}
public function onLeadCreated(LeadEvent $event)
{
$this->logger->info('New lead created: ' . $event->getLead()->getTitle());
}
API Versioning:
The bundle defaults to Bitrix24’s latest stable API. To use a specific version, override the ClientInterface:
How can I help you explore Laravel packages today?