### Install AbacatePay SDK using pip Source: https://github.com/abacatepay/abacatepay-python-sdk/blob/main/README.md Use this command to install the AbacatePay SDK via pip. ```bash pip install abacatepay ``` -------------------------------- ### Install Dependencies with Poetry Source: https://github.com/abacatepay/abacatepay-python-sdk/blob/main/CONTRIBUTING.md Install project dependencies using Poetry. Ensure Poetry is installed globally. ```bash poetry install ``` -------------------------------- ### Install Pre-commit Hooks Source: https://github.com/abacatepay/abacatepay-python-sdk/blob/main/CONTRIBUTING.md Install pre-commit hooks to maintain code quality during development. These hooks run automatically before each commit. ```bash poetry run pre-commit install ``` -------------------------------- ### Install with UV Source: https://github.com/abacatepay/abacatepay-python-sdk/blob/main/docs/templates/installation.md Use this command to add the AbacatePay SDK to your project if you are using UV for dependency management. ```bash uv add abacatepay ``` -------------------------------- ### Install with pip Source: https://github.com/abacatepay/abacatepay-python-sdk/blob/main/docs/templates/installation.md Use this command to install the AbacatePay SDK using pip. For Linux and macOS, you may need to use 'pip3'. ```bash # Ou pip3 para linux e macOS pip install abacatepay ``` -------------------------------- ### Install with Poetry Source: https://github.com/abacatepay/abacatepay-python-sdk/blob/main/docs/templates/installation.md Use this command to add the AbacatePay SDK to your project if you are using Poetry for dependency management. ```bash poetry add abacatepay ``` -------------------------------- ### Import AbacatePay SDK Source: https://github.com/abacatepay/abacatepay-python-sdk/blob/main/docs/tutorials/billing_flow.md Import the AbacatePay SDK and initialize the client with your API key. Keep your API key secure, preferably as an environment variable. ```python from abacatepay import AbacatePay client = AbacatePay("") # (1) ``` -------------------------------- ### Define Products using SDK Model Source: https://github.com/abacatepay/abacatepay-python-sdk/blob/main/docs/tutorials/billing_flow.md Alternatively, use the Product model provided by the SDK to define products. Prices must be specified in cents. ```python from abacatepay.products import Product products = [ Product( external_id="123", name="PC gamer", quantity=1, price=1600_00, description="PC gamer completo de última geração" ) ] ``` -------------------------------- ### Initialize AbacatePay Client Source: https://github.com/abacatepay/abacatepay-python-sdk/blob/main/README.md Import the SDK and initialize the client with your API key to begin using the AbacatePay services. ```python import abacatepay client = abacatepay.AbacatePay("") ``` -------------------------------- ### Create a Billing with Products Source: https://github.com/abacatepay/abacatepay-python-sdk/blob/main/README.md Create a new billing by providing a list of products, return URL, and completion URL. Products can be defined as Product objects or dictionaries. The billing URL is then printed. ```python from abacatepay.products import Product products = [ Product( external_id="123", name="Test Product", quantity=1, price=50_00, description="Example product" ), # or as dict { 'external_id': "321", 'name': "Product as dict", 'quantity': 1, 'price': 10_00, 'description': "Example using dict" } ] billing = client.billing.create( products=products, return_url="https://yourwebsite.com/return", completion_url="https://yourwebsite.com/complete" ) print(billing.data.url) ``` -------------------------------- ### Create a Customer Source: https://github.com/abacatepay/abacatepay-python-sdk/blob/main/README.md Create a new customer using CustomerMetadata object or a dictionary. The customer's ID is then printed. ```python from abacatepay.customers import CustomerMetadata customer = CustomerMetadata( # Its can also be only a dict email="customer@example.com", name="Customer Name", cellphone="(12) 3456-7890", tax_id="123-456-789-10" ) created_customer = client.customers.create(customer) print(created_customer.id) ``` -------------------------------- ### Client Initialization Source: https://context7.com/abacatepay/abacatepay-python-sdk/llms.txt Factory function that returns a sync or async client configured with a Bearer-token API key. ```APIDOC ## Client Initialization Factory function that returns a sync or async client configured with a Bearer-token API key. ```python import abacatepay # Synchronous client (default) client = abacatepay.AbacatePay("your_api_key_here") # Asynchronous client async_client = abacatepay.AbacatePay("your_api_key_here", async_mode=True) # Type-checked usage from abacatepay import AbacatePayClient, AbacatePayAsyncClient sync: AbacatePayClient = abacatepay.AbacatePay("key", async_mode=False) aio: AbacatePayAsyncClient = abacatepay.AbacatePay("key", async_mode=True) ``` ``` -------------------------------- ### Define Products for Billing Source: https://github.com/abacatepay/abacatepay-python-sdk/blob/main/docs/tutorials/billing_flow.md Create a list of products to include in the billing charge. Prices must be specified in cents. ```python products = [ { "external_id": "123", "name": "PC gamer", "quantity": 1, "price": 1600_00, # (1) "description": "PC gamer completo de última geração" } ] ``` -------------------------------- ### Create Billing for New Customer Source: https://github.com/abacatepay/abacatepay-python-sdk/blob/main/docs/tutorials/billing_flow.md Create a billing charge for a new customer. Provide customer details along with return and completion URLs, and frequency. If the customer already exists, they will not be recreated. ```python billing = client.billing.create( products=products, return_url="https://mysite.com/return", # (1) completion_url="https://mysite.com/completed",# (2) customer={ "name": "John Doe", "email": "john@email.com", "cellphone": "(21) 5032-2583", "tax_id": "123.456.789-10" # (4) }, frequency='ONE_TIME', # (5) ) print(billing.url) ``` -------------------------------- ### Create Product Input Model Source: https://context7.com/abacatepay/abacatepay-python-sdk/llms.txt Defines the input structure for a product, including external ID, name, quantity, and price. Price must be in cents and at least 100, quantity must be at least 1. ```python p = Product(external_id="sku-001", name="T-Shirt", quantity=2, price=4900) ``` -------------------------------- ### client.pixQrCode.create Source: https://context7.com/abacatepay/abacatepay-python-sdk/llms.txt Creates a static Pix QR Code for a given amount. Returns a PixQrCode object containing the brcode and brcode_base64. ```APIDOC ## `client.pixQrCode.create` — Generate a Pix QR Code Creates a static Pix QR Code for a given amount. Returns a `PixQrCode` object containing the `brcode` (copy-paste EMV string) and `brcode_base64` (PNG image as base64 data URI). ```python import abacatepay from abacatepay.customers.models import CustomerMetadata client = abacatepay.AbacatePay("your_api_key_here") qr = client.pixQrCode.create( amount=5000, # R$50.00 in cents expires_in=3600, # 1 hour description="Payment for order #1042", customer=CustomerMetadata( name="Lucas Oliveira", email="lucas@example.com", cellphone="(11) 94444-5555", tax_id="222.333.444-55", ), ) print(qr.id) # pix_char_xxxxxx print(qr.status) # PENDING print(qr.amount) # 5000 print(qr.brcode) # 00020101021226950014br.gov.bcb.pix... print(qr.brcode_base64) # data:image/png;base64,iVBORw0K... print(qr.expires_at) # 2025-03-25T21:50:20.772Z print(qr.platform_fee) # fee in cents # Serve the QR code image in a web app: ``` ``` -------------------------------- ### Create a Discount Coupon with AbacatePay Python SDK Source: https://context7.com/abacatepay/abacatepay-python-sdk/llms.txt Creates reusable discount coupons. Supports PERCENTAGE and FIXED discount types. Use max_redeems=-1 for unlimited redemptions. Note that fixed discounts are in cents. ```python import abacatepay from abacatepay.coupons.models import CouponIn client = abacatepay.AbacatePay("your_api_key_here") # --- Percentage discount --- coupon = client.coupons.create( code="SUMMER20", discount_kind="PERCENTAGE", discount=20, # 20% notes="20% off for summer campaign", max_redeems=100, # limited to 100 uses ) print(coupon.id) # coup_xxxx print(coupon.status) # ACTIVE print(coupon.discount_kind) # PERCENTAGE print(coupon.discount) # 20 print(coupon.redeems_count) # 0 print(coupon.max_redeems) # 100 print(coupon.dev_mode) # True / False # --- Fixed amount discount --- coupon2 = client.coupons.create( CouponIn( code="FIXED10", discount_kind="FIXED", discount=1000, # R$10.00 off (in cents) notes="R$10 flat discount", max_redeems=-1, # unlimited metadata={"campaign": "black_friday_2024"}, ) ) print(coupon2.code if hasattr(coupon2, "code") else coupon2.id) ``` -------------------------------- ### client.billing.create Source: https://context7.com/abacatepay/abacatepay-python-sdk/llms.txt Creates a payment billing page with one or more products, returning a URL the end-user can visit to complete the payment. Accepts `BillingIn`, a dict, or keyword arguments. Prices are expressed in cents (minimum 100 = R$1.00). ```APIDOC ## `client.billing.create` — Create a New Billing Creates a payment billing page with one or more products, returning a URL the end-user can visit to complete the payment. Accepts `BillingIn`, a dict, or keyword arguments. Prices are expressed in **cents** (minimum 100 = R$1.00). ```python import abacatepay from abacatepay.billings.models import BillingIn from abacatepay.customers.models import CustomerMetadata from abacatepay.products.models import Product from abacatepay.utils.exceptions import ForbiddenRequest, BadRequestError client = abacatepay.AbacatePay("your_api_key_here") # --- Option 1: keyword arguments --- billing = client.billing.create( products=[ Product( external_id="prod-001", name="Premium Plan", quantity=1, price=9900, # R$99.00 description="Monthly premium subscription", ), { "external_id": "prod-002", "name": "Setup Fee", "quantity": 1, "price": 5000, # R$50.00 }, ], return_url="https://myapp.com/checkout/cancel", completion_url="https://myapp.com/checkout/success", frequency="ONE_TIME", # or "MULTIPLE_PAYMENTS" methods=["PIX"], customer=CustomerMetadata( name="Maria Silva", email="maria@example.com", cellphone="(11) 98765-4321", tax_id="123.456.789-00", ), ) print(billing.url) # https://abacatepay.com/pay/bill_xxxx print(billing.id) # bill_abc123 print(billing.amount) # 14900 (total in cents) print(billing.status) # PENDING print(billing.dev_mode) # True (sandbox) / False (production) # --- Option 2: BillingIn model instance --- data = BillingIn( products=[Product(external_id="x1", name="Item", quantity=2, price=1500)], return_url="https://myapp.com/back", completion_url="https://myapp.com/done", customer_id="cust_AbCdEfGh", # reuse existing customer ) billing2 = client.billing.create(data) # --- Error handling --- try: billing3 = client.billing.create( products=[Product(external_id="e1", name="X", quantity=1, price=100)], return_url="https://myapp.com/back", completion_url="https://myapp.com/done", ) except ForbiddenRequest as e: print("Invalid API key:", e) except BadRequestError as e: print("Validation error:", e) ``` ``` -------------------------------- ### client.pixQrCode.simulate — Simulate a Pix Payment (Dev Mode) Source: https://context7.com/abacatepay/abacatepay-python-sdk/llms.txt Simulates a Pix payment for a QR Code in sandbox/dev mode. Useful for automated testing without real transactions. ```APIDOC ## `client.pixQrCode.simulate` — Simulate a Pix Payment (Dev Mode) ### Description Simulates a Pix payment for a QR Code in sandbox/dev mode. Useful for automated testing without real transactions. ### Method ```python client.pixQrCode.simulate(pix_id: str, metadata: dict = None) ``` ### Parameters #### Path Parameters - **pix_id** (str) - Required - The unique identifier of the Pix QR Code to simulate payment for. #### Query Parameters - **metadata** (dict) - Optional - Additional metadata to associate with the simulated payment. ### Request Example ```python import abacatepay client = abacatepay.AbacatePay("your_sandbox_api_key") # First create a QR code in dev mode qr = client.pixQrCode.create(amount=2500, description="Test payment") print(f"Created QR Code: {qr.id}, Status: {qr.status}") # PENDING # Simulate the payment paid_qr = client.pixQrCode.simulate(qr.id, metadata={"test_run": "ci_pipeline"}) print(f"After simulation: {paid_qr.status}") # PAID # Confirm via check result = client.pixQrCode.check(qr.id) print(f"Confirmed status: {result.status}") # PAID ``` ### Response #### Success Response (200) - **PixQrCode** (object) - The updated Pix QR Code object after simulation. - **id** (str) - The unique identifier of the Pix QR Code. - **status** (str) - The status of the Pix QR Code (e.g., PAID). ### Response Example ```json { "id": "pix_char_xxxxxx", "status": "PAID" } ``` ``` -------------------------------- ### Simulate Pix Payment in Dev Mode Source: https://context7.com/abacatepay/abacatepay-python-sdk/llms.txt Simulates a Pix payment for a QR Code in sandbox/dev mode. Useful for automated testing without real transactions. Requires creating a QR code first. ```python import abacatepay client = abacatepay.AbacatePay("your_sandbox_api_key") # First create a QR code in dev mode qr = client.pixQrCode.create(amount=2500, description="Test payment") print(f"Created QR Code: {qr.id}, Status: {qr.status}") # PENDING # Simulate the payment paid_qr = client.pixQrCode.simulate(qr.id, metadata={"test_run": "ci_pipeline"}) print(f"After simulation: {paid_qr.status}") # PAID # Confirm via check result = client.pixQrCode.check(qr.id) print(f"Confirmed status: {result.status}") # PAID ``` -------------------------------- ### Commit and Push Changes Source: https://github.com/abacatepay/abacatepay-python-sdk/blob/main/CONTRIBUTING.md Stage all changes, commit them with a descriptive message, and push the branch to your fork. ```bash git add . git commit -m "Add feature or fix: short description" git push origin feature-name ``` -------------------------------- ### Async Client Usage Source: https://context7.com/abacatepay/abacatepay-python-sdk/llms.txt Demonstrates how to use the AbacatePay SDK in asynchronous mode for non-blocking operations. ```APIDOC ## Async Client — All Operations with `async_mode=True` ### Description All four sub-clients (`billing`, `customers`, `coupons`, `pixQrCode`) have full async equivalents using `httpx`. Switch to async mode by passing `async_mode=True`. ### Method ```python client = abacatepay.AbacatePay(api_key: str, async_mode: bool = True) ``` ### Request Example ```python import asyncio import abacatepay from abacatepay.products.models import Product from abacatepay.customers.models import CustomerMetadata async def main(): client = abacatepay.AbacatePay("your_api_key_here", async_mode=True) # Create customer customer = await client.customers.create( CustomerMetadata( name="Async User", email="async@example.com", cellphone="(11) 90000-0000", tax_id="000.000.000-00", ) ) print(f"Customer: {customer.id}") # Create billing tied to customer billing = await client.billing.create( products=[Product(external_id="p1", name="Service", quantity=1, price=19900)], return_url="https://myapp.com/back", completion_url="https://myapp.com/done", customer_id=customer.id, ) print(f"Billing URL: {billing.url}") # Create Pix QR Code qr = await client.pixQrCode.create(amount=19900, description="Service payment") print(f"QR Code brcode: {qr.brcode[:40]}...") # List all concurrently billings, customers, coupons = await asyncio.gather( client.billing.list(), client.customers.list(), client.coupons.list(), ) print(f"Totals — Billings: {len(billings)}, Customers: {len(customers)}, Coupons: {len(coupons)}") asyncio.run(main()) ``` ``` -------------------------------- ### Create BillingIn Input Model Source: https://context7.com/abacatepay/abacatepay-python-sdk/llms.txt Defines the input structure for a billing, including a list of products, return and completion URLs, billing frequency, payment methods, and customer information. ```python b_in = BillingIn( products=[p], return_url="https://app.com/back", completion_url="https://app.com/done", frequency="ONE_TIME", # or "MULTIPLE_PAYMENTS" methods=["PIX"], customer=cm, ) ``` -------------------------------- ### Create CouponIn Input Model Source: https://context7.com/abacatepay/abacatepay-python-sdk/llms.txt Defines the input structure for a coupon, including its code, discount kind (percentage or fixed), discount amount, and maximum number of redemptions. ```python c_in = CouponIn(code="SAVE10", discount_kind="PERCENTAGE", discount=10, max_redeems=50) ``` -------------------------------- ### List All Coupons with AbacatePay Python SDK Source: https://context7.com/abacatepay/abacatepay-python-sdk/llms.txt Retrieves all coupons associated with the account. Returns an empty list if no coupons exist. The output format for discount varies based on discount_kind. ```python import abacatepay client = abacatepay.AbacatePay("your_api_key_here") coupons = client.coupons.list() for c in coupons: print( f"ID: {c.id} | " f"Status: {c.status} | " f"Discount: {c.discount}{'%' if c.discount_kind == 'PERCENTAGE' else ' cents'} | " f"Redeems: {c.redeems_count}/{c.max_redeems if c.max_redeems != -1 else '∞'}" ) # Filter active coupons active = [c for c in coupons if c.status == "ACTIVE"] ``` -------------------------------- ### Create a Customer with AbacatePay Python SDK Source: https://context7.com/abacatepay/abacatepay-python-sdk/llms.txt Registers a new customer using CustomerMetadata, a dictionary, or keyword arguments. Ensure all required fields are provided to avoid BadRequestError. ```python import abacatepay from abacatepay.customers.models import CustomerMetadata from abacatepay.utils.exceptions import BadRequestError client = abacatepay.AbacatePay("your_api_key_here") # --- Option 1: CustomerMetadata model --- customer = client.customers.create( CustomerMetadata( name="João Pereira", email="joao@example.com", cellphone="(21) 91234-5678", tax_id="987.654.321-00", # CPF or CNPJ ) ) print(customer.id) # cust_AbCdEfGh1234 print(customer.name) # João Pereira print(customer.email) # joao@example.com print(customer.tax_id) # 987.654.321-00 print(customer.cellphone) # (21) 91234-5678 # --- Option 2: dict --- customer2 = client.customers.create({ "name": "Ana Lima", "email": "ana@example.com", "cellphone": "(31) 99876-5432", "tax_id": "111.222.333-44", }) # --- Option 3: keyword arguments --- customer3 = client.customers.create( name="Pedro Costa", email="pedro@example.com", cellphone="(41) 91111-2222", tax_id="555.666.777-88", ) try: bad = client.customers.create(email="missing_fields@example.com") except BadRequestError as e: print("Missing required fields:", e) ``` -------------------------------- ### Create Billing for Existing Customer Source: https://github.com/abacatepay/abacatepay-python-sdk/blob/main/docs/tutorials/billing_flow.md Create a billing charge for a customer already registered in the system. Specify return and completion URLs, customer ID, and frequency. ```python billing = client.billing.create( products=products, return_url="https://mysite.com/return", # (1) completion_url="https://mysite.com/completed",# (2) customer_id='cust_1234', # (3) frequency='ONE_TIME', # (4) ) print(billing.url) ``` -------------------------------- ### client.coupons.create Source: https://context7.com/abacatepay/abacatepay-python-sdk/llms.txt Creates a reusable coupon code that can be applied to billings. Supports PERCENTAGE and FIXED discount types. max_redeems=-1 means unlimited redemptions. ```APIDOC ## `client.coupons.create` — Create a Discount Coupon Creates a reusable coupon code that can be applied to billings. Supports `PERCENTAGE` and `FIXED` discount types. `max_redeems=-1` means unlimited redemptions. ```python import abacatepay from abacatepay.coupons.models import CouponIn client = abacatepay.AbacatePay("your_api_key_here") # --- Percentage discount --- coupon = client.coupons.create( code="SUMMER20", discount_kind="PERCENTAGE", discount=20, # 20% notes="20% off for summer campaign", max_redeems=100, # limited to 100 uses ) print(coupon.id) # coup_xxxx print(coupon.status) # ACTIVE print(coupon.discount_kind) # PERCENTAGE print(coupon.discount) # 20 print(coupon.redeems_count) # 0 print(coupon.max_redeems) # 100 print(coupon.dev_mode) # True / False # --- Fixed amount discount --- coupon2 = client.coupons.create( CouponIn( code="FIXED10", discount_kind="FIXED", discount=1000, # R$10.00 off (in cents) notes="R$10 flat discount", max_redeems=-1, # unlimited metadata={"campaign": "black_friday_2024"}, ) ) print(coupon2.code if hasattr(coupon2, "code") else coupon2.id) ``` ``` -------------------------------- ### client.coupons.list Source: https://context7.com/abacatepay/abacatepay-python-sdk/llms.txt Returns all coupons for the account as a list of Coupon objects. Returns an empty list when no coupons exist. ```APIDOC ## `client.coupons.list` — List All Coupons Returns all coupons for the account as `list[Coupon]`. Returns an empty list when no coupons exist. ```python import abacatepay client = abacatepay.AbacatePay("your_api_key_here") coupons = client.coupons.list() for c in coupons: print( f"ID: {c.id} | " f"Status: {c.status} | " f"Discount: {c.discount}{'%' if c.discount_kind == 'PERCENTAGE' else ' cents'} | " f"Redeems: {c.redeems_count}/{c.max_redeems if c.max_redeems != -1 else '∞'}" ) # Filter active coupons active = [c for c in coupons if c.status == "ACTIVE"] ``` ``` -------------------------------- ### Initialize AbacatePay Client (Sync and Async) Source: https://context7.com/abacatepay/abacatepay-python-sdk/llms.txt Factory function to create synchronous or asynchronous clients using an API key. Supports type-checked usage with specific client types. ```python import abacatepay # Synchronous client (default) client = abacatepay.AbacatePay("your_api_key_here") # Asynchronous client async_client = abacatepay.AbacatePay("your_api_key_here", async_mode=True) # Type-checked usage from abacatepay import AbacatePayClient, AbacatePayAsyncClient sync: AbacatePayClient = abacatepay.AbacatePay("key", async_mode=False) aio: AbacatePayAsyncClient = abacatepay.AbacatePay("key", async_mode=True) ``` -------------------------------- ### Clone Repository Source: https://github.com/abacatepay/abacatepay-python-sdk/blob/main/CONTRIBUTING.md Clone your forked repository locally. Replace 'your-username' with your GitHub username. ```bash git clone https://github.com/your-username/abacatepay.git cd abacatepay ``` -------------------------------- ### Create a New Branch Source: https://github.com/abacatepay/abacatepay-python-sdk/blob/main/CONTRIBUTING.md Create a new branch for your feature or bug fix. Use a descriptive name for the branch. ```bash git checkout -b feature-name ``` -------------------------------- ### Create PixQrCodeIn Input Model Source: https://context7.com/abacatepay/abacatepay-python-sdk/llms.txt Defines the input structure for a Pix QR Code payment, including the amount, expiration time in seconds, and a description. ```python pix_in = PixQrCodeIn(amount=7500, expires_in=1800, description="Invoice #55") ``` -------------------------------- ### List All Customers with AbacatePay Python SDK Source: https://context7.com/abacatepay/abacatepay-python-sdk/llms.txt Retrieves all customers registered under the account. The result is a plain list of Customer objects. ```python import abacatepay client = abacatepay.AbacatePay("your_api_key_here") customers = client.customers.list() print(f"Total customers: {len(customers)}") for c in customers: print(f"{c.id} | {c.name} | {c.email}") # Look up a customer by email target = next((c for c in customers if c.email == "joao@example.com"), None) if target: print(f"Found: {target.id}") ``` -------------------------------- ### Generate a Pix QR Code with AbacatePay Python SDK Source: https://context7.com/abacatepay/abacatepay-python-sdk/llms.txt Creates a static Pix QR Code for a specified amount and duration. The response includes a 'brcode' for copy-pasting and 'brcode_base64' for image display. Note that the amount is in cents. ```python import abacatepay from abacatepay.customers.models import CustomerMetadata client = abacatepay.AbacatePay("your_api_key_here") qr = client.pixQrCode.create( amount=5000, # R$50.00 in cents expires_in=3600, # 1 hour description="Payment for order #1042", customer=CustomerMetadata( name="Lucas Oliveira", email="lucas@example.com", cellphone="(11) 94444-5555", tax_id="222.333.444-55", ), ) print(qr.id) # pix_char_xxxxxx print(qr.status) # PENDING print(qr.amount) # 5000 print(qr.brcode) # 00020101021226950014br.gov.bcb.pix... print(qr.brcode_base64) # data:image/png;base64,iVBORw0K... print(qr.expires_at) # 2025-03-25T21:50:20.772Z print(qr.platform_fee) # fee in cents # Serve the QR code image in a web app: ``` -------------------------------- ### client.customers.list Source: https://context7.com/abacatepay/abacatepay-python-sdk/llms.txt Returns all customers registered under the account as a plain list of Customer objects. ```APIDOC ## `client.customers.list` — List All Customers Returns all customers registered under the account as a plain `list[Customer]`. ```python import abacatepay client = abacatepay.AbacatePay("your_api_key_here") customers = client.customers.list() print(f"Total customers: {len(customers)}") for c in customers: print(f"{c.id} | {c.name} | {c.email}") # Look up a customer by email target = next((c for c in customers if c.email == "joao@example.com"), None) if target: print(f"Found: {target.id}") ``` ``` -------------------------------- ### Async Client Operations Source: https://context7.com/abacatepay/abacatepay-python-sdk/llms.txt Demonstrates using the AbacatePay SDK in asynchronous mode with `httpx`. All sub-clients support async operations. Requires `asyncio`. ```python import asyncio import abacatepay from abacatepay.products.models import Product from abacatepay.customers.models import CustomerMetadata async def main(): client = abacatepay.AbacatePay("your_api_key_here", async_mode=True) # Create customer customer = await client.customers.create( CustomerMetadata( name="Async User", email="async@example.com", cellphone="(11) 90000-0000", tax_id="000.000.000-00", ) ) print(f"Customer: {customer.id}") # Create billing tied to customer billing = await client.billing.create( products=[Product(external_id="p1", name="Service", quantity=1, price=19900)], return_url="https://myapp.com/back", completion_url="https://myapp.com/done", customer_id=customer.id, ) print(f"Billing URL: {billing.url}") # Create Pix QR Code qr = await client.pixQrCode.create(amount=19900, description="Service payment") print(f"QR Code brcode: {qr.brcode[:40]}...") # List all concurrently billings, customers, coupons = await asyncio.gather( client.billing.list(), client.customers.list(), client.coupons.list(), ) print(f"Totals — Billings: {len(billings)}, Customers: {len(customers)}, Coupons: {len(coupons)}") asyncio.run(main()) ``` -------------------------------- ### client.customers.create Source: https://context7.com/abacatepay/abacatepay-python-sdk/llms.txt Registers a new customer in AbacatePay. Accepts CustomerMetadata, a dict, or keyword arguments. Returns a Customer object with a platform-assigned ID. ```APIDOC ## `client.customers.create` — Create a Customer Registers a new customer in AbacatePay and returns a `Customer` object with a platform-assigned ID (`cust_*`). Accepts `CustomerMetadata`, a dict, or keyword arguments. ```python import abacatepay from abacatepay.customers.models import CustomerMetadata from abacatepay.utils.exceptions import BadRequestError client = abacatepay.AbacatePay("your_api_key_here") # --- Option 1: CustomerMetadata model --- customer = client.customers.create( CustomerMetadata( name="João Pereira", email="joao@example.com", cellphone="(21) 91234-5678", tax_id="987.654.321-00", # CPF or CNPJ ) ) print(customer.id) # cust_AbCdEfGh1234 print(customer.name) # João Pereira print(customer.email) # joao@example.com print(customer.tax_id) # 987.654.321-00 print(customer.cellphone) # (21) 91234-5678 # --- Option 2: dict --- customer2 = client.customers.create({ "name": "Ana Lima", "email": "ana@example.com", "cellphone": "(31) 99876-5432", "tax_id": "111.222.333-44", }) # --- Option 3: keyword arguments --- customer3 = client.customers.create( name="Pedro Costa", email="pedro@example.com", cellphone="(41) 91111-2222", tax_id="555.666.777-88", ) try: bad = client.customers.create(email="missing_fields@example.com") except BadRequestError as e: print("Missing required fields:", e) ``` ``` -------------------------------- ### Create CustomerMetadata Input Model Source: https://context7.com/abacatepay/abacatepay-python-sdk/llms.txt Defines the input structure for customer metadata, including name, email, cellphone, and tax ID. This can be embedded in billings. ```python cm = CustomerMetadata(name="Jane", email="jane@x.com", cellphone="(11) 9...", tax_id="000.000.000-00") ``` -------------------------------- ### Discount Kinds Constants Source: https://context7.com/abacatepay/abacatepay-python-sdk/llms.txt Defines the types of discounts available: PERCENTAGE or FIXED. ```python # DISCOUNT_KINDS = 'PERCENTAGE' | 'FIXED' ``` -------------------------------- ### Run Tests Source: https://github.com/abacatepay/abacatepay-python-sdk/blob/main/CONTRIBUTING.md Execute all project tests to ensure code integrity. This command also runs code style checks. ```bash poetry run task test ``` -------------------------------- ### Billing Methods Constants Source: https://context7.com/abacatepay/abacatepay-python-sdk/llms.txt Defines the supported billing methods. Currently only PIX is listed. ```python # BILLING_METHODS = 'PIX' ``` -------------------------------- ### Create New Billing with AbacatePay Source: https://context7.com/abacatepay/abacatepay-python-sdk/llms.txt Generates a payment billing page. Accepts product details, return/completion URLs, payment frequency, methods, and customer information. Prices are in cents. Supports keyword arguments or BillingIn model instances. Includes error handling for common request issues. ```python import abacatepay from abacatepay.billings.models import BillingIn from abacatepay.customers.models import CustomerMetadata from abacatepay.products.models import Product from abacatepay.utils.exceptions import ForbiddenRequest, BadRequestError client = abacatepay.AbacatePay("your_api_key_here") # --- Option 1: keyword arguments --- billing = client.billing.create( products=[ Product( external_id="prod-001", name="Premium Plan", quantity=1, price=9900, # R$99.00 description="Monthly premium subscription", ), { "external_id": "prod-002", "name": "Setup Fee", "quantity": 1, "price": 5000, # R$50.00 }, ], return_url="https://myapp.com/checkout/cancel", completion_url="https://myapp.com/checkout/success", frequency="ONE_TIME", # or "MULTIPLE_PAYMENTS" methods=["PIX"], customer=CustomerMetadata( name="Maria Silva", email="maria@example.com", cellphone="(11) 98765-4321", tax_id="123.456.789-00", ), ) print(billing.url) # https://abacatepay.com/pay/bill_xxxx print(billing.id) # bill_abc123 print(billing.amount) # 14900 (total in cents) print(billing.status) # PENDING print(billing.dev_mode) # True (sandbox) / False (production) # --- Option 2: BillingIn model instance --- data = BillingIn( products=[Product(external_id="x1", name="Item", quantity=2, price=1500)], return_url="https://myapp.com/back", completion_url="https://myapp.com/done", customer_id="cust_AbCdEfGh", # reuse existing customer ) billing2 = client.billing.create(data) # --- Error handling --- try: billing3 = client.billing.create( products=[Product(external_id="e1", name="X", quantity=1, price=100)], return_url="https://myapp.com/back", completion_url="https://myapp.com/done", ) except ForbiddenRequest as e: print("Invalid API key:", e) except BadRequestError as e: print("Validation error:", e) ``` -------------------------------- ### AbacatePay SDK Data Models Source: https://context7.com/abacatepay/abacatepay-python-sdk/llms.txt Reference for key Pydantic models used within the AbacatePay SDK for data structures. ```python from abacatepay.products.models import Product, ProductInline from abacatepay.customers.models import CustomerMetadata, Customer, CustomerInline from abacatepay.billings.models import BillingIn, Billing, BillingList, BillingMetadata from abacatepay.coupons.models import CouponIn, Coupon from abacatepay.pixQrCode.models import PixQrCodeIn, PixQrCode, PixStatus ``` -------------------------------- ### Format Code Source: https://github.com/abacatepay/abacatepay-python-sdk/blob/main/CONTRIBUTING.md Manually fix code formatting issues using the provided task. This command uses Ruff for formatting. ```bash poetry run task fmt ``` -------------------------------- ### List All Billings Source: https://github.com/abacatepay/abacatepay-python-sdk/blob/main/README.md Retrieve a list of all billings and print their IDs and statuses. The total count of billings is also printed. ```python billings = client.billing.list() for billing in billings: print(billing.id, billing.status) print(len(billings)) ``` -------------------------------- ### client.billing.list Source: https://context7.com/abacatepay/abacatepay-python-sdk/llms.txt Retrieves all billings associated with the API key. Returns a `BillingList` object that supports `len()` and direct iteration over `Billing` instances. ```APIDOC ## `client.billing.list` — List All Billings Retrieves all billings associated with the API key. Returns a `BillingList` object that supports `len()` and direct iteration over `Billing` instances. ```python import abacatepay client = abacatepay.AbacatePay("your_api_key_here") billings = client.billing.list() print(f"Total billings: {len(billings)}") for billing in billings: print( f"ID: {billing.id} | " f"Status: {billing.status} | " # PENDING, PAID, EXPIRED, CANCELLED, REFUNDED, ACTIVE f"Amount: R${billing.amount / 100:.2f} | " f"URL: {billing.url} | " f"Created: {billing.created_at}" ) # Filter by status paid = [b for b in billings if b.status == "PAID"] print(f"Paid billings: {len(paid)}") ``` ``` -------------------------------- ### Error Handling Reference Source: https://context7.com/abacatepay/abacatepay-python-sdk/llms.txt Reference for API errors and exceptions raised by the AbacatePay SDK. ```APIDOC ## Error Handling Reference ### Description All exceptions inherit from `APIError`. HTTP errors are raised automatically by the internal `raise_for_status` helper. ### Exception Hierarchy - `APIError` (Base class for all AbacatePay API errors) - `APIStatusError` (Error related to HTTP status codes) - `ForbiddenRequest` (403 — wrong API key) - `UnauthorizedRequest` (401 — insufficient permissions) - `BadRequestError` (400 — malformed request / validation failure) - `NotFoundError` (404 — resource not found) - `InternalServerError` (500 — server-side error) - `APIConnectionError` (Error related to network connection issues) - `APITimeoutError` (Error related to request timeouts) ### Request Example ```python import abacatepay from abacatepay.utils.exceptions import ( APIError, APIStatusError, APIConnectionError, APITimeoutError, ForbiddenRequest, UnauthorizedRequest, BadRequestError, NotFoundError, InternalServerError, ) client = abacatepay.AbacatePay("your_api_key_here") try: billings = client.billing.list() except ForbiddenRequest as e: print(f"Auth error: {e}") # "Means that the request was unsuccessful due to a forbidden request. Maybe your API key is wrong?" except UnauthorizedRequest as e: print(f"Permission error: {e}") except BadRequestError as e: print(f"Bad request: {e}") # includes JSON error body except NotFoundError as e: print(f"Not found: {e}") # includes requested URL except InternalServerError as e: print(f"Server error: {e}") except APITimeoutError as e: print(f"Timeout: {e}") except APIConnectionError as e: print(f"Connection failed: {e}") except APIError as e: print(f"Generic API error: {e}") ``` ``` -------------------------------- ### Check Pix QR Code Status with Polling Source: https://context7.com/abacatepay/abacatepay-python-sdk/llms.txt Polls the payment status of a Pix QR Code. Use this in a loop to monitor status changes. Possible statuses include PENDING, PAID, EXPIRED, CANCELLED, REFUNDED. ```python import abacatepay import time client = abacatepay.AbacatePay("your_api_key_here") pix_id = "pix_char_xxxxxx" # Simple polling loop for _ in range(10): status = client.pixQrCode.check(pix_id) print(f"Status: {status.status} | Expires at: {status.expires_at}") # Possible statuses: PENDING, PAID, EXPIRED, CANCELLED, REFUNDED if status.status == "PAID": print("Payment confirmed!") break elif status.status in ("EXPIRED", "CANCELLED"): print("Payment no longer valid.") break time.sleep(5) ``` -------------------------------- ### Billing Status Constants Source: https://context7.com/abacatepay/abacatepay-python-sdk/llms.txt Defines the possible statuses for a billing: PENDING, EXPIRED, CANCELLED, PAID, REFUNDED, ACTIVE. ```python # BILLING_STATUS = 'PENDING' | 'EXPIRED' | 'CANCELLED' | 'PAID' | 'REFUNDED' | 'ACTIVE' ``` -------------------------------- ### List All Billings with AbacatePay Source: https://context7.com/abacatepay/abacatepay-python-sdk/llms.txt Retrieves all billings associated with the API key. The result is a BillingList object that can be iterated over to access individual Billing instances. Supports filtering by status. ```python import abacatepay client = abacatepay.AbacatePay("your_api_key_here") billings = client.billing.list() print(f"Total billings: {len(billings)}") for billing in billings: print( f"ID: {billing.id} | " f"Status: {billing.status} | " # PENDING, PAID, EXPIRED, CANCELLED, REFUNDED, ACTIVE f"Amount: R${billing.amount / 100:.2f} | " f"URL: {billing.url} | " f"Created: {billing.created_at}" ) # Filter by status paid = [b for b in billings if b.status == "PAID"] print(f"Paid billings: {len(paid)}") ``` -------------------------------- ### Error Handling with APIError Subclasses Source: https://context7.com/abacatepay/abacatepay-python-sdk/llms.txt Demonstrates how to catch specific AbacatePay API errors. All exceptions inherit from `APIError`. Use specific subclasses for targeted error handling. ```python import abacatepay from abacatepay.utils.exceptions import ( APIError, APIStatusError, APIConnectionError, APITimeoutError, ForbiddenRequest, # 403 — wrong API key UnauthorizedRequest, # 401 — insufficient permissions BadRequestError, # 400 — malformed request / validation failure NotFoundError, # 404 — resource not found InternalServerError, # 500 — server-side error ) client = abacatepay.AbacatePay("your_api_key_here") try: billings = client.billing.list() except ForbiddenRequest as e: print(f"Auth error: {e}") # "Means that the request was unsuccessful due to a forbidden request. Maybe your API key is wrong?" except UnauthorizedRequest as e: print(f"Permission error: {e}") except BadRequestError as e: print(f"Bad request: {e}") # includes JSON error body except NotFoundError as e: print(f"Not found: {e}") # includes requested URL except InternalServerError as e: print(f"Server error: {e}") except APITimeoutError as e: print(f"Timeout: {e}") except APIConnectionError as e: print(f"Connection failed: {e}") except APIError as e: print(f"Generic API error: {e}") ``` -------------------------------- ### Billing Kinds Constants Source: https://context7.com/abacatepay/abacatepay-python-sdk/llms.txt Defines the possible billing kinds: ONE_TIME or MULTIPLE_PAYMENTS. ```python # BILLING_KINDS = 'ONE_TIME' | 'MULTIPLE_PAYMENTS' ``` -------------------------------- ### Pix QR Code Status Constants Source: https://context7.com/abacatepay/abacatepay-python-sdk/llms.txt Defines the possible statuses for a Pix QR Code payment: PENDING, EXPIRED, CANCELLED, PAID, REFUNDED. ```python # PIX_QR_CODE_STATUS = 'PENDING' | 'EXPIRED' | 'CANCELLED' | 'PAID' | 'REFUNDED' ```