NeuroAgent

How to programmatically create an invoice for CRM

Complete guide to programmatically generating invoices from order data and integrating with CRM systems. Learn about libraries, APIs, and practical code examples.

Question

How to programmatically generate and obtain an invoice file from customer order data for transmission to a CRM system?

Hello! I have a task: I need to generate an invoice from customer order data and convert it to a file format for subsequent transmission to a CRM system.

Specific questions:

  1. How to programmatically generate an invoice file based on customer order data?
  2. What methods or APIs allow obtaining the actual invoice file rather than just its data?
  3. How to properly integrate the invoice generation process with a CRM system?

I’m particularly interested in solutions for obtaining the invoice in file format, as data transmission to the CRM is already implemented. I would be grateful for any code examples, library recommendations, or step-by-step instructions.

NeuroAgent

For programmatic generation of payment invoices from customer order data, various approaches can be used, including creating PDF files using specialized libraries, integrating with banking APIs to get ready-made electronic invoices, as well as automatically transferring generated documents to CRM systems through API integration.

Table of Contents


Main Approaches to Invoice Generation

There are several main approaches to programmatic generation of payment invoices:

  1. Creating PDF documents - the most common method for obtaining invoice files in a standard format
  2. Integration with banking services - using ready-made bank APIs to generate electronic invoices
  3. Automatic generation in CRM systems - built-in capabilities of modern CRM systems for creating documents

Important: When choosing an approach, consider the legal requirements for electronic documents and the need to store original invoices.

For creating PDF invoices, the most popular libraries are iText, PDFKit, and WeasyPrint, which allow generating professionally formatted documents from order data.


Libraries for Creating PDF Invoices

For programmatic generation of PDF invoices, there are specialized libraries that work with various programming languages:

Python Solutions

python
# Example using ReportLab
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle, Paragraph
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.units import inch

