Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Darvin Bitrix24 Bundle Laravel Package

darvinstudio/darvin-bitrix24-bundle

View on GitHub
Deep Wiki
Context7
## 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],
];
  1. 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'
    
  2. 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);
    }
    

Implementation Patterns

Core Workflows

  1. 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);
    
  2. 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
    
  3. 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);
    }
    
  4. Dependency Injection: Prefer constructor injection for services:

    public function __construct(
        private ClientInterface $client,
        private LeadFactoryInterface $leadFactory
    ) {}
    

Integration Tips

  • 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);
    

Gotchas and Tips

Pitfalls

  1. Authentication:

    • Ensure client_id and client_secret are correctly set in the config.
    • Redirect URI must match the one registered in Bitrix24 developer settings.
    • Gotcha: If using OAuth, the first request will redirect to Bitrix24 for authorization. Handle this in your frontend or use the implicit flow carefully.
  2. 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);
    
  3. Data Mapping:

    • Bitrix24 uses specific field names (e.g., PHONE[VALUE]). Incorrect mapping will fail silently or return errors.
    • Tip: Use the LeadFactory to ensure consistent field formatting:
      $lead = $leadFactory->createLead('Name', [
          'PHONE' => ['VALUE' => '+12345'], // Correct format
          'WRONG_FIELD' => 'value',         // Will be ignored
      ]);
      
  4. Deprecation:

    • The bundle was last updated in 2021. Check for breaking changes if Bitrix24 updates their API.
    • Tip: Subscribe to Bitrix24’s API changelog and test updates in a staging environment.
  5. Webhook Security:

    • Always validate webhook signatures if using Bitrix24’s webhook system. The bundle does not include built-in validation.
    • Tip: Add a middleware to verify signatures:
      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');
          }
      }
      

Debugging

  1. Enable Debug Mode: Set DARVIN_BITRIX24_DEBUG: true in .env to log raw API responses:

    DARVIN_BITRIX24_DEBUG=1
    
  2. 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"]
    
  3. 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.

Extension Points

  1. 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']
    
  2. 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);
        }
    }
    
  3. 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());
    }
    
  4. API Versioning: The bundle defaults to Bitrix24’s latest stable API. To use a specific version, override the ClientInterface:

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky