๐งพGenerate & Send an E-Invoice
Learn how to generate and dispatch invoices through Docs-Dispatcher with complete end-to-end examples in 4 languages (curl, Node.js, PHP, Java).
Overview
This comprehensive recipe walks you through the complete invoice generation and dispatch workflow:
Set up Basic Authentication credentials
Prepare your invoice data
Validate the request (recommended safety check)
Send the invoice to your accounting provider
Handle the response and track status
By the end of this guide, you'll have working code to automatically generate and send invoices to providers like Qonto, PennyLane, and iPaidThat.
What You'll Learn
How to structure invoice requests for different providers
Best practices for validation before sending
Error handling strategies
Async vs sync dispatch modes
Provider-specific features and limitations
Complete working examples in 4 languages
Prerequisites
Before you begin:
Docs-Dispatcher account with email and password
At least one invoicing provider configured (Qonto, PennyLane, iPaidThat, or SuperPDP)
Template created in Templater (or use API to create one)
Basic understanding of REST APIs
No provider configured yet? You can still test with the validation endpoint - it checks your request format without calling external APIs or charging credits.
Step 1: Authentication
Dispatcher API uses HTTP Basic Authentication. You'll need your Dispatcher account email and password for all API calls.
Setup Credentials
No token management needed! Unlike JWT-based APIs, Basic Auth doesn't require separate authentication endpoints or token refresh. Your credentials are sent with each request.
Quick links:
Step 2: Prepare Invoice Data
Structure your invoice data according to the CompositeRequest model. The request has two main parts:
Template - Specifies which template to use and the data to populate it
Service fields - Provider name, document type, and invoicing-specific options
Basic Invoice Structure
Required Fields
providerName
string
Provider to use: qonto, pennylane, ipaidthat, superpdp
documentType
string
Document type: INVOICE, E_INVOICE, QUOTE, CREDIT
template.id
number
Template ID from Templater
template.data
object
Template variables (schema depends on template)
Optional Fields
invoicing.dueDate
string
Payment due date (ISO 8601 format)
invoicing.paymentTerms
string
Payment terms description (e.g., "Net 30")
invoicing.customerId
string
Provider's customer ID
metadata
object
Custom tracking data (max 20 key-value pairs)
Template Data Schema
The template.data object schema depends on your template. Common fields include:
Invoice details:
invoiceNumber,date,dueDateCustomer info:
name,email,address,city,postalCode,countryLine items: Array of
{description, quantity, unitPrice, total}Totals:
subtotal,taxRate,taxAmount,totalPayment:
paymentTerms,bankDetailsAdditional:
notes,conditions, custom fields
How do I know my template schema? View your template in Templater UI to see expected fields, or use the validation endpoint to test - it will report missing required fields.
Step 3: Validate Request (Recommended)
Before sending real invoices, validate your request structure. This checks for errors without calling external providers or charging credits.
Why Validate?
Catch errors early (before external API calls)
Free and fast (< 100ms response)
No risk of duplicate invoices
Test during development
Verify template data schema
Validation Request
Validation Success Response
Validation Error Response
Validation passed? You're ready to send the real invoice! Simply change /validate to /invoicing in the endpoint URL.
More on validation:
Step 4: Send Invoice (Real Dispatch)
Once validation passes, send the actual invoice by changing the endpoint from /validate to /invoicing.
Sync Mode (Default)
Synchronous mode waits for the provider to complete the operation and returns the full response immediately.
Success Response:
When to use sync mode:
User is waiting for result (interactive workflows)
Quick operations (expected completion < 30 seconds)
Simple error handling (errors returned immediately)
Testing and development
Async Mode (Recommended for Production)
Asynchronous mode queues the request immediately and processes it in the background. You receive a webhook notification when complete.
Immediate Response:
When to use async mode:
Background jobs and batch processing
Long-running operations (> 30 seconds)
High volume scenarios
Non-interactive workflows
Better scalability and resilience
More on execution modes:
Step 5: Handle Response
Process the dispatch response and handle errors gracefully.
Success Response Fields
success
true if dispatch succeeded
dispatchId
Unique dispatch identifier (use for tracking)
providerResponse
Provider-specific response (invoiceId, status, url)
generatedDocument
Generated PDF document URL and metadata
metadata
Your custom tracking data (echoed back)
executionTime
Processing time in seconds (sync mode only)
Error Response
Common Error Types
validation_error
Invalid request format
Check required fields, field types
authentication_error
Invalid/expired JWT
Refresh token, re-authenticate
provider_error
Provider API error
Check provider error details
template_not_found
Template ID doesn't exist
Verify template ID in Templater
configuration_missing
Provider not configured
Configure provider credentials
timeout
Operation took too long
Use async mode instead
HTTP Status Codes
200 OK
Success (sync mode) or queued (async mode)
400 Bad Request
Invalid request format
401 Unauthorized
Missing/invalid JWT
404 Not Found
Template or resource not found
422 Unprocessable Entity
Validation failed
500 Internal Server Error
Server error
503 Service Unavailable
Provider temporarily unavailable
Complete Examples
Here are complete, runnable examples in 4 languages showing the full invoice workflow from authentication to dispatch.
curl (Complete Flow)
Node.js (Complete Flow)
PHP (Complete Flow)
Java (Complete Flow)
Provider-Specific Notes
Different invoicing providers have unique features and requirements. Here's what you need to know for each.
iPaidThat
Provider name: ipaidthat
Features:
Full invoicing, quotes, and credit notes support
No e-invoicing support (use
INVOICEnotE_INVOICE)Sandbox environment available for testing
Specific requirements:
Customer email required
Invoice number must be unique per company
Supports French invoicing requirements
Example:
Best for:
French companies
Standard invoicing workflows
Integration with iPaidThat accounting
Qonto
Provider name: qonto
Features:
Full invoicing, quotes, and credit notes
E-invoicing support for France
Sandbox environment available (use
sandbox: truein config)Real-time invoice status updates
Customer portal for payment
Specific requirements:
IBAN required for bank transfer invoices
Supports multiple payment methods
Customer VAT number validated for B2B
Sandbox mode:
Example:
Best for:
French businesses using Qonto banking
E-invoicing compliance (Chorus Pro)
Automated payment reconciliation
Testing with sandbox
Qonto Sandbox: Use sandbox: true in your request to test without creating real invoices. Perfect for development and testing. See Qonto provider docs for details.
PennyLane
Provider name: pennylane
Features:
Complete invoicing, quotes, and credit notes
E-invoicing with automatic Chorus Pro submission
Multi-currency support
Advanced tax handling (multiple VAT rates)
Customer and product catalog integration
Specific requirements:
Product/service codes for e-invoicing
Customer SIRET for French B2B
Detailed tax breakdowns
Example:
Best for:
E-invoicing compliance (automatic Chorus Pro)
Complex tax scenarios
Multi-currency businesses
Product catalog management
SuperPDP
Provider name: superpdp
Features:
Full invoicing and quotes
Credit note support
E-invoicing with PDP platform
Integration with French tax authorities
Automatic archiving
Specific requirements:
Detailed customer address for legal compliance
SIRET/SIREN for French companies
Specific format for credit notes (reference to original invoice)
Example:
Best for:
French e-invoicing compliance
Public sector invoicing (PPP)
Automatic tax archiving
Legal document retention
Provider Comparison
Standard Invoice
โ
โ
โ
โ
E-Invoice
โ
โ
โ
โ
Quotes
โ
โ
โ
โ
Credit Notes
โ
โ
โ
โ
Sandbox
โ
โ
โ
โ
Multi-currency
โ
โ
โ
โ
Webhooks
โ
โ
โ
โ
Chorus Pro
โ
โ
โ
โ
Best for
Simple invoicing
Banking integration
Advanced features
Government/PPP
Async Mode (Using Webhooks)
For production environments, async mode with webhooks is recommended for better scalability and resilience.
Enable Async Mode
Add ?async=true to the endpoint URL:
Provide Callback URL
Implement Webhook Handler
Your webhook endpoint must:
Return 200 OK quickly (< 10 seconds)
Handle duplicate events (idempotency)
Verify webhook signature (recommended)
Process async (don't block the response)
Node.js webhook handler:
More on async mode:
Error Handling
Implement robust error handling for production reliability.
Common Errors
1. Validation Errors (400)
Cause: Invalid request format or missing required fields
Solution:
Use validation endpoint first
Check required fields for your provider
Verify template data schema
2. Authentication Errors (401)
Cause: Missing, invalid, or expired Basic Auth credentials
Solution:
Refresh Basic Auth credentials (120min expiry)
Re-authenticate if refresh fails
Store token expiration and check before requests
3. Template Not Found (404)
Cause: Template ID doesn't exist or not accessible
Solution:
Verify template ID in Templater UI
Check template belongs to your company
Ensure template is not deleted
4. Provider Errors (422)
Cause: Provider API rejected the request
Solution:
Check provider-specific requirements
Use unique invoice numbers
Verify customer data format
Check provider documentation
5. Timeout Errors (504)
Cause: Operation took longer than 120 seconds (sync mode only)
Solution:
Use async mode (
?async=true)Reduce document size/complexity
Contact support if timeout persists
Error Handling Example
Troubleshooting Common Issues
Issue 1: "Template not found"
Symptoms:
404 error when dispatching
Message: "Template with ID XXX not found"
Causes:
Wrong template ID
Template deleted
Template belongs to different company
User lacks access to template
Solutions:
Verify template ID in Templater UI
Check template exists:
GET /api/v1/templates/{id}Ensure template belongs to your company
Check user permissions
Issue 2: "Duplicate invoice number"
Symptoms:
Provider error: "Invoice already exists"
Message mentions invoice number conflict
Causes:
Invoice number already used in provider
Multiple simultaneous requests with same number
Solutions:
Use unique invoice numbers (timestamp, UUID, counter)
Check existing invoices before dispatch
Implement retry with new number
Use provider's invoice number validation API
Issue 3: "Invalid customer data"
Symptoms:
Validation error on customer fields
Provider rejects customer information
Causes:
Missing required customer fields
Invalid email format
Invalid address/postal code
Wrong country code format
Solutions:
Validate customer data before dispatch
Use proper country codes (ISO 3166-1 alpha-2: FR, US, etc.)
Validate email format
Include all required fields for your provider
Issue 4: "Token expired"
Symptoms:
401 Unauthorized error
Message: "Invalid or expired Basic Auth credentials"
Causes:
Basic Auth credentials older than 120 minutes
System clock skew
Token not refreshed
Solutions:
Implement token refresh logic
Store token expiration timestamp
Refresh token before expiry (10min buffer)
Re-authenticate if refresh fails
Issue 5: "Calculation mismatch"
Symptoms:
Validation error: "Total doesn't match subtotal + tax"
Provider rejects invoice due to amount discrepancy
Causes:
Rounding errors in calculations
Incorrect tax rate application
Item totals don't sum to subtotal
Solutions:
Use decimal-safe math libraries
Round consistently (2 decimal places for currency)
Validate calculations before dispatch
Use provider's calculation rules
What Happens Behind the Scenes
Understanding the complete workflow helps troubleshoot issues and optimize your integration.
Complete Dispatch Flow
Timing Breakdown
Typical sync mode timing:
JWT validation: 10-50ms
Request validation: 50-100ms
Template loading: 100-200ms
Document generation: 500-2000ms
Provider API call: 1000-5000ms
Total: 1.5-7 seconds
Async mode timing:
Queue dispatch: 50-200ms
Background processing: 2-30 seconds
Webhook delivery: 100-500ms
Resource Usage
What gets created:
Generated PDF - Stored in cloud storage (30-day retention)
Provider invoice - Created in accounting platform
Dispatch record - Tracked in Dispatcher database
Audit log - Security and compliance tracking
What gets charged:
1 credit per successful invoice dispatch
0 credits for validation requests
0 credits for failed dispatches (validation errors)
Credits deducted after successful provider response
Next Steps
Now that you know how to generate and send invoices:
Related Recipes
Credit Note (Avoir) - Issue refunds and adjustments
Quote (Devis) - Generate quotes before invoicing
Validate then Send - Production-ready validation pattern
Async Flow - Scale with webhooks and background processing
Email Dispatch - Email invoices to customers
Core Concepts
Request Model - Understand CompositeRequest structure
Providers & Configurations - Configure providers
Sync vs Async - Choose execution mode
Services - Explore all services
Provider Documentation
Qonto - Qonto-specific features and sandbox
PennyLane - PennyLane integration details
iPaidThat - iPaidThat configuration
SuperPDP - SuperPDP e-invoicing
SDKs
Node.js SDK - Pre-built Node.js client
PHP SDK - PHP integration library
Java SDK - Java client library
Support
Check Common Errors for error reference
See Provider Issues for provider-specific problems
Use Debug Checklist for systematic troubleshooting
Contact [email protected] for help
Summary
You've learned how to:
โ Authenticate and obtain Basic Auth credentials
โ Structure invoice requests for different providers
โ Validate requests before sending (safety check)
โ Send invoices in sync and async modes
โ Handle responses and errors gracefully
โ Implement complete workflows in 4 languages
โ Choose the right provider for your needs
โ Troubleshoot common issues
Ready for production? Follow this checklist:
Configure your provider credentials (company/user level)
Create and test templates in Templater
Validate all requests before production dispatch
Implement error handling and retry logic
Use async mode with webhooks for scalability
Monitor dispatch success rates
Set up alerts for failures
Happy invoicing!
Last updated