Bill
Creating Invoices

Creating Invoices

Create professional invoices with line items, tax calculation, and autopay capabilities


Invoices provide a structured way to bill customers for products, services, or subscriptions. The Payload Invoice API enables you to create detailed invoices with multiple line items, apply tax rates, configure automatic payment settings, and track payment status throughout the invoice lifecycle. Invoices can be created as standalone one-time bills or automatically generated from billing schedules for recurring payments.

Prerequisites

Before creating invoices, ensure you have:


When to Use Invoices


Invoices are ideal for structured billing scenarios where you need detailed itemization and tracking.

Benefits of invoices

  • Professional Billing: Generate detailed, itemized invoices with tax calculations
  • Autopay Support: Configure automatic payment on due date for recurring billing
  • Payment Tracking: Monitor payment status from unpaid through paid or closed
  • Line Item Details: Break down charges by product, service, quantity, and unit price
  • Tax Automation: Apply default or custom tax rates automatically
  • Organized Structure: Group related charges with item groups for clarity
  • Custom Numbering: Use your own invoice numbering scheme for accounting integration
  • Payment History: Track all payments applied to each invoice

Common use cases

  • Subscription Billing: Monthly or annual recurring charges with line item breakdowns
  • Professional Services: Hourly billing with detailed time tracking and rates
  • E-commerce Orders: Product-based invoices with shipping, tax, and discounts
  • B2B Transactions: Purchase orders, net terms, and detailed invoicing requirements
  • Membership Fees: Club dues, association fees, and recurring member charges
  • Utility Billing: Usage-based charges with multiple rate tiers
  • Project-Based Work: Milestone billing and progress payments

Creating a Simple Invoice


Create a basic invoice with line items for products or services.

import payload
pl = payload.Session('secret_key_3bW9...', api_version='v2')
 
# Create a simple invoice with line items
invoice = pl.Invoice.create(
    due_date='2024-02-01',
    description='January 2024 Services',
    payer={
        'account_id': 'acct_customer123'
    },
    biller={
        'account_id': 'acct_merchant456'
    },
    items=[
        {
            'type': 'line_item',
            'description': 'Monthly subscription',
            'line_item': {
                'value': 99.00,
                'qty': 1
            }
        },
        {
            'type': 'line_item',
            'description': 'Setup fee',
            'line_item': {
                'value': 50.00,
                'qty': 1
            }
        }
    ]
)
 
print(f'Invoice created: {invoice.id}')
print(f'Invoice number: {invoice.number}')
print(f'Total amount: {invoice.totals['total']}')
print(f'Status: {invoice.status}')

This creates an invoice with:

  • due_date specifying when payment is expected (required)
  • description providing context about the invoice
  • payer.account_id identifying who is being billed
  • biller.account_id identifying who receives payment
  • items array containing line item charges

Each line item must have:

  • type: 'line_item' to indicate it's a charge
  • description explaining what the charge is for
  • line_item.value as the unit price or rate
  • line_item.qty for quantity (defaults to 1 if omitted)

Key features:

  • Invoice totals (subtotal, tax, total) are automatically calculated
  • Invoice numbers are auto-generated as INV-000001 if not specified
  • Invoice status defaults to unpaid (ready for payment)
  • All amounts use your account's default currency

Understanding Line Items


Line items are the building blocks of an invoice, representing individual charges, discounts, or fees.

Line Item Structure

Each line item contains:

{
  type: "line_item",           // Required: indicates this is a charge
  description: "Product XYZ",   // What this charge is for
  line_item: {
    value: 99.99,               // Unit price or rate
    qty: 2,                     // Quantity (defaults to 1)
    value_units: "number"       // "number" for fixed amounts, "percentage" for percentages
  },
  line_number: 1                // Optional: controls display order
}

The total for each line item is automatically calculated as value * qty.

Working with Quantities

Use quantities for multiple units of the same item:

{
  type: "line_item",
  description: "Professional consulting (hourly)",
  line_item: {
    value: 175.00,  // $175 per hour
    qty: 8.5        // 8.5 hours worked
  }
}
// Calculated total: $1,487.50

Adding Discounts

Use negative values for discounts or credits:

