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

Bitrix24 Laravel Sdk Laravel Package

rodrigofr/bitrix24-laravel-sdk

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to First Use

  1. Install the Package

    composer require rodrigofr/bitrix24-laravel-sdk
    
  2. Publish Config & Views

    php artisan vendor:publish --provider="Rodrigofr\Bitrix24LaravelSdk\Bitrix24ServiceProvider" --tag="config"
    php artisan vendor:publish --provider="Rodrigofr\Bitrix24LaravelSdk\Bitrix24ServiceProvider" --tag="views"
    
  3. Configure .env Add your Bitrix24 credentials:

    BITRIX24_CLIENT_ID=your_client_id
    BITRIX24_CLIENT_SECRET=your_client_secret
    BITRIX24_REDIRECT_URI=http://your-app.dev/auth/bitrix24/callback
    
  4. Run Migrations

    php artisan migrate
    

    (The package includes migrations for storing OAuth tokens.)

  5. First Use Case: Installing an App

    • Visit /bitrix24/install (route defined in the package).
    • Follow the OAuth flow to authorize your Laravel app with Bitrix24.
    • After installation, the package auto-stores the access token.
  6. Making Your First API Call

    use Rodrigofr\Bitrix24LaravelSdk\Facades\Bitrix24;
    
    $users = Bitrix24::crm()->contact()->get();
    

Implementation Patterns

Core Workflows

1. OAuth Flow & Installation

  • Use the built-in InstallController (published with views) to handle the OAuth flow:
    Route::get('/bitrix24/install', [\Rodrigofr\Bitrix24LaravelSdk\Http\Controllers\InstallController::class, 'install']);
    Route::get('/bitrix24/callback', [\Rodrigofr\Bitrix24LaravelSdk\Http\Controllers\InstallController::class, 'callback']);
    
  • Customize the install.blade.php view (published in resources/views/vendor/bitrix24-laravel-sdk/install.blade.php) to match your app’s branding.

2. API Access via ServiceBuilder

The package wraps the Bitrix24 PHP SDK and provides a fluent interface:

// CRM Example: Fetch contacts
$contacts = Bitrix24::crm()->contact()->get(['SELECT' => ['ID', 'NAME']]);

// Tasks Example: Create a task
$task = Bitrix24::crm()->task()->add([
    'TITLE' => 'Test Task',
    'DESCRIPTION' => 'Created via Laravel SDK',
]);

3. Token Management

  • Tokens are stored in the bitrix24_oauth_tokens table.
  • Manually refresh tokens if needed:
    $token = Bitrix24::getToken(); // Get current token
    $token->refresh(); // Refresh token
    

4. Middleware for Authenticated Requests

Protect routes requiring Bitrix24 access:

Route::middleware(['bitrix24.auth'])->group(function () {
    Route::get('/dashboard', [DashboardController::class, 'index']);
});

The bitrix24.auth middleware checks for a valid token.

5. Customizing API Responses

Extend the SDK’s response handling by overriding the Bitrix24ServiceProvider:

// In AppServiceProvider@boot()
Bitrix24::extend(function ($builder) {
    $builder->afterResponse(function ($response) {
        // Transform response data (e.g., convert timestamps)
        return collect($response)->map(function ($item) {
            $item['CREATED_DATE'] = Carbon::parse($item['CREATED_DATE']);
            return $item;
        });
    });
});

