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

Yousign Bundle Laravel Package

com-company/yousign-bundle

Bundle Symfony pour intégrer Yousign (API v3, compat v2) : configuration via variables d’environnement, envoi de demandes de signature et gestion des webhooks (routes, listeners/handlers, payloads) avec binding d’événements.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**
   ```bash
   composer require com-company/yousign-bundle

Add the bundle to config/bundles.php:

return [
    // ...
    ComCompany\YousignBundle\YousignBundle::class => ['all' => true],
];
  1. Environment Configuration Set .env variables for V3 (focused on this package):

    YOUSIGN_V3_URI=https://api-sandbox.yousign.app/v3/  # or prod
    YOUSIGN_V3_TOKEN=your_v3_api_token
    YOUSIGN_V3_ACCESS_KEY=your_webhook_key_if_needed
    
  2. First Use Case: Sending a Signature Request with Custom Signing Date Inject the YousignClient service and use it to create a signature workflow with a predefined signing date:

    use ComCompany\YousignBundle\Client\YousignClient;
    use ComCompany\YousignBundle\Model\SignatureRequest;
    use ComCompany\YousignBundle\Model\Signer;
    
    public function createSignatureWithDate(YousignClient $client)
    {
        $signer = new Signer();
        $signer->setEmail('user@example.com');
        $signer->setSigningDate('2024-12-31'); // New feature: Set a specific signing date
    
        $request = new SignatureRequest();
        $request->setSubject('Contract Approval');
        $request->setSigners([$signer]);
        $request->setDocuments([['url' => 'https://example.com/contract.pdf']]);
    
        $response = $client->sendSignatureRequest($request);
        return $response->getUrl(); // Redirect URL for signer
    }
    

Implementation Patterns

Core Workflows

  1. Signature Requests with Signing Dates

    • Setting a Signing Date: Use the setSigningDate() method on the Signer object to specify when the signer must sign.
      $signer->setSigningDate('YYYY-MM-DD'); // ISO 8601 format
      
    • Validation: Ensure the date is in the future to avoid rejection by Yousign’s API.
    • Use Case: Ideal for contracts requiring signatures on specific dates (e.g., lease agreements, legal deadlines).
  2. Signature Requests

    • Creation: Use YousignClient::sendSignatureRequest() with a SignatureRequest object.
    • Status Check: Poll with YousignClient::getSignatureRequestStatus() or use webhooks (see below).
    • Templates: Predefine templates via YousignClient::createTemplate() and reuse them.
  3. Webhooks (Event-Driven)

    • Setup: Declare routes in config/routes/yousign.yaml (as per README).
    • Handlers: Implement EventHandlerInterface for each event (e.g., signature_request_created, signature_request_signed).
      // Example: src/EventHandler/SignatureSignedHandler.php
      use ComCompany\YousignBundle\Event\WebhookPayload;
      use ComCompany\YousignBundle\Event\EventHandlerInterface;
      
      class SignatureSignedHandler implements EventHandlerInterface
      {
          public function handle(WebhookPayload $payload): void
          {
              $event = $payload->getEvent();
              if ($event === 'signature_request_signed') {
                  $data = $payload->getData();
                  if (isset($data['signing_date'])) {
                      // Handle custom signing date logic
                  }
              }
          }
      }
      
    • Register Handlers: Bind handlers in a service provider or via autowiring tags.
  4. Document Management

    • Upload documents via YousignClient::uploadDocument() and attach them to requests.
  5. Error Handling

    • Wrap API calls in try-catch blocks to handle YousignException:
      try {
          $response = $client->sendSignatureRequest($request);
      } catch (YousignException $e) {
          // Log or notify (e.g., $e->getMessage())
          if (str_contains($e->getMessage(), 'signing_date')) {
              // Handle date-specific validation errors
          }
      }
      

Integration Tips

  • Symfony Forms: Bind signature URLs and signing dates to form fields for user redirection and date selection.
  • Queue Jobs: Offload long-running operations (e.g., status checks) to Symfony’s queue system.
  • Testing: Use the sandbox URI (YOUSIGN_V3_URI) and mock the YousignClient in PHPUnit:
    $client = $this->createMock(YousignClient::class);
    $client->method('sendSignatureRequest')->willReturn(new SignatureResponse());
    $this->assertEquals('2024-12-31', $client->getLastSigningDate());
    

Gotchas and Tips

Pitfalls

  1. Environment Variables

    • V2 vs. V3 Confusion: Ensure you’re using YOUSIGN_V3_* variables, not V2_* ones.
    • Missing URI: Forgetting to set YOUSIGN_V3_URI will throw RuntimeException on client initialization.
  2. Signing Date Validation

    • Future Date Requirement: Yousign’s API may reject requests with past dates. Validate dates server-side:
      $signingDate = new \DateTime('2024-12-31');
      if ($signingDate < new \DateTime()) {
          throw new \InvalidArgumentException('Signing date must be in the future.');
      }
      
    • Time Zone Handling: Ensure dates are in UTC or explicitly convert them to avoid timezone-related issues.
  3. Webhook Quirks

    • Access Key Validation: If using webhooks, ensure YOUSIGN_V3_ACCESS_KEY is set and matches the key in the Yousign dashboard.
    • Route Prefix Collisions: Customize the yousign.yaml prefix to avoid conflicts with existing routes.
    • Event Payload Parsing: Webhook payloads may now include signing_date for signed events. Use $payload->getData() and cast to WebhookPayload for type safety.
  4. Rate Limiting

    • Yousign’s API has rate limits. Implement exponential backoff in retries:
      use Symfony\Component\HttpClient\RetryableHttpClient;
      
      $client = new RetryableHttpClient(
          $httpClient,
          [
              'max_retries' => 3,
              'delay' => 1000, // ms
              'multiplier' => 2,
          ]
      );
      
  5. Document URLs

    • Public Access: Ensure documents referenced in SignatureRequest are publicly accessible (Yousign fetches them via URL).
    • Temporary Links: For sensitive docs, use short-lived presigned URLs (e.g., AWS S3).

Debugging Tips

  1. Logging Enable debug mode in config/packages/yousign.yaml:

    yousign:
        debug: true  # Logs API requests/responses to monolog
    

    Check logs for raw payloads during webhook testing, especially for signing_date fields.

  2. Webhook Testing

    • Use tools like ngrok to expose local routes to Yousign’s sandbox for testing.
    • Validate payloads with Yousign’s webhook simulator, paying attention to the new signing_date field.
  3. Common Errors

    • 401 Unauthorized: Verify YOUSIGN_V3_TOKEN is correct and not expired.
    • 400 Bad Request: Validate SignatureRequest data (e.g., required fields like subject, signers, or signing_date format).
    • 500 Internal Server Error: Check Yousign’s status page for outages.

Extension Points

  1. Custom Events for Signing Dates Extend the bundle’s event system to handle signing_date in webhooks or custom events:

    use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
    
    $dispatcher->dispatch(new SigningDateEvent($payload->getData()['signing_date']));
    
  2. Service Decorators for Date Logic Decorate YousignClient to add pre/post-processing logic for signing dates:

    class CustomYousignClientDecorator implements YousignClientInterface
    {
        public function __construct(private YousignClientInterface $decorated)
        {}
    
        public function sendSignatureRequest(SignatureRequest $request): SignatureResponse
        {
            // Pre-process: Validate or modify signing dates
            $this->validateSigningDates($request->getSigners());
            $response = $this->decorated->sendSignatureRequest($request);
            // Post
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui