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

Esign Client Laravel Package

docusign/esign-client

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require docusign/esign-client
    

    Ensure require_once('vendor/autoload.php'); is included in your Laravel app’s bootstrap (e.g., bootstrap/app.php).

  2. Authentication Setup

    • Register a Docusign developer account (Sandbox).
    • Choose OAuth flow (recommended: Authorization Code Grant) or JWT.
    • Store credentials in Laravel’s .env:
      DOCUSIGN_CLIENT_ID=your_client_id
      DOCUSIGN_CLIENT_SECRET=your_client_secret
      DOCUSIGN_REDIRECT_URI=http://your-app.com/callback
      DOCUSIGN_PRIVATE_KEY=-----BEGIN RSA PRIVATE KEY-----\n... (for JWT)
      
  3. First Use Case: Send a Simple Envelope

    use DocuSign\eSign\Model\EnvelopeDefinition;
    use DocuSign\eSign\Model\Signer;
    use DocuSign\eSign\Model\SignHere;
    use DocuSign\eSign\Model\Document;
    use DocuSign\eSign\Api\EnvelopesApi;
    
    // Initialize API client (OAuth example)
    $apiClient = new \DocuSign\eSign\ApiClient();
    $apiClient->setOAuthBasePath('https://account-d.docusign.com/oauth');
    $apiClient->setBasePath('https://demo.docusign.net/restapi');
    
    // Authenticate (simplified; use OAuth or JWT in practice)
    $apiClient->setDefaultHeader('Authorization', 'Bearer ' . $accessToken);
    
    // Create envelope
    $envelopesApi = new EnvelopesApi($apiClient);
    $document = new Document('1', 'https://example.com/document.pdf');
    $signHere = new SignHere('1', '10', '10', '50', '50');
    $signer = new Signer('signer@example.com', 'John Doe', 'signer1', '1', [$signHere]);
    $envelopeDefinition = new EnvelopeDefinition('Test Envelope', 'Test Subject', [$document], [$signer]);
    
    $envelopeSummary = $envelopesApi->createEnvelope($accountId, $envelopeDefinition);
    

Implementation Patterns

Core Workflows

  1. Envelope Management

    • Create/Update: Use EnvelopesApi::createEnvelope() and EnvelopesApi::updateEnvelope().
    • Retrieve Status: Poll with EnvelopesApi::getEnvelope() and check status (e.g., "completed", "declined").
    • Recipients: Dynamically add signers/cc’s via Signer, CarbonCopy, or InPersonSigner.
  2. Templates & Bulk Sending

    • Templates: Pre-define envelopes in Docusign, then instantiate with TemplatesApi::createTemplateEnvelope().
    • Bulk Send: Use BulkSendingApi for batch operations (e.g., mass mailouts).
  3. Authentication Patterns

    • OAuth (Recommended):
      • Redirect users to Docusign’s OAuth endpoint.
      • Exchange code for tokens via ApiClient::requestJWTUserToken() or requestAuthorizationCode().
      • Store tokens securely (e.g., Laravel’s encrypter).
    • JWT: Use ApiClient::requestJWTUserToken() with a private key (store in .env or AWS Secrets Manager).
  4. Webhooks

    • Configure webhooks in Docusign’s admin console to trigger Laravel events (e.g., EnvelopeCompleted).
    • Handle callbacks via a Laravel route:
      Route::post('/docusign/webhook', function (Request $request) {
          $payload = $request->json()->all();
          // Validate signature, dispatch event, etc.
      });
      
  5. Document Handling

    • Upload: Use DocumentsApi::uploadDocument() for large files.
    • Merge Fields: Dynamically populate tabs with Laravel collections:
      $tabs = [];
      foreach ($users as $user) {
          $tabs[] = new \DocuSign\eSign\Model\Text('user_' . $user->id, '100,100,100,100', $user->name);
      }
      

