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

Php Odoo Api Client Laravel Package

ang3/php-odoo-api-client

View on GitHub
Deep Wiki
Context7

Getting Started

First Steps

  1. Installation Add the package via Composer:

    composer require ang3/php-odoo-api-client:^7.0
    

    Register the service provider in config/app.php (if not auto-discovered):

    'providers' => [
        Ang3\Odoo\OdooServiceProvider::class,
    ],
    
  2. Basic Configuration Publish the config file:

    php artisan vendor:publish --provider="Ang3\Odoo\OdooServiceProvider"
    

    Update .env with Odoo API credentials:

    ODOO_URL=https://your-odoo-instance.com
    ODOO_DB=your_database
    ODOO_USERNAME=your_username
    ODOO_PASSWORD=your_password
    
  3. First API Call Inject the client into a Laravel service or controller:

    use Ang3\Odoo\OdooClient;
    use Psr\Log\LoggerInterface; // New PSR-14 Logger support
    
    public function __construct(OdooClient $client, LoggerInterface $logger) {
        $this->client = $client;
        $this->logger = $logger;
    }
    
    public function fetchContacts() {
        $contacts = $this->client->get('/res.partner');
        $this->logger->info('Fetched contacts', ['count' => count($contacts)]);
        return response()->json($contacts);
    }
    

Implementation Patterns

Common Workflows

  1. CRUD Operations

    • Create:
      $newContact = $this->client->post('/res.partner', [
          'name' => 'John Doe',
          'email' => 'john@example.com',
      ]);
      
    • Read:
      $contact = $this->client->get('/res.partner/1');
      
    • Update:
      $this->client->put('/res.partner/1', ['name' => 'Updated Name']);
      
    • Delete:
      $this->client->delete('/res.partner/1');
      
  2. Searching Records Use domain filters:

    $contacts = $this->client->search('/res.partner', [
        'filters' => [['email', '=', 'john@example.com']],
    ]);
    
  3. Batch Operations Use execute_kw for complex actions (e.g., bulk updates):

    $this->client->executeKw('res.partner', 'write', [
        [1, 2, 3], // IDs
        [['name' => 'Updated']] // Values
    ]);
    
  4. Logging with PSR-14 Leverage the new PSR-14 logger integration for structured logging:

    // Configure logger in OdooServiceProvider
    $this->app->bind(LoggerInterface::class, function ($app) {
        return $app->make(\Illuminate\Log\Logger::class);
    });
    
    // Use in your code
    $this->logger->debug('Odoo API request', [
        'method' => 'GET',
        'endpoint' => '/res.partner',
        'params' => $this->client->getLastRequest()->getData()
    ]);
    
  5. Authentication & Rate Limiting

    • Handle 401 errors by re-authenticating:
      $this->client->authenticate(); // Force re-auth
      
    • Implement retry logic for rate limits (429).
  6. Event-Driven Integrations Use Laravel queues to process Odoo webhook payloads:

    // In a controller
    public function handleWebhook(Request $request) {
        dispatch(new ProcessOdooWebhook($request->json()));
    }
    

Gotchas and Tips

Pitfalls & Debugging

  1. Authentication Issues

    • Symptom: 401 Unauthorized.
    • Fix: Verify .env credentials and call $client->authenticate() explicitly.
    • Tip: Use OdooClient::setDebug(true) to log raw requests/responses.
  2. Rate Limiting

    • Symptom: 429 Too Many Requests.
    • Fix: Implement exponential backoff in your retry logic:
      $attempts = 0;
      while ($attempts < 3) {
          try {
              $response = $this->client->get('/endpoint');
              break;
          } catch (\Ang3\Odoo\Exception\RateLimitException $e) {
              $this->logger->warning('Rate limited, retrying...', ['attempt' => $attempts]);
              sleep(2 ** $attempts); // Exponential delay
              $attempts++;
          }
      }
      
  3. XML-RPC vs. JSON-RPC

    • The package defaults to JSON-RPC 2.0 (modern Odoo).
    • If using XML-RPC (legacy), manually construct the XML payload.
  4. Field Access Restrictions

    • Symptom: Missing fields in responses.
    • Fix: Ensure your Odoo user has the correct group permissions (e.g., Access Rights in Odoo settings).
  5. Timeouts

    • Default timeout is 30 seconds. Adjust in config:
      'timeout' => 60, // seconds
      
  6. PSR-14 Logger Compatibility

    • Symptom: Logger not working as expected.
    • Fix: Ensure your Laravel application is configured to use PSR-14 compatible logger (default since Laravel 8+).
    • Tip: If using custom logger, bind it explicitly in the service provider:
      $this->app->bind(LoggerInterface::class, function ($app) {
          return new MonologLogger($app->make(\Illuminate\Log\Logger::class));
      });
      

Extension Points

  1. Custom Middleware Add request/response filters:

    $client->getMiddleware()->push(function ($request) {
        $request->headers->set('X-Custom-Header', 'value');
    });
    
  2. Model Bindings Create Laravel models that map to Odoo records:

    class OdooContact extends Model {
        public function fetch($id) {
            return $this->client->get("/res.partner/{$id}");
        }
    }
    
  3. Webhook Validation Validate Odoo webhook signatures (if enabled):

    use Ang3\Odoo\WebhookValidator;
    
    $validator = new WebhookValidator($request->header('X-Odoo-Signature'));
    if (!$validator->isValid($request->getContent())) {
        $this->logger->warning('Invalid webhook signature');
        abort(403);
    }
    
  4. Caching Responses Cache frequent API calls (e.g., product lists):

    $products = Cache::remember('odoo_products', now()->addHours(1), function () {
        return $this->client->get('/product.product');
    });
    
  5. Structured Logging Use the new PSR-14 logger for better observability:

    $this->logger->info('Odoo API operation', [
        'action' => 'create',
        'model' => 'res.partner',
        'data' => ['name' => 'John Doe']
    ]);
    

Config Quirks

  • Base URL: Ensure ODOO_URL includes the database name (e.g., https://odoo.com/db_name).
  • Environment Switching: Use Laravel’s config('odoo.url') for dynamic environments.
  • Logging: Enable debug mode in config/odoo.php:
    'debug' => env('ODOO_DEBUG', false),
    'logger' => [
        'enabled' => true,
        'channel' => env('ODOO_LOG_CHANNEL', 'stack'),
    ],
    
  • PSR-14 Logger Configuration: Ensure your config/logging.php is set up for PSR-14 compatibility:
    'default' => env('LOG_CHANNEL', 'stack'),
    'channels' => [
        'stack' => [
            'driver' => 'stack',
            'channels' => ['single', 'daily'],
        ],
        // ...
    ],
    
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
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
spatie/mailcoach-vapor