{
  type: "line_item",
  description: "Early payment discount",
  line_item: {
    value: -50.00,  // Negative value reduces total
    qty: 1
  }
}

Percentage-Based Charges

Use value_units: 'percentage' for percentage-based fees:

# Percentage-based line item example
pl.Invoice.create(
    due_date="2024-02-01",
    payer={"account_id": "acct_customer123"},
    biller={"account_id": "acct_merchant456"},
    items=[
        {
            "type": "line_item",
            "description": "Processing fee (3%)",
            "line_item": {
                "value": 3.0,
                "value_units": "percentage",
                "qty": 1
            }
        }
    ]
)

Controlling Display Order

Use line_number to control how items appear on the invoice:

items: [
  {
    type: "line_item",
    description: "Product",
    line_number: 1, // Appears first
    line_item: { value: 100.0, qty: 1 }
  },
  {
    type: "line_item",
    description: "Shipping",
    line_number: 2, // Appears second
    line_item: { value: 15.0, qty: 1 }
  }
];

Organizing with Item Groups


Item groups allow you to organize related line items into sections for better readability and structure.

import payload
 
pl = payload.Session('secret_key_3bW9...', api_version='v2')
 
# Create an invoice with grouped line items
invoice = pl.Invoice.create(
    due_date='2024-03-01',
    description='E-commerce order #ORD-5678',
    payer={'account_id': 'acct_customer123'},
    biller={'account_id': 'acct_merchant456'},
    items=[
        # Products group
        {
            'type': 'item_group',
            'description': 'Products',
            'line_number': 1,
            'item_group': {
                'items': [
                    {
                        'type': 'line_item',
                        'description': 'Widget Pro - Blue',
                        'line_item': {'value': 49.99, 'qty': 2},
                    },
                    {
                        'type': 'line_item',
                        'description': 'Premium Support License',
                        'line_item': {'value': 99.00, 'qty': 1},
                    },
                ]
            },
        },
        # Shipping group
        {
            'type': 'item_group',
            'description': 'Shipping & Handling',
            'line_number': 2,
            'item_group': {
                'items': [
                    {
                        'type': 'line_item',
                        'description': 'Standard shipping',
                        'line_item': {'value': 12.50, 'qty': 1},
                    },
                    {
                        'type': 'line_item',
                        'description': 'Insurance',
                        'line_item': {'value': 5.00, 'qty': 1},
                    },
                ]
            },
        },
    ],
)
 
print(f'Invoice created: {invoice.id}')
print(f'Total items: {len(invoice.items)}')
print(f'Total amount: {invoice.totals['total']}')

Item group structure:

  • type: 'item_group' indicates this is a container, not a charge
  • description provides the group heading (e.g., "Products", "Shipping")
  • item_group.items contains nested line items belonging to this group
  • line_number controls the order of groups on the invoice

Benefits of item groups:

  • Visual Organization: Separate products, services, fees, and discounts into distinct sections
  • Professional Presentation: Invoices are easier to read and understand
  • Flexible Structure: Group items by category, department, or any logical grouping
  • Subtotals: Groups can have their own subtotals for clarity

Common grouping strategies:

  • Group by product category (hardware, software, services)
  • Separate recurring charges from one-time fees
  • Organize by project phase or deliverable
  • Group shipping, handling, and insurance together
  • Separate discounts and adjustments

Advanced Invoice Configuration


Customize invoices with tax rates, autopay settings, custom numbering, and metadata.

import payload
 
pl = payload.Session('secret_key_3bW9...', api_version='v2')
 