Integration Tips

  • Laravel Service Provider: Bind the SDK to Laravel’s container for dependency injection:

    public function register()
    {
        $this->app->singleton(EnvelopesApi::class, function ($app) {
            $apiClient = new \DocuSign\eSign\ApiClient();
            $apiClient->setOAuthBasePath(config('docusign.oauth_base_path'));
            $apiClient->setBasePath(config('docusign.base_path'));
            $apiClient->setDefaultHeader('Authorization', 'Bearer ' . $app['auth']->user()->docusignToken);
            return new EnvelopesApi($apiClient);
        });
    }
    
  • Queues for Async Operations: Dispatch envelope creation to a queue (e.g., SendEnvelopeJob) to avoid timeouts:

    SendEnvelopeJob::dispatch($envelopeDefinition)->onQueue('docusign');
    
  • Error Handling: Wrap SDK calls in try-catch blocks and log ApiException details:

    try {
        $envelope = $envelopesApi->createEnvelope($accountId, $definition);
    } catch (\DocuSign\eSign\ApiException $e) {
        Log::error('Docusign error: ' . $e->getMessage(), ['error' => $e->getResponseBody()]);
        throw new \Exception('Failed to send envelope');
    }
    

Gotchas and Tips

Pitfalls

  1. Token Expiry

    • OAuth tokens expire (typically 1 hour). Implement token refresh logic:
      if ($token->isExpired()) {
          $refreshedToken = $apiClient->requestRefreshToken(
              config('docusign.refresh_token'),
              config('docusign.client_id'),
              config('docusign.client_secret')
          );
      }
      
    • Tip: Use Laravel’s auth:api token system or a package like spatie/laravel-activitylog to track token lifecycles.
  2. Rate Limiting

    • Docusign enforces rate limits. Cache responses and implement exponential backoff:
      if ($response->getStatusCode() === 429) {
          sleep($response->getHeader('Retry-After'));
          retry();
      }
      
  3. Document Size Limits

    • Files >10MB may fail silently. Use DocumentsApi::uploadDocument() for large files and chunk uploads if needed.
  4. Time Zone Mismatches

    • Docusign uses UTC. Ensure Laravel’s config/app.php has 'timezone' => 'UTC' to avoid signing date discrepancies.
  5. Sandbox vs. Production

    • Always test in Sandbox first. Use https://demo.docusign.net (Sandbox) vs. https://api.docusign.com (Production).

Debugging

  • Enable SDK Logging:
    $apiClient->setDebug(true); // Logs requests/responses to STDOUT
    
  • Validate Payloads: Use EnvelopeValidator to check envelope definitions before sending:
    use DocuSign\eSign\Model\EnvelopeValidator;
    $validator = new EnvelopeValidator();
    $errors = $validator->validateEnvelope($envelopeDefinition);
    

Extension Points

  1. Custom Models Extend SDK models (e.g., Signer) to add Laravel-specific logic:

    class LaravelSigner extends \DocuSign\eSign\Model\Signer
    {
        public function __construct(User $user, string $roleName)
        {
            parent::__construct(
                $user->email,
                $user->name,
                $roleName,
                uniqid(),
                []
            );
        }
    }
    
  2. Middleware for Auth Create Laravel middleware to inject Docusign tokens:

    public function handle(Request $request, Closure $next)
    {
        $request->merge([
            'docusign_token' => auth()->user()->docusignToken,
        ]);
        return $next($request);
    }
    
  3. Event Dispatching Trigger Laravel events on Docusign webhook payloads:

    event(new EnvelopeCompleted($payload['envelopeId'], $payload['status']));
    

Config Quirks

  • Base Paths:
    • Sandbox: https://demo.docusign.net/restapi
    • Production: https://api.docusign.com/restapi
    • OAuth: Use `account-d.docus
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.
bugban/php-sdk
littlerocket/job-queue-bundle
graham-campbell/flysystem
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
directorytree/opensearch-client
directorytree/opensearch-adapter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php