Integration Tips

  • Webhooks: Use Bitrix24’s webhook system to push events to your Laravel app. Store the webhook secret in config/bitrix24.php and validate incoming requests:

    Route::post('/bitrix24/webhook', function (Request $request) {
        $payload = $request->getContent();
        $signature = $request->header('X-Bitrix24-Signature');
    
        if (Bitrix24::validateWebhook($payload, $signature)) {
            // Process webhook
        }
    });
    
  • Batch Operations: Leverage Bitrix24’s batch API for bulk operations:

    $batch = Bitrix24::batch();
    $batch->add(Bitrix24::crm()->contact()->method('add'), ['NAME' => 'John Doe']);
    $batch->add(Bitrix24::crm()->contact()->method('add'), ['NAME' => 'Jane Doe']);
    $results = $batch->execute();
    
  • Error Handling: Catch Bitrix24-specific exceptions:

    try {
        $result = Bitrix24::crm()->contact()->get();
    } catch (\Rodrigofr\Bitrix24LaravelSdk\Exceptions\Bitrix24Exception $e) {
        Log::error('Bitrix24 Error: ' . $e->getMessage());
        return response()->json(['error' => 'Failed to fetch contacts'], 500);
    }
    

Gotchas and Tips

Pitfalls

  1. Token Expiry Handling

    • The package auto-refreshes expired tokens, but ensure your BITRIX24_REDIRECT_URI is correct in .env to avoid silent failures during OAuth.
    • If tokens expire frequently, log the expires_at timestamp to debug:
      $token = Bitrix24::getToken();
      Log::debug('Token expires at:', [$token->expires_at]);
      
  2. CORS Issues

    • If using Bitrix24’s web interface, ensure your Laravel app’s CORS settings (via fruitcake/laravel-cors) allow requests from your Bitrix24 domain:
      'paths' => ['api/*', 'bitrix24/*'],
      'allowed_methods' => ['*'],
      'allowed_origins' => ['https://your-bitrix24-domain.com'],
      
  3. Rate Limiting

    • Bitrix24 has API rate limits. Implement retries with exponential backoff:
      use Rodrigofr\Bitrix24LaravelSdk\Exceptions\Bitrix24RateLimitException;
      
      try {
          $result = Bitrix24::crm()->contact()->get();
      } catch (Bitrix24RateLimitException $e) {
          sleep($e->getRetryAfter());
          retry();
      }
      
  4. Timezone Mismatches

    • Bitrix24 uses UTC for timestamps. Convert to your local timezone in responses:
      Bitrix24::extend(function ($builder) {
          $builder->afterResponse(function ($response) {
              return array_map(function ($item) {
                  $item['DATE_CREATE'] = Carbon::parse($item['DATE_CREATE'])->tz('Europe/Moscow');
                  return $item;
              }, $response);
          });
      });
      
  5. Published Assets Overwrites

    • Avoid manually editing published views/config. Instead, extend them:
      // In AppServiceProvider@boot()
      $this->loadViewsFrom(__DIR__.'/views/vendor/bitrix24-laravel-sdk', 'bitrix24-laravel-sdk');
      

Debugging Tips

  • Enable SDK Debugging Add to config/bitrix24.php:

    'debug' => env('BITRIX24_DEBUG', false),
    

    This logs raw API requests/responses to storage/logs/bitrix24.log.

  • Inspect Raw SDK Calls The underlying bitrix24/b24phpsdk is available via:

    $rawSdk = Bitrix24::getSdk();
    $rawSdk->crm()->contact()->get(); // Use the raw SDK if needed
    
  • Common HTTP Errors

    • 401 Unauthorized: Token is invalid/expired. Check bitrix24_oauth_tokens table.
    • 403 Forbidden: Insufficient permissions. Verify OAuth scopes during installation.
    • 500 Internal Server Error: Bitrix24 API issue. Check their status page.

Extension Points

  1. Custom API Methods Extend the SDK to add missing methods:

    Bitrix24::extend(function ($builder) {
        $builder->crm()->contact()->method('customMethod', function ($params) {
            return $this->call('crm.contact.custommethod', $params);
        });
    });
    
  2. Model Bindings Create Eloquent models for Bitrix2

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.
make-dev/orca
dmstr/symfony-system-resources-bundle
dmstr/symfony-job-queue-bundle
dmstr/openapi-json-schema-bundle
dmstr/keycloak-security-bundle
dmstr/doctrine-audit-log-bundle
dmstr/api-platform-utils-bundle
dmstr/api-configuration-bundle
chrisdev/ux-components
baks-dev/finances
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle