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

Dynamics Webapi Toolkit Laravel Package

alexacrm/dynamics-webapi-toolkit

Laravel/PHP toolkit for working with Microsoft Dynamics 365 Web API. Simplifies authentication, building requests, and performing CRUD operations with entities, queries, and batch actions. Handy wrapper to integrate CRM data into your app with less boilerplate.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require alexacrm/dynamics-webapi-toolkit
    

    Ensure your project meets PHP 7.4+ requirements.

  2. Basic Configuration Create a config file (e.g., config/dynamics.php) and define your Dynamics 365 Web API endpoint, client ID, and client secret:

    return [
        'auth' => [
            'client_id' => env('DYNAMICS_CLIENT_ID'),
            'client_secret' => env('DYNAMICS_CLIENT_SECRET'),
        ],
        'endpoint' => env('DYNAMICS_ENDPOINT', 'https://yourorg.crm.dynamics.com'),
        'version' => env('DYNAMICS_API_VERSION', '9.2'),
    ];
    
  3. First Use Case: Authentication Initialize the client in a service or controller:

    use Alexacrm\DynamicsWebapiToolkit\Client;
    
    $client = new Client(config('dynamics'));
    $accessToken = $client->authenticate();
    
  4. First API Call Fetch an account record:

    $account = $client->get('accounts(12345678-1234-1234-1234-123456789012)');
    

Implementation Patterns

Common Workflows

  1. CRUD Operations

    • Create:
      $newAccount = $client->create('accounts', [
          'name' => 'Acme Corp',
          'revenue' => 1000000
      ]);
      
    • Update:
      $client->update('accounts(12345678-...)', ['name' => 'Updated Acme Corp']);
      
    • Delete:
      $client->delete('accounts(12345678-...)');
      
  2. Querying Data Use OData queries for filtering, sorting, and pagination:

    $accounts = $client->get('accounts?$select=name,revenue&$filter=revenue gt 1000000');
    
  3. Associations Fetch related records (e.g., contacts for an account):

    $accountWithContacts = $client->get('accounts(12345678-...)?$expand=contacts($select=fullname)');
    
  4. Bulk Operations Use $batch for multiple operations in a single request:

    $batch = $client->batch();
    $batch->create('accounts', ['name' => 'Batch Account 1']);
    $batch->create('accounts', ['name' => 'Batch Account 2']);
    $results = $batch->execute();
    
  5. Webhooks Subscribe to entity changes (e.g., account updates):

    $client->subscribe('accounts', 'https://your-app.com/webhook-endpoint', ['created', 'updated']);
    

Integration Tips

  1. Laravel Service Provider Bind the client to the container for dependency injection:

    $this->app->singleton(Client::class, function ($app) {
        return new Client($app['config']['dynamics']);
    });
    
  2. Middleware for Authentication Create middleware to handle token refresh:

    public function handle($request, Closure $next) {
        $client = app(Client::class);
        if (!$client->isAuthenticated()) {
            $client->authenticate();
        }
        return $next($request);
    }
    
  3. Eloquent Models Extend Eloquent models to interact with Dynamics 365:

    class Account extends Model {
        public static function fetch($id) {
            $client = app(Client::class);
            return $client->get("accounts({$id})");
        }
    }
    
  4. Event Handling Listen for Dynamics 365 webhook events:

    Route::post('/webhook', function (Request $request) {
        $payload = $request->json()->all();
        // Process payload (e.g., update local cache)
    });
    

Gotchas and Tips

Pitfalls

  1. Token Expiry

    • The OAuth token expires after 1 hour. Always handle 401 Unauthorized responses by refreshing the token:
      try {
          $response = $client->get('accounts');
      } catch (\Alexacrm\DynamicsWebapiToolkit\Exception\UnauthorizedException $e) {
          $client->authenticate(); // Refresh token
          $response = $client->get('accounts');
      }
      
  2. Entity Names

    • Dynamics 365 uses plural entity names (e.g., accounts, contacts), but the API may require singular names for some operations. Verify with the Dynamics 365 API documentation.
  3. Large Data Sets

    • Avoid fetching large datasets without pagination. Use $top and $skip:
      $accounts = $client->get('accounts?$top=100&$skip=0');
      
  4. Concurrency Conflicts

    • Use If-Match headers for optimistic concurrency control:
      $client->update('accounts(12345678-...)', ['name' => 'Updated'], [
          'headers' => ['If-Match' => '*']
      ]);
      
  5. Case Sensitivity

    • Entity and attribute names are case-sensitive in queries. Use the exact names from the Dynamics 365 schema.

Debugging

  1. Enable Verbose Logging Configure the client to log requests/responses:

    $client = new Client(config('dynamics'), [
        'logger' => new \Monolog\Logger('dynamics', [
            new \Monolog\Handler\StreamHandler(storage_path('logs/dynamics.log'))
        ])
    ]);
    
  2. Common HTTP Errors

    • 400 Bad Request: Validate your payload and query syntax.
    • 403 Forbidden: Check your permissions or OAuth scopes.
    • 404 Not Found: Verify the entity name or ID.
    • 500 Internal Server Error: Check the Dynamics 365 admin center for errors.
  3. Schema Exploration Use the $metadata endpoint to explore available entities and attributes:

    $metadata = $client->get('$metadata');
    

Extension Points

  1. Custom Headers Add custom headers to requests:

    $client->setDefaultHeaders(['X-Custom-Header' => 'value']);
    
  2. Request Interceptors Extend the client to modify requests before they’re sent:

    $client->setRequestInterceptor(function ($request) {
        $request->headers->set('X-Request-ID', uniqid());
    });
    
  3. Response Transformers Transform responses before they’re returned:

    $client->setResponseTransformer(function ($response) {
        return json_decode($response->getBody(), true);
    });
    
  4. Custom Entities Dynamically register custom entities or attributes:

    $client->registerEntity('custom_entities', [
        'name' => 'Custom Entity',
        'attributes' => ['custom_field' => 'String']
    ]);
    
  5. Webhook Validation Validate incoming webhook payloads using the validateWebhook method:

    $isValid = $client->validateWebhook($payload, 'accounts', 'https://your-app.com/webhook-endpoint');
    
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