# Create a detailed invoice with advanced configuration
invoice = pl.Invoice.create(
    number='INV-2024-001',  # Custom invoice number
    due_date='2024-02-15',
    description='Web development services - January 2024',
    type='service',  # Invoice classification
    default_tax_rate=8.5,  # 8.5% tax rate
    payer={
        'account_id': 'acct_customer123',
        'method_id': 'pm_card_456',  # Specific payment method for autopay
    },
    biller={
        'account_id': 'acct_merchant789',
        'method_id': 'pm_bank_012',  # Where funds will be deposited
    },
    autopay_settings={'allowed': True},  # Enable automatic payment on due date
    items=[
        {
            'type': 'line_item',
            'description': 'Frontend development (40 hours)',
            'line_item': {
                'value': 150.00,  # Hourly rate
                'qty': 40,  # Hours worked
                'value_units': 'number',
            },
            'line_number': 1,
        },
        {
            'type': 'line_item',
            'description': 'Backend API integration (25 hours)',
            'line_item': {'value': 175.00, 'qty': 25, 'value_units': 'number'},
            'line_number': 2,
        },
        {
            'type': 'line_item',
            'description': 'Project discount',
            'line_item': {
                'value': -500.00,  # Negative value for discount
                'qty': 1,
                'value_units': 'number',
            },
            'line_number': 3,
        },
    ],
    attrs={'project_id': 'PROJ-456', 'purchase_order': 'PO-2024-789'},
)
 
print(f'Invoice created: {invoice.id}')
print(f'Invoice number: {invoice.number}')
print(f'Subtotal: {invoice.totals['subtotal']}')
print(f'Tax: {invoice.totals['tax']}')
print(f'Total: {invoice.totals['total']}')
print(f'Autopay enabled: {invoice.autopay_settings['allowed']}')

Tax Configuration

Apply a default tax rate to all taxable line items:

default_tax_rate: 8.5; // Applies 8.5% tax

The tax amount is automatically calculated and included in the invoice totals. Tax is applied to the subtotal of all line items.

Custom Invoice Numbers

Provide your own invoice numbering scheme:

number: "INV-2024-001"; // Custom format

If not provided, invoice numbers are auto-generated as INV-000001, incrementing for each new invoice.

Invoice Classification

Use the type field to categorize invoices:

type: "service"; // Examples: "service", "product", "subscription", "recurring"

This helps with filtering, reporting, and organizing invoices by business type.

Autopay Configuration

Enable automatic payment when the invoice is due:

autopay_settings: {
  allowed: true  // Enables autopay
},
payer: {
  account_id: "acct_customer123",
  method_id: "pm_card_456"  // Specific payment method to charge (optional)
}

When autopay is enabled:

  • The invoice automatically charges the specified payment method on due_date
  • If no method_id is specified, the payer's default payment method is used
  • Successful autopay transitions the invoice to paid status
  • Failed autopay keeps the invoice unpaid for manual payment

Specifying Fund Destination

Control where invoice payments are deposited:

biller: {
  account_id: "acct_merchant789",
  method_id: "pm_bank_012"  // Specific bank account for deposits (optional)
}

If method_id is not specified, payments go to the biller account's default funding method.

Custom Attributes

Store additional metadata with attrs:

attrs: {
  project_id: "PROJ-456",
  purchase_order: "PO-2024-789",
  department: "Engineering",
  cost_center: "CC-1001"
}

Attributes can store up to 255 characters when serialized and are useful for:

  • External system integration
  • Internal tracking and reporting
  • Custom business logic
  • Accounting system synchronization

External System Integration

Use external_uid for upsert operations and external ID tracking:

external_uid: "ERP-INV-5678"; // Unique identifier from external system