def generate_invoice(order_data, filename):
    doc = SimpleDocTemplate(filename, pagesize=letter)
    elements = []
    
    styles = getSampleStyleSheet()
    elements.append(Paragraph("Invoice", styles['h1']))
    
    # Creating a table with order data
    table_data = [['Item', 'Quantity', 'Price', 'Amount']]
    for item in order_data['items']:
        table_data.append([item['name'], str(item['quantity']), 
                          f"{item['price']:.2f}", f"{item['total']:.2f}"])
    
    table = Table(table_data)
    table.setStyle(TableStyle([
        ('BACKGROUND', (0, 0), (-1, 0), colors.grey),
        ('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
        ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
        ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
        ('BOTTOMPADDING', (0, 0), (-1, 0), 12),
    ]))
    
    elements.append(table)
    doc.build(elements)

JavaScript Solutions

javascript
// Example using jsPDF
const { jsPDF } = require("jspdf");
require("jspdf-autotable");

function generateInvoice(data) {
    const doc = new jsPDF();
    
    // Header
    doc.setFontSize(18);
    doc.text('Invoice', 105, 15, { align: 'center' });
    
    // Items table
    doc.autoTable({
        head: [['Item', 'Qty', 'Price', 'Amount']],
        body: data.items.map(item => [
            item.name,
            item.quantity,
            item.price.toFixed(2),
            item.total.toFixed(2)
        ])
    });
    
    // Save file
    doc.save(`invoice_${data.order_id}.pdf`);
}

According to research, modern CRM systems often have built-in document generation mechanisms, which can simplify integration.


Integration with Banking Services

Many banks provide APIs for generating electronic invoices and documents. This allows you to get ready-made invoice files in standard formats:

Main Capabilities of Banking APIs:

  • Generation of QR codes for payment
  • Creation of electronic invoices in PDF format
  • Automatic formation of payment orders
  • Integration with electronic document management systems

As noted in research, major banks in Russia are actively developing API integrations, including exchange of customer invoice data.

Example of integration with a banking API for invoice generation:

python
import requests

def generate_bank_invoice(order_data, bank_api_key):
    headers = {
        'Authorization': f'Bearer {bank_api_key}',
        'Content-Type': 'application/json'
    }
    
    payload = {
        'order_id': order_data['id'],
        'customer': order_data['customer'],
        'items': order_data['items'],
        'total_amount': order_data['total']
    }
    
    response = requests.post(
        'https://api.bank.com/v1/invoices/generate',
        headers=headers,
        json=payload
    )
    
    if response.status_code == 200:
        return response.content  # Returns PDF file in binary format
    else:
        raise Exception('Invoice generation error')

Automatic Transfer to CRM Systems

Integration of the invoice generation process with CRM systems allows for automation of document flow and increased operational efficiency:

Main Integration Methods:

  1. Direct API integration - direct interaction with CRM through their APIs
  2. Webhook notifications - automatic sending of invoices to CRM upon creation
  3. File exchange - uploading generated invoices to CRM through file interfaces

As noted in research, integration of amoCRM and ERP allows for automation of sales and warehouse operations without errors, synchronizing data between systems.

Example of integration with CRM via API:

python
def upload_invoice_to_crm(pdf_file, crm_config):
    url = f"{crm_config['base_url']}/api/v2/documents"
    headers = {
        'Authorization': f'Bearer {crm_config["api_key"]}',
        'Content-Type': 'application/pdf'
    }
    
    with open(pdf_file, 'rb') as f:
        response = requests.post(
            url,
            headers=headers,
            data=f.read(),
            params={
                'deal_id': crm_config['deal_id'],
                'document_type': 'invoice'
            }
        )
    
    return response.json()

Practical Implementation Examples

Complete invoice generation and transfer cycle:

python
import os
import requests
from datetime import datetime

class InvoiceGenerator:
    def __init__(self, bank_api_key, crm_config):
        self.bank_api_key = bank_api_key
        self.crm_config = crm_config
    
    def generate_and_send_invoice(self, order_data):
        # 1. Generate invoice via banking API
        pdf_content = self._generate_bank_invoice(order_data)
        
        # 2. Save temporary file
        temp_file = f"/tmp/invoice_{datetime.now().strftime('%Y%m%d_%H%M%S')}.pdf"
        with open(temp_file, 'wb') as f:
            f.write(pdf_content)
        
        try:
            # 3. Upload to CRM
            result = self._upload_to_crm(temp_file)
            
            # 4. Clean up temporary file
            os.remove(temp_file)
            
            return result
        except Exception as e:
            # In case of error, leave file for analysis
            raise Exception(f"CRM integration error: {str(e)}")
    
    def _generate_bank_invoice(self, order_data):
        # Implementation of banking API call
        pass
    
    def _upload_to_crm(self, pdf_file):
        # Implementation of upload to CRM
        pass

CRM Automation Setup:

According to research, CRM for subscriptions helps automate reminders and control tasks, which can also be applied to working with invoices.

Setting up triggers in CRM:

  1. Create invoice when order is placed
  2. Send payment reminders
  3. Automatically update status after payment confirmation
  4. Generate acts of completed work based on paid invoices

Security and Compliance Recommendations

When implementing an invoice generation system, it’s important to consider the following aspects:

Data Security:

  • Using HTTPS when transferring documents
  • Encrypting confidential information in invoices
  • Limited access to API keys
  • Maintaining access logs for invoices

Legal Compliance:

  • Using approved formats for electronic documents
  • Complying with electronic signature requirements
  • Correctly indicating organization details
  • Maintaining document change history

As noted in research, document automation in 1C allows accelerating many processes and avoiding document loss.

Monitoring and Analytics:

  • Tracking payment statuses of invoices
  • Analyzing payment process duration
  • Identifying issues in automatic generation
  • Optimizing invoice templates based on feedback

Sources

  1. OpenAI API in Russia: how to buy access and pay for a subscription in 2025 — Services on vc.ru
  2. How to create a QR code for payment using organization details: SBP and IP
  3. Secrets of creating an effective REST API: a guide for system analysts / Habr
  4. API Gateway implementation: problems, solutions, practical recommendations / Habr
  5. Automatic API documentation with OpenAPI | PlantagoWeb
  6. API integrations: how it works and why businesses need it | Blog
  7. What is REST API and how it works: methods, examples, principles, advantages and disadvantages, how to learn to work with it
  8. Major banks in Russia will start exchanging customer account data via API
  9. Four largest banks will start exchanging account data through open APIs - Vedomosti
  10. Software for working with customers and customer accounting
  11. amoCRM + ERP integration: how to automate sales and warehouse without errors — Business analyst from Salekit on vc.ru
  12. CRM for subscriptions: Automation of tasks and customer control
  13. CRM for a travel agency: how to stop losing customers and automate tour sales
  14. 9 free CRM systems: comparing capabilities and limitations
  15. Document automation in 1C: what processes can be accelerated already tomorrow
  16. Online payment invoice in Kazakhstan: how to issue through banking apps for business
  17. How I wrote a CRM system for a company using ChatGPT. Without experience in commercial programming / Habr
  18. How much does CRM system implementation cost: factors and examples | BoevLab
  19. New currency control rules: how to avoid fines and account blocking - news Pravo.ru

Conclusion

  1. Choosing an approach to invoice generation depends on your business requirements - creating PDFs through specialized libraries or integrating with banking APIs to get ready-made electronic invoices.

  2. Integration with CRM systems allows complete automation of document flow, minimizing the human factor and increasing efficiency in customer relations.

  3. Security and compliance with legislation should be a priority when implementing any invoice generation system, especially when working with financial documents.

  4. Continuous improvement of the invoice generation process based on feedback and data analysis will help optimize business processes and improve customer experience.

For more detailed information on specific integrations, it’s recommended to study the documentation of your banking services and CRM systems, as well as consult with qualified specialists in business process automation.