Create a Scheduled Invoice

Create invoice schedules with a runnable Python example, recurrence rules, optional autopay, and email settings.

Use POST /invoice/schedule/ in your API integration to generate invoices on a recurring or one-time schedule. This reference is for developers; Cards and Tabs organize the documentation, not controls in the Stax Pay Dashboard.

Create a monthly invoice schedule

  1. Install Python 3 to run the example without third-party packages.
  2. Select your sandbox (a test environment) from the merchant switcher in the upper-right corner of Stax Pay, then copy your merchant API key from Stax Pay > Apps > API Keys. Use the sandbox key to test without creating a production billing schedule.
  3. Prepare the hosted invoice page URL for the required url field. The example prompts for this URL and your API key rather than storing credentials in the script.
  4. Save the following code as create_schedule.py and run python3 create_schedule.py. It creates a monthly schedule starting tomorrow in UTC, leaves email notifications enabled, and omits payment_method_id so customers pay manually.
import getpass
import json
import sys
from datetime import datetime, timedelta, timezone
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen

api_key = getpass.getpass("Sandbox merchant API key: ").strip()
invoice_url = input("Hosted invoice page URL: ").strip()
if not api_key or not invoice_url:
    sys.exit("Provide both an API key and a hosted invoice page URL.")

# Compute a future start so the example does not expire as fixed dates do.
start = (datetime.now(timezone.utc) + timedelta(days=1)).strftime(
    "%Y%m%dT%H%M%SZ"
)
payload = {
    "url": invoice_url,
    "total": 25,
    "rule": f"DTSTART={start};FREQ=MONTHLY",
    "email_notification": True,
}
request = Request(
    "https://apiprod.fattlabs.com/invoice/schedule/",
    data=json.dumps(payload).encode("utf-8"),
    headers={
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json",
        "Accept": "application/json",
    },
    method="POST",
)

try:
    with urlopen(request, timeout=30) as response:
        status = response.status
        body = response.read().decode("utf-8", errors="replace")
except HTTPError as error:
    detail = error.read().decode("utf-8", errors="replace")
    guidance = {
        400: "Check required fields and parameter values.",
        422: "Check that DTSTART is in the future and the rule is valid.",
        500: "A server error occurred; verify the outcome before retrying.",
    }.get(error.code, "Check the response details and your credentials.")
    sys.exit(f"HTTP {error.code}: {guidance}\n{detail}")
except (URLError, TimeoutError, OSError) as error:
    sys.exit(f"Request failed: {error}. Verify the outcome before retrying.")

if status != 201:
    sys.exit(f"Unexpected HTTP {status}; verify the outcome.\n{body}")

print("HTTP 201: Schedule created.")
if body.strip():
    print(body)
else:
    print("No response body returned.")

Expected success output begins with:

HTTP 201: Schedule created.

The script also prints the response body if present. The endpoint specification does not define a success response body, so use HTTP 201 to confirm creation rather than assuming specific JSON fields. A created schedule generates invoices at its configured times; creation does not mean an invoice has already been paid.

Request fields used in this flow

FieldTypeRequiredDefault and constraints
urlstringYesHosted invoice page URL; no default is documented.
totalnumberYesInvoice total; no default or numeric bounds are documented.
rulestringNoiCalendar RRule (a text rule describing when a schedule runs). When you supply DTSTART, use a future date; no default rule is documented.
customer_idstringNoID of the customer to associate with the schedule; no default is documented.
payment_method_idstringNoID of a saved payment method for autopay (automatic payment attempts when invoices are generated). Omit it for manual payment.
email_notificationbooleanNoDefaults to true; set to false only if you want to disable invoice emails.

Optional: Scheduling capabilities

Key Features

Flexible Scheduling

Creates a schedule to generate invoices at specified intervals using recurrence rules following the iCalendar RRule specification.

Autopay Support

Include payment_method_id to attempt payment automatically with a saved payment method when an invoice is generated.

Smart Recalculation

Automatically recalculates next_run_at (the next scheduled run time) after each generated invoice or payment.

Enhanced Details

Enables merchants to include metadata like tax, subtotal, and lineItems for comprehensive invoice detail. Optionally hide line items from customer-facing emails using hideCustomerLineItems.

Email Control

Allows merchants to control email notifications for generated invoices with customizable settings.

Pause & Resume

Full control over schedule lifecycle with the ability to pause and resume billing as needed.

Optional: Configure scheduling and notifications

The rule parameter follows the iCalendar RRule specification. Here are common examples:

Monthly recurrence: The runnable example above computes a future DTSTART and appends FREQ=MONTHLY.

Weekly recurrence until a specific date: Use the following as the rule value, adjusting both dates before sending the request. This is a parameter value, not a standalone command:

DTSTART=20271201T120000Z;FREQ=WEEKLY;UNTIL=20271231T000000Z;INTERVAL=1

With these dates, the rule describes weekly runs beginning December 1, 2027, at 12:00 UTC and ending by December 31, 2027, at 00:00 UTC.

Important: DTSTART must be a future date; past dates are invalid and will result in a 422 validation error.

Response Structure

CodeResponseReason
201Schedule CreatedThe schedule was successfully created.
400Bad RequestInvalid parameters or missing required fields.
422Validation ErrorDTSTART is in the past, or recurrence rules are incorrectly formatted.
500Internal Server ErrorUnexpected server error.

Requirements and recommendations

Requirements and optional recommendations

Required request fields: Include url and total in your request.

Required for a valid start date: Set DTSTART to a future date when supplying a recurrence rule. Past dates trigger a 422 validation error.

Optional: Metadata and emails: Populate meta fields such as subtotal, tax, and lineItems if you want these details in notifications and invoices. Set the boolean meta.hideCustomerLineItems to true only if you want to hide line items from customer-facing emails and receipts while retaining them on the invoice record.

Automatic Recalculation: The system automatically recalculates the next_run_at time each time an invoice is generated or paid, ensuring accurate scheduling.

Audit trail: Each generated invoice includes timestamps and payment details for reporting. These records support compliance efforts; they do not guarantee compliance. Consult your legal team regarding specific requirements.

Invoice Lifecycle: When paused, schedules will not generate invoices until resumed with a valid future DTSTART. Plan pause periods accordingly to avoid billing gaps.

Body Params
string
required

The URL for the hosted invoice page.

number
required

The total amount for the invoice.

string

The iCalendar RRule recurrence rule string (e.g., DTSTART=20231101T120000Z;FREQ=MONTHLY;COUNT=12).

string

The ID of the customer to associate with the schedule.

string

The ID of the payment method for autopay. If omitted, the customer will pay manually.

boolean
Defaults to true

Whether to send email notifications when invoices are generated. Defaults to true.

files
array of strings

Array of file IDs to attach to the schedule.

files
meta
object

Metadata for the invoice, including line items, tax, and other details.

Responses
201

Schedule successfully created.

400

Bad Request - Invalid parameters or missing required fields.

422

Validation Error - DTSTART is in the past, recurrence rules are incorrectly formatted, or invalid field values.

500

Internal Server Error.

Language
Credentials
Bearer
JWT
LoadingLoading…
Response
Click Try It! to start a request and see the response here!