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

Bitrix24 PHP SDK for working with the Bitrix24 REST API from Laravel or plain PHP. Provides typed clients, authentication helpers, API method wrappers, pagination, and webhook/OAuth support to simplify integrating CRM, tasks, chats, and other Bitrix24 modules.

Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package via Composer:
    composer require bitrix24/b24phpsdk
    
  2. Configure the SDK in config/services.php (or a dedicated b24.php config file):
    'b24' => [
        'client_id' => env('B24_CLIENT_ID'),
        'client_secret' => env('B24_CLIENT_SECRET'),
        'redirect_uri' => env('B24_REDIRECT_URI'),
        'domain' => env('B24_DOMAIN', 'yourdomain.bitrix24.com'),
        'token' => env('B24_ACCESS_TOKEN'),
    ],
    
  3. Publish the config (if needed):
    php artisan vendor:publish --provider="Bitrix24\B24PhpSdk\B24PhpSdkServiceProvider"
    

First Use Case: Fetching a Contact

use Bitrix24\B24PhpSdk\B24Client;

$client = new B24Client(config('b24'));
$contact = $client->crm()->contacts()->get(123); // Fetch contact with ID 123

Key Entry Points

  • Client Initialization: new B24Client(config('b24'))
  • CRM Operations: $client->crm()->[entity]()->[method]()
  • Auth Flow: $client->auth()->getAuthUrl() (for OAuth)

Implementation Patterns

1. Service Layer Integration

Wrap the SDK in a Laravel service class to abstract Bitrix24 logic:

namespace App\Services;

use Bitrix24\B24PhpSdk\B24Client;

class Bitrix24Service
{
    protected $client;

    public function __construct()
    {
        $this->client = new B24Client(config('b24'));
    }

    public function createLead(array $data)
    {
        return $this->client->crm()->leads()->add($data);
    }
}

Usage in Controller:

public function store(Request $request)
{
    $lead = app(Bitrix24Service::class)->createLead($request->all());
    return response()->json($lead);
}

2. OAuth Flow

Handle authorization with a redirect:

// Generate auth URL
$authUrl = app(B24Client::class)->auth()->getAuthUrl();

// After redirect, exchange code for token
$token = app(Bitrix24Service::class)->client->auth()->getAccessToken($code);

3. Bulk Operations

Use collections for batch processing:

$contacts = $client->crm()->contacts()->getList(['SELECT' => ['ID', 'NAME']]);
foreach ($contacts as $contact) {
    // Process each contact
}

4. Webhooks

Extend the SDK to handle Bitrix24 webhooks:

use Bitrix24\B24PhpSdk\Events\WebhookEvent;

class Bitrix24WebhookHandler
{
    public function handle(WebhookEvent $event)
    {
        if ($event->type === 'lead.add') {
            // Handle new lead
        }
    }
}

5. Custom Endpoints

Extend the SDK for unsupported endpoints:

use Bitrix24\B24PhpSdk\B24Client;

$client = new B24Client(config('b24'));
$response = $client->request('GET', '/rest/1/yourcustomendpoint');

Gotchas and Tips

Common Pitfalls

  1. Token Expiry:

    • Always handle Bitrix24\B24PhpSdk\Exceptions\TokenExpiredException.
    • Refresh tokens automatically in a middleware:
      public function handle($request, Closure $next)
      {
          try {
              return $next($request);
          } catch (TokenExpiredException $e) {
              $token = $this->refreshToken();
              config(['b24.token' => $token]);
              return $next($request);
          }
      }
      
  2. Rate Limiting:

    • Bitrix24 enforces rate limits (e.g., 100 requests/minute). Cache responses:
      $cacheKey = 'b24_contacts_' . $id;
      return Cache::remember($cacheKey, now()->addMinutes(5), function () use ($client, $id) {
          return $client->crm()->contacts()->get($id);
      });
      
  3. Field Mappings:

    • Bitrix24 uses UF_* for custom fields. Ensure your SDK version supports them:
      $lead = $client->crm()->leads()->add([
          'TITLE' => 'New Lead',
          'UF_CRM_123456789' => 'Custom Value', // Custom field
      ]);
      

Debugging Tips

  1. Enable Debug Mode:

    $client = new B24Client(config('b24'), [
        'debug' => true,
    ]);
    
    • Logs requests/responses to storage/logs/b24.log.
  2. Validate Responses:

    • Use ->validate() on responses to check for errors:
      $response = $client->crm()->contacts()->get(123)->validate();
      
  3. Test with Sandbox:

    • Use https://sandbox.bitrix24.com for testing before going live.

Extension Points

  1. Custom Entities:

    • Extend Bitrix24\B24PhpSdk\Entities\Entity for new CRM objects:
      class CustomEntity extends Entity
      {
          protected $endpoint = 'customentity';
      }
      
  2. Middleware:

    • Add request/response middleware:
      $client->addMiddleware(function ($request) {
          $request->headers->set('X-Custom-Header', 'value');
      });
      
  3. Event Dispatching:

    • Bind SDK events to Laravel events:
      event(new WebhookEvent($data));
      

Performance Tips

  • Batch Requests: Use ->batch() for multiple operations:
    $client->crm()->contacts()->batch([
        ['method' => 'add', 'params' => [...]],
        ['method' => 'update', 'params' => [...]],
    ]);
    
  • Lazy Loading: Use ->getList() with SELECT to fetch only needed fields.

Configuration Quirks

  • Domain Format: Ensure B24_DOMAIN is in subdomain.bitrix24.com format (not https://...).
  • SSL Verification: Disable only for testing:
    $client = new B24Client(config('b24'), [
        'verify_ssl' => false,
    ]);
    
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware