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

Salesforce Rest Sdk Laravel Package

ae/salesforce-rest-sdk

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require ae/salesforce-rest-sdk
    
  2. Basic Client Initialization (for OAuth):

    use AE\SalesforceRestSdk\Rest\Client;
    use AE\SalesforceRestSdk\AuthProvider\OAuthProvider;
    
    $client = new Client(
        new OAuthProvider(
            env('SF_CLIENT_ID'),
            env('SF_CLIENT_SECRET'),
            env('SF_LOGIN_URL', 'https://login.salesforce.com'),
            env('SF_USERNAME'),
            env('SF_PASSWORD'),
            env('SF_SECURITY_TOKEN', '') // Optional
        ),
        '58.0' // API version (optional, defaults to 44.0)
    );
    
  3. First Use Case: Querying Data

    $query = 'SELECT Id, Name FROM Account LIMIT 10';
    $results = $client->query($query);
    foreach ($results as $record) {
        echo $record['Name'] . "\n";
    }
    
  4. Key Starting Points:

    • API Documentation (reference for endpoints).
    • Client class methods: query(), queryAll(), queryMore(), describeSObject(), create(), update(), etc.
    • Composite API for batch operations.

Implementation Patterns

Core Workflows

1. Authentication & Session Management

  • OAuth Flow: Use OAuthProvider for web apps (redirect-based auth).
    $provider = new OAuthProvider($clientId, $clientSecret, $loginUrl, null, null, null, $redirectUri);
    $client = new Client($provider);
    $accessToken = $provider->getAccessToken($authCode); // After redirect
    
  • Username/Password: For server-to-server (less secure, avoid in production).
    $provider = new OAuthProvider($clientId, $clientSecret, $loginUrl, $username, $password, $securityToken);
    
  • Refresh Tokens: Handle token expiration gracefully.
    try {
        $client->query('SELECT Id FROM Account LIMIT 1');
    } catch (\AE\SalesforceRestSdk\Exception\AuthException $e) {
        $provider->refreshAccessToken();
        retryOperation();
    }
    

2. CRUD Operations

  • Create/Update:
    $account = [
        'Name' => 'Test Account',
        'Description' => 'Created via SDK'
    ];
    $created = $client->create('Account', $account);
    $updated = $client->update('Account', $created['id'], ['Description' => 'Updated']);
    
  • Bulk Operations (for large datasets):
    $batch = $client->newBatch();
    $batch->add('Account', 'insert', $accountsArray);
    $batch->add('Contact', 'upsert', $contactsArray, 'Email');
    $results = $batch->execute();
    

3. Composite API

  • Tree Operations (parent-child relationships):
    $tree = $client->newTree();
    $tree->add('Account', '001xx000003D', ['fields' => ['Name']]);
    $tree->addChild('Contact', '003xx000004E', ['fields' => ['FirstName']], '001xx000003D');
    $results = $tree->execute();
    
  • Collections (multiple records in one call):
    $collection = $client->newCollection();
    $collection->add('Account', '001xx000003D', ['fields' => ['Name']]);
    $collection->add('Account', '001xx000003E', ['fields' => ['Name']]);
    $results = $collection->execute();
    

4. Streaming API (Real-Time Updates)

  • Subscribe to Change Data Capture (CDC):
    $client->subscribeToChangeData('Account', function ($event) {
        log("Account updated: " . $event['ChangeEventHeader']['entityName']);
    });
    
  • Push Topics (for custom events):
    $client->subscribeToPushTopic('MyTopic', function ($payload) {
        log("Push event: " . $payload['data']);
    });
    

5. Metadata & Describe

  • Global Describe (list all objects):
    $describe = $client->describeGlobal();
    $objects = $describe['sobjects'];
    
  • SObject Describe (schema for a specific object):
    $describe = $client->describeSObject('Account');
    $fields = $describe['fields'];
    

6. Bulk API

  • Job Management:
    $job = $client->newBulkJob('Account', 'insert');
    $job->addRecords($accountsArray);
    $job->close();
    $job->monitor(); // Poll for completion
    $results = $job->getResults();
    

Integration Tips

  • Error Handling: Wrap calls in try-catch blocks. Common exceptions:
    • AuthException: Token expired or invalid.
    • ApiException: Salesforce API errors (e.g., INVALID_FIELD).
    • HttpException: Network issues.
  • Rate Limiting: Use $client->getLimits() to check API usage.
    $limits = $client->getLimits();
    if ($limits['queriesRemaining'] < 5) {
        sleep(60); // Wait to avoid hitting limits
    }
    
  • Logging: Enable debug logging for troubleshooting:
    $client->setLogger(new \Monolog\Logger('salesforce', [
        new \Monolog\Handler\StreamHandler('salesforce.log', \Monolog\Logger::DEBUG)
    ]));
    
  • Testing: Use sandbox orgs and mock the Client for unit tests:
    $mockClient = Mockery::mock('AE\SalesforceRestSdk\Rest\Client');
    $mockClient->shouldReceive('query')->andReturn([['Id' => '001xx000003D']]);
    

Gotchas and Tips

Pitfalls

  1. API Version Lock-In:

    • The SDK defaults to v44.0. Always specify a recent version (e.g., 58.0) to avoid deprecated endpoints.
    • Check Salesforce API Version Support for breaking changes.
  2. Bulk API Quirks:

    • Job Timeout: Bulk jobs can take hours. Use monitor() in a loop with delays:
      while (!$job->isComplete()) {
          sleep(5);
          $job->monitor();
      }
      
    • Batch Size Limits: Each batch in a bulk job has a 10,000-record limit. Split large datasets accordingly.
    • CSV Formatting: Bulk API expects CSV with specific escaping rules. Use $client->newBulkJob()->addRecordsAsCsv() for complex data.
  3. Streaming API Issues:

    • Connection Drops: Long-running subscriptions may drop. Implement reconnection logic:
      while (true) {
          try {
              $client->subscribeToChangeData('Account', $callback);
              break;
          } catch (\Exception $e) {
              sleep(10);
          }
      }
      
    • Client App Name: Required for CDC filtering. Omit or set to null to receive all events.
  4. Composite API Limits:

    • Max Subtree Depth: Tree operations are limited to 10 levels deep.
    • Response Size: Composite responses are capped at 3MB. Avoid fetching large datasets in a single call.
  5. Authentication Edge Cases:

    • Security Token: Required for username/password auth in production (not sandbox).
    • OAuth Redirect: Ensure your redirectUri matches the one registered in Salesforce.
    • Token Expiry: Access tokens expire after 2 hours. Always handle AuthException to refresh.
  6. SOQL Limitations:

    • Field Limits: Queries can return max 2,000 fields (not records). Use SELECT Id, Name instead of SELECT *.
    • Offset Pagination: queryMore() is required for large datasets. Avoid LIMIT without queryMore:
      $query = 'SELECT Id FROM Account';
      $results = $client->query($query);
      do {
          foreach ($results as $record) { /* ... */ }
          $results = $client->queryMore($results['done'] ?? 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.
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