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

B24Phpsdk Laravel Package

bitrix24/b24phpsdk

Official PHP SDK for the Bitrix24 REST API. Supports v1 (stable, PHP 8.2–8.4) and v3 (new endpoints, PHP 8.4+, breaking changes). Provides typed clients for Bitrix24 REST methods with active CI and production-ready releases.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the SDK (choose version based on PHP compatibility):

    composer require bitrix24/b24phpsdk:"^1.0"  # v1 (PHP 8.2-8.4)
    composer require bitrix24/b24phpsdk:"^3.2"  # v3 (PHP 8.4+, breaking changes)
    
  2. Initialize the service (pick one auth method):

    • Webhook (for single-account integrations):
      use Bitrix24\SDK\Services\ServiceBuilderFactory;
      $b24Service = ServiceBuilderFactory::createServiceBuilderFromWebhook('YOUR_WEBHOOK_URL');
      
    • Local Application (for multi-account OAuth):
      use Bitrix24\SDK\Core\Credentials\ApplicationProfile;
      $appProfile = ApplicationProfile::initFromArray([
          'CLIENT_ID' => 'your_client_id',
          'CLIENT_SECRET' => 'your_secret',
          'SCOPE' => 'crm,im' // Comma-separated permissions
      ]);
      $b24Service = ServiceBuilderFactory::createServiceBuilderFromPlacementRequest(
          \Symfony\Component\HttpFoundation\Request::createFromGlobals(),
          $appProfile
      );
      
  3. First API call (e.g., fetch CRM deals):

    $deals = $b24Service->getMainScope()->crm()->deals()->getDeals();
    

Key Files to Explore

  • /src/Services/ – Service classes (e.g., CrmService, ImService).
  • /examples/ – Ready-to-use workflows (webhook, local app, marketplace).
  • /tests/ – Integration patterns (use .env.local for test credentials).

Implementation Patterns

1. Service Access Patterns

Use builder methods to chain operations:

// v3 example (v1 uses similar but shorter paths)
$deals = $b24Service
    ->getMainScope()
    ->crm()
    ->deals()
    ->getDeals(['SELECT' => ['ID', 'TITLE', 'AMOUNT']]);

Batch Operations (memory-efficient for large datasets):

foreach ($b24Service->getMainScope()->crm()->deals()->getDealsBatch() as $deal) {
    // Process one deal at a time (generator)
    yield $deal->getId();
}

2. Authentication Workflows

  • Token Refresh: The SDK auto-renews tokens on 401 errors (configure via ApiClient).
  • Webhook Validation: Verify requests with:
    $webhookSecret = 'your_secret';
    $isValid = $b24Service->getCore()->validateWebhookRequest(
        $_SERVER['HTTP_X_B24_WEBHOOK_SIGNATURE'],
        file_get_contents('php://input'),
        $webhookSecret
    );
    

3. Common CRUD Patterns

Create:

$deal = $b24Service->getMainScope()->crm()->deals()->addDeal([
    'TITLE' => 'New Deal',
    'AMOUNT' => 1000
]);

Update:

$deal->setTitle('Updated Deal')->update();

Delete:

$deal->delete();

4. Event-Driven Integrations

Listen for webhook events (e.g., CRM deal updates):

$event = $b24Service->getCore()->getWebhookEvent();
switch ($event->getType()) {
    case 'crm.deal.add':
        $deal = $event->getData()['fields'];
        break;
    // Handle other events...
}

5. Laravel Integration

Service Provider:

// app/Providers/Bitrix24ServiceProvider.php
public function register()
{
    $this->app->singleton('bitrix24', function () {
        return ServiceBuilderFactory::createServiceBuilderFromWebhook(
            config('services.bitrix24.webhook_url')
        );
    });
}

Usage in Controllers:

public function syncDeals()
{
    $deals = app('bitrix24')->getMainScope()->crm()->deals()->getDeals();
    // Process deals...
}

6. Error Handling

Wrap API calls in try-catch:

try {
    $result = $b24Service->core()->call('crm.deal.get', ['ID' => 1]);
} catch (\Bitrix24\SDK\Core\Exceptions\ApiException $e) {
    if ($e->getCode() === 401) {
        // Token expired; SDK auto-renews, but handle manually if needed
    }
    Log::error($e->getMessage());
}

Gotchas and Tips

1. Version-Specific Pitfalls

  • v1 vs. v3:
    • v3 uses /rest/api/ endpoints (v1: /rest/).
    • v3 requires PHP 8.4+ (v1: 8.2+).
    • Tip: Use v3 for new projects; v1 for legacy systems.
  • Breaking Changes in v3:
    • Method signatures may differ (e.g., getDeals()getDealsBatch()).
    • Fix: Check the changelog for your upgrade path.

2. Common Debugging Issues

  • 403 Forbidden:
    • Ensure your scope (permissions) includes the required module (e.g., crm, im).
    • Fix: Reconfigure the local app in Bitrix24 with correct scopes.
  • Token Expiry:
    • The SDK auto-renews tokens, but webhook requests require manual handling.
    • Tip: Store the latest token in a cache (e.g., Redis) for webhook responses.
  • Large Datasets:
    • Avoid getDeals() without limits; use getDealsBatch() or SELECT filters.
    • Example:
      $deals = $b24Service->getMainScope()->crm()->deals()->getDeals([
          'SELECT' => ['ID', 'TITLE'],
          'FILTER' => ['AMOUNT' => ['>=', 1000]],
          'START' => 0,
          'TOP' => 100
      ]);
      

3. Performance Tips

  • Batch Writes:
    $b24Service->getMainScope()->crm()->deals()->addDealsBatch([
        ['TITLE' => 'Deal 1', 'AMOUNT' => 100],
        ['TITLE' => 'Deal 2', 'AMOUNT' => 200]
    ]);
    
  • Disable Counting: Add COUNT => false to reduce payload size for list queries.

4. Extension Points

  • Custom Services: Extend \Bitrix24\SDK\Services\AbstractService to wrap undocumented endpoints:
    class CustomService extends AbstractService {
        public function customMethod(array $params): array {
            return $this->getApiClient()->call('custom.endpoint', $params);
        }
    }
    
  • Middleware: Inject HTTP middleware (e.g., logging) via ApiClient:
    $client = new ApiClient(
        $webhookUrl,
        new \Symfony\Component\HttpClient\CurlHttpClient(),
        new \Bitrix24\SDK\Core\Middleware\LoggingMiddleware()
    );
    

5. Testing Quirks

  • Integration Tests:
    • Use .env.local to override test credentials (never commit this file).
    • Tip: Run tests with --filter to target specific scopes:
      make test-integration-scope-crm
      
  • Mocking: Use ApiClientMock for unit tests:
    $mockClient = new ApiClientMock();
    $mockClient->setResponse('crm.deal.get', ['result' => ['ID' => 1]]);
    $service = new CrmService($mockClient);
    

6. Configuration Quirks

  • Webhook Secrets:
    • Store secrets in environment variables (e.g., BITRIX24_WEBHOOK_SECRET).
    • Never hardcode in source files.
  • Local App URLs:
    • Use ngrok for local development (as shown in examples).
    • Tip: Add a /install.php endpoint to handle OAuth callbacks.

7. IDE Tips

  • Autocompletion: The SDK uses PHP 8.2+ typed properties; enable PHP 8.2+ support in your IDE.
  • Navigation: Use Ctrl+Click on service methods to jump to the [Bitrix24 API docs](https://apidocs.bitrix24.com/
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.
graham-campbell/flysystem
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi