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
- Install Python 3 to run the example without third-party packages.
- 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.
- Prepare the hosted invoice page URL for the required
urlfield. The example prompts for this URL and your API key rather than storing credentials in the script. - Save the following code as
create_schedule.pyand runpython3 create_schedule.py. It creates a monthly schedule starting tomorrow in UTC, leaves email notifications enabled, and omitspayment_method_idso 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
| Field | Type | Required | Default and constraints |
|---|---|---|---|
url | string | Yes | Hosted invoice page URL; no default is documented. |
total | number | Yes | Invoice total; no default or numeric bounds are documented. |
rule | string | No | iCalendar RRule (a text rule describing when a schedule runs). When you supply DTSTART, use a future date; no default rule is documented. |
customer_id | string | No | ID of the customer to associate with the schedule; no default is documented. |
payment_method_id | string | No | ID of a saved payment method for autopay (automatic payment attempts when invoices are generated). Omit it for manual payment. |
email_notification | boolean | No | Defaults to true; set to false only if you want to disable invoice emails. |
Optional: Scheduling capabilities
Key Features
Creates a schedule to generate invoices at specified intervals using recurrence rules following the iCalendar RRule specification.
Include payment_method_id to attempt payment automatically with a saved payment method when an invoice is generated.
Automatically recalculates next_run_at (the next scheduled run time) after each generated invoice or payment.
Enables merchants to include metadata like tax, subtotal, and lineItems for comprehensive invoice detail. Optionally hide line items from customer-facing emails using hideCustomerLineItems.
Allows merchants to control email notifications for generated invoices with customizable settings.
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=1With 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:
DTSTARTmust be a future date; past dates are invalid and will result in a 422 validation error.
Configure automatic payment processing for generated invoices:
- With Autopay: Include
payment_method_idto attempt payments automatically when invoices are generated - Manual Payment: Omit
payment_method_idto allow customers to manually enter payment details when paying
Use autopay for recurring billing when customers have authorized use of a saved payment method. payment_method_id identifies that saved method; it is not a card number.
Use IDs from your own account, not sample IDs. For an existing invoice with a saved payment method, the Get an Invoice response includes payment_method.id and customer.id. For example, "1789f7da-eb8e-4b83-9b12-498b6ee1c947" illustrates the payment method ID format; do not send this documentation value as your customer's ID.
Control how customers are notified about new invoices:
- Default Behavior:
email_notificationis set totrueby default - Disable Notifications: Set
email_notification=falseto disable automatic emails - Enhanced Emails: Populate
metafields likesubtotal,tax, andlineItemsto include detailed information in notifications - Hide Line Items: Set
meta.hideCustomerLineItems=trueto suppress line item details from customer-facing emails and receipts. The line items remain stored on the invoice and are passed to the payment gateway, but are excluded from email notifications sent to customers.
Manage schedule lifecycle with pause and resume functionality:
To pause a schedule:
- Use
PUT /invoice/schedule/{id}. Here,{id}is API path notation, not a literal value to send. Replace it with your schedule ID. For an invoice generated by the schedule, use itsschedule_idfrom the Get All Invoices response, not its invoiceid. For example, a schedule ID has the form"e70c126c-f7b7-4673-a129-5b650f00f84a"; use your own account's value without quotes in the URL path. - Set
active=falseto pause invoice generation. This clearsnext_run_at.
To resume a schedule:
- Update the same schedule with
active=true. - Provide a future
DTSTARTdate in the recurrence rule.
The schedule resumes generating invoices from the new start date.
Response Structure
| Code | Response | Reason |
|---|---|---|
| 201 | Schedule Created | The schedule was successfully created. |
| 400 | Bad Request | Invalid parameters or missing required fields. |
| 422 | Validation Error | DTSTART is in the past, or recurrence rules are incorrectly formatted. |
| 500 | Internal Server Error | Unexpected 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.
201Schedule successfully created.
400Bad Request - Invalid parameters or missing required fields.
422Validation Error - DTSTART is in the past, recurrence rules are incorrectly formatted, or invalid field values.
500Internal Server Error.