This enables:

  • Preventing duplicate invoice creation when syncing
  • Looking up invoices by external system ID
  • Upsert operations (create if doesn't exist, update if exists)
  • Maintaining consistency across systems

Draft Mode and Invoice Lifecycle


Control when invoices become payable using draft status.

Creating Draft Invoices

Create invoices that aren't ready for payment yet:

invoice = pl.Invoice.create(
    status="draft",  # Prevents payment until finalized
    due_date="2024-02-01",
    payer={"account_id": "acct_customer123"},
    biller={"account_id": "acct_merchant456"},
    items=[
        # Line items...
    ]
)

Draft invoices allow you to:

  • Build invoices gradually before sending
  • Review and approve invoices internally
  • Wait for external data before finalizing
  • Prevent premature payment attempts

Finalizing Draft Invoices

Change status to open when ready for payment:

invoice = pl.Invoice.get("inv_abc123")
 
invoice.update(
    status="open"  # Makes invoice payable, immediately transitions to unpaid/partially_paid/paid
)

When you finalize a draft invoice by setting status to open, it immediately transitions to unpaid, partially_paid, or paid based on the current balance.

Invoice Status Flow

Invoices transition through these statuses:

  • draft: Not yet published, cannot be paid
  • unpaid: Published and awaiting payment, balance due equals total
  • partially_paid: Some payment received, balance remains
  • paid: Fully paid, balance is zero
  • closed: Manually closed or cancelled

Status transitions:

  • Draft → Open → Unpaid/Partially Paid/Paid (when finalized, immediately transitions based on balance)
  • Unpaid → Partially Paid (when partial payment received)
  • Partially Paid → Paid (when balance reaches zero)
  • Unpaid/Partially Paid → Closed (manual closure)

Retrieving and Updating Invoices


Retrieve an Invoice

Get invoice details including items, payments, and totals:

invoice = pl.Invoice.get("inv_abc123")
 
print("Status:", invoice.status)
print("Total:", invoice.totals["total"])
print("Balance due:", invoice.totals["balance_due"])
print("Items:", len(invoice.items))

The invoice response includes:

  • All line items and item groups (expanded by default)
  • Calculated totals (subtotal, tax, total, paid, balance_due)
  • Payment allocations showing all payments applied
  • Payment links for customer payment
  • Payer and biller account information

Update an Invoice

Modify invoice details before payment:

invoice = pl.Invoice.get("inv_abc123")
 
invoice.update(
    due_date="2024-02-15",  # Extended due date
    description="Updated description",
    default_tax_rate=9.0  # Changed tax rate
)

Update restrictions:

  • Paid invoices cannot be modified
  • Items cannot be updated after partial payment
  • Status transitions must follow the lifecycle flow

List Invoices

Query invoices with filtering and sorting:

# Get unpaid invoices for a customer
invoices = pl.Invoice.filter_by(
    q='payer.account_id == "acct_customer123" && status == "unpaid"',
    order_by="desc(created_at)",
    limit=25
).all()
 
# Get overdue invoices
overdue = pl.Invoice.filter_by(
    q='status == "unpaid" && due_date < "2024-01-15"',
    order_by="asc(due_date)"
).all()

Schema Reference


The following fields are available when creating invoices:

Invoice Configuration

due_date
string (date)
The date by which payment is due for this invoice. If autopay is enabled, the invoice will be automatically charged on this date. For manual payments, this serves as the payment deadline. Late fees or payment reminders may be triggered based on this date. Required for all invoices.
description
string
Text description providing context about this invoice. Typically includes what the invoice is for, such as "Monthly subscription - January 2024" or "Consulting services". This appears on the invoice and helps both payer and biller understand what is being charged.
Max length: 512
number
string
A unique, human-readable invoice number for reference and organization. Automatically generated in the format "INV-000001" if not provided, incrementing for each new invoice within the same organization. Can be customized if you want to use your own numbering scheme. Used for tracking, customer communication, and accounting records.
Max length: 32
type
string
Arbitrary classification or category for this invoice. Use this to organize invoices by type, such as "subscription", "one-time", "service", "product", or custom categories specific to your business needs. Helpful for filtering, reporting, and organization.
Max length: 24
default_tax_rate
number (double)
The default tax rate (as a percentage) applied to taxable line items on this invoice. For example, 8.5 represents an 8.5% tax rate. This rate is applied automatically to line items unless overridden at the item level. Used for calculating the tax portion of the invoice total.
external_uid
string
Optional unique external identifier for this invoice from an external system. Maximum length of 64 characters. When provided, this can be used to look up the invoice or perform upsert operations (update if exists, create if not). Useful for maintaining consistency with external accounting, ERP, or billing systems. Prevents duplicate invoice creation when syncing from external sources.
Max length: 64
attrs
object
Custom attributes for extending the resource with additional key-value pairs. Maximum length is 255 characters when serialized.

Payer and Biller

payer
object
Information about the customer being invoiced. Includes the payer account and optionally the specific payment method to use for autopay. The payer is responsible for paying this invoice and will receive communications about it.
accountAccount
object
The expanded payer account object. When included, this provides full account details for who is being invoiced and is responsible for payment.
Visibility: explicit
account_id ID of Account
string
The unique identifier of the account being invoiced. This is the payer who owes payment and will receive the invoice. Required if payer account is not provided inline. (ID prefix: acct)
Pattern: ^acct_[A-Za-z0-9]+$
Required if:
payer[account]=null
object
The expanded payment method object for autopay. When included, this shows the specific payment method (card, bank account, etc.) that will be automatically charged if autopay is enabled for this invoice.
Visibility: explicit
method_id ID of PaymentMethod
string
The unique identifier of the payment method to use for automatic payment of this invoice. If specified and autopay is enabled, this payment method will be charged when the invoice is due. If not set, the payer account's default payment method will be used. Not required to belong to the payer account. (ID prefix: pm)
Pattern: ^pm_[A-Za-z0-9]+$
biller
object
Information about the merchant or service provider who issued this invoice. Includes the biller account and optionally the specific payment method for receiving funds. The biller receives payment when the payer pays this invoice.
accountAccount
object
The expanded biller account object. When included, this provides full account details for the merchant or service provider who issued this invoice and will receive payment.
Visibility: explicit
account_id ID of Account
string
The unique identifier of the processing account that issued this invoice and will receive payment. This is the merchant or service provider being paid. If not specified, the system will attempt to select an applicable biller account automatically. (ID prefix: acct)
Pattern: ^acct_[A-Za-z0-9]+$
Required if:
biller[account]=null
object
The expanded payment method object for funding. When included, this shows where the funds from this invoice payment will be deposited (the merchant's bank account or payment destination).
Visibility: explicit
method_id ID of PaymentMethod
string
The unique identifier of the payment method where funds from this invoice will be deposited. If specified, payments for this invoice will be sent to this payment method. If not set, the biller account's default funding method will be used. Must belong to the biller account. (ID prefix: pm)
Pattern: ^pm_[A-Za-z0-9]+$

The payer is the customer being invoiced. The biller is the merchant receiving payment.

Autopay Settings

autopay_settings
object
Configuration for automatic payment behavior on this invoice. Controls whether the invoice can automatically charge the payer's default payment method (if configured) when due, or if manual payment is required. Essential for managing recurring payments and subscription billing.
allowed
boolean
Controls whether automatic payment is allowed for this invoice. When set to true, if the payer has an automatic payment method configured, the invoice will be automatically charged when due. When false, the invoice must be paid manually.

Invoice Items

Invoices contain an array of items, which can be either line items (charges) or item groups (organizational containers).

Line Item Fields:

type
enum[string]
The type of invoice item. Must be either "line_item" (a single charge with amount and quantity) or "item_group" (a container for grouping multiple line items together). The type determines which fields are required and how the item is structured.
Values: line_item, item_group
description
string
Text description of this invoice item. This appears on the invoice and helps identify what the charge is for. Examples include "Monthly subscription fee", "Setup charge", "Product: Widget Pro", or "Consulting hours". Clear descriptions help customers understand their invoices and reduce payment disputes and support inquiries.
Max length: 128
line_item
object
Detailed pricing information for a line item charge. Required when type is "line_item". Contains the unit value, quantity, and automatically calculated total. Use this for individual charges on an invoice, such as product prices, service fees, or usage charges. Hidden when type is not "line_item".
Required if:
type=line_item
qty
number (double)
The quantity or number of units for this line item. Multiplied by the value to calculate the total charge. For example, if value is 10.00 and qty is 3, the total would be 30.00. Defaults to 1 if not specified.
total
number (double)Read-only
The calculated total amount for this line item (value * qty), rounded to 2 decimal places. This field is read-only and automatically computed. Represents the final charge that will be applied to the invoice for this line item.
value
number (double)
The unit amount or rate for this line item. If value_units is "number", this is the price per unit. If value_units is "percentage", this is the percentage rate (e.g., 5.5 for 5.5%). The total charge is calculated as value * qty. Required for line items.
value_units
enum[string]
Specifies how the value should be interpreted. Set to "number" for fixed amounts (e.g., $10.00 per item) or "percentage" for percentage-based charges (e.g., 5% of a base amount). Determines how the line item total is calculated.
Values: percentage, number
line_number
integer (int64)
Numeric value that determines the display order of line items on the invoice. Lower numbers appear first. Use this to control the presentation order of charges, such as showing products before shipping, or grouping related items together. If not specified, items are ordered by creation time. Useful for ensuring consistent, professional invoice formatting.

Item Group Fields:

type
enum[string]
The type of invoice item. Must be either "line_item" (a single charge with amount and quantity) or "item_group" (a container for grouping multiple line items together). The type determines which fields are required and how the item is structured.
Values: line_item, item_group
description
string
Text description of this invoice item. This appears on the invoice and helps identify what the charge is for. Examples include "Monthly subscription fee", "Setup charge", "Product: Widget Pro", or "Consulting hours". Clear descriptions help customers understand their invoices and reduce payment disputes and support inquiries.
Max length: 128
item_group
object
Container for grouping multiple related line items together. Required when type is "item_group". Use item groups to organize charges on invoices for better readability and structure, such as grouping all products, services, or fees into separate sections. Hidden when type is not "item_group".
Required if:
type=item_group
array
List of line items that belong to this item group. Each item in this list must have type "line_item" and will be nested under this group for organizational purposes. Expanded by default when retrieving the item group. Use this to organize related charges together on an invoice (e.g., grouping all shipping charges or all product line items).
line_number
integer (int64)
Numeric value that determines the display order of line items on the invoice. Lower numbers appear first. Use this to control the presentation order of charges, such as showing products before shipping, or grouping related items together. If not specified, items are ordered by creation time. Useful for ensuring consistent, professional invoice formatting.

Invoice Status

status
enum[string]
The current status of this invoice. Possible values: "draft" (not yet published/sent), "open" (published and awaiting payment, same as unpaid), "unpaid" (published with no payments), "partially_paid" (some payment received but balance remains), "paid" (fully paid), or "closed" (manually closed/cancelled). Status transitions are restricted - for example, paid invoices cannot be modified.
Values: draft, open, unpaid, partially_paid, paid, closed, sync

Invoices transition from draft through open (transitional) to unpaid, partially_paid, or paid based on payment activity.

Invoice Totals

All totals are automatically calculated and read-only:

totals
object
Financial summary of this invoice, including subtotal, tax, total amounts, and payment status. All fields are read-only and automatically calculated based on the line items and payments associated with this invoice. Provides a quick overview of the invoice's financial state.
balance_due
number (double)Read-only
The remaining unpaid balance on this invoice (total - paid). Read-only field that represents the outstanding amount the payer still owes. When this reaches zero, the invoice is fully paid.
paid
number (double)Read-only
The total amount that has been successfully paid toward this invoice. Read-only field that updates as payments are received and allocated to this invoice. Use this to track how much has been collected.
subtotal
number (double)Read-only
The subtotal of all line items on this invoice before tax is applied. This is the sum of all line item amounts (value * qty for each item). Read-only field that is automatically calculated based on the invoice items. Represents the pre-tax total.
tax
number (double)Read-only
The total tax amount for this invoice. Calculated by applying tax rates to taxable line items. Read-only field that updates when line items or tax rates change. This amount is added to the subtotal to get the total amount due.
total
number (double)Read-only
The total amount due for this invoice (subtotal + tax). This is the full amount the payer owes. Read-only field that is automatically calculated from line items and tax. Represents the complete invoice amount before any payments are applied.

Next Steps

Manage payment collection and automate recurring billing


Collect Payment on Invoices

Accept payments with Paying Invoices via API or payment links for flexible customer payment options, set up Payment Portal with hosted payment pages for customer self-service, and configure Autopay Enrollment to enable automatic payments on invoice due dates.

Manage Invoice Workflow

Track invoice progress with Invoice Statuses to understand the complete invoice lifecycle from draft through paid, automate workflows with Webhook Events to receive real-time notifications for invoice status changes, and customize Invoice Presentment with branded PDFs and customer-facing invoice views.

Automate Recurring Billing

Set up recurring invoices with Billing Schedules for automated invoice generation on flexible frequencies, build subscription billing with Creating Schedules for monthly or annual recurring charges, and modify recurring charges with Updating Schedules to add or remove items from future invoices.


Related articles