Services API
Payment Service
- class fastapi_payments.services.payment_service.PaymentService(config, event_publisher, db_session=None)[source]
Bases:
objectService for payment operations.
Methods:
__init__(config, event_publisher[, db_session])Initialize the payment service.
set_db_session(session)Set the database session.
get_provider([provider_name])Get a payment provider instance.
create_customer(email[, name, meta_info, ...])Create a customer.
ensure_provider_customer(customer_id, provider)Ensure the customer is registered with the requested provider.
get_customer(customer_id)Get customer details.
list_customers(*[, limit, offset, search])List customers stored in the service database.
update_customer(customer_id, **kwargs)Update customer details.
create_payment_method(customer_id, ...[, ...])Create a payment method for a customer.
create_setup_intent(customer_id[, provider, ...])Create a SetupIntent (or provider equivalent) for the given customer so a client-side flow (3DS) can be completed before saving a payment method.
list_payment_methods(customer_id[, provider])List payment methods for a customer.
update_payment_method(customer_id, method_id)Update a stored payment method's attributes.
delete_payment_method(customer_id, method_id)Delete (detach) a stored payment method both in provider (if supported) and DB.
set_default_payment_method(customer_id, ...)Mark a stored payment method as the default for the customer.
create_product(name[, description, ...])Create a new product.
list_products(*[, limit, offset])Return products stored in the local database.
create_plan(product_id, name, pricing_model, ...)Create a plan for a product.
list_plans(*[, product_id, limit, offset])Return plans, optionally filtered by product.
create_subscription(customer_id, plan_id[, ...])Create a subscription for a customer.
get_subscription(subscription_id)Get subscription details.
list_subscriptions(*[, customer_id, status, ...])Return subscriptions filtered by optional criteria.
cancel_subscription(subscription_id[, ...])Cancel a subscription.
process_payment(customer_id, amount, currency)Process a one-time payment.
sync_resources([resources, provider, ...])Synchronize local DB state with provider(s).
create_sync_job([resources, provider, filters])Create a SyncJob record and return its basic details.
execute_sync_job(job_id)Run sync_resources for a previously created job and persist results.
refund_payment(payment_id[, amount])Refund a payment, partially or fully.
list_payments(*[, customer_id, status, ...])Return payments filtered by optional criteria.
record_usage(subscription_id, quantity[, ...])Record usage for a subscription.
handle_webhook(provider, payload[, signature])Handle webhooks from payment providers.
- Parameters:
config (PaymentConfig)
event_publisher (PaymentEventPublisher)
- __init__(config, event_publisher, db_session=None)[source]
Initialize the payment service.
- Parameters:
config (
PaymentConfig) – Payment configurationevent_publisher (
PaymentEventPublisher) – Event publisher for notificationsdb_session – Database session
- set_db_session(session)[source]
Set the database session.
- Parameters:
session (
AsyncSession) – SQLAlchemy AsyncSession
- async create_customer(email, name=None, meta_info=None, provider=None, address=None)[source]
Create a customer.
- Parameters:
- Return type:
- Returns:
Customer data dictionary
- async ensure_provider_customer(customer_id, provider)[source]
Ensure the customer is registered with the requested provider.
- async list_customers(*, limit=50, offset=0, search=None)[source]
List customers stored in the service database.
- async create_payment_method(customer_id, payment_details, provider=None)[source]
Create a payment method for a customer.
- async create_setup_intent(customer_id, provider=None, usage=None)[source]
Create a SetupIntent (or provider equivalent) for the given customer so a client-side flow (3DS) can be completed before saving a payment method.
Returns a dict that includes id and client_secret keys when supported by the provider.
- async list_payment_methods(customer_id, provider=None)[source]
List payment methods for a customer.
- async update_payment_method(customer_id, method_id, provider=None, **fields)[source]
Update a stored payment method’s attributes.
Supported updates include setting is_default, or meta_info.
- async delete_payment_method(customer_id, method_id, provider=None)[source]
Delete (detach) a stored payment method both in provider (if supported) and DB.
- async set_default_payment_method(customer_id, method_id, provider=None)[source]
Mark a stored payment method as the default for the customer.
Updates both DB (via repository.set_default) and attempts to update the provider’s customer default payment settings where supported.
- async create_product(name, description=None, provider=None, meta_info=None)[source]
Create a new product.
- async create_plan(product_id, name, pricing_model, amount, description=None, currency='USD', billing_interval=None, billing_interval_count=None, trial_period_days=None, provider=None, meta_info=None)[source]
Create a plan for a product.
- Parameters:
product_id (
str) – Product IDname (
str) – Plan namepricing_model (
str) – Pricing model (subscription, usage_based, etc.)amount (
float) – Base amountcurrency (
str) – Currency codebilling_interval (
Optional[str]) – Billing interval (day, week, month, year)billing_interval_count (
Optional[int]) – Number of intervals between billingstrial_period_days (
Optional[int]) – Optional trial period in daysmeta_info (
Optional[Dict[str,Any]]) – Optional plan meta_info
- Return type:
- Returns:
Created plan data
- async list_plans(*, product_id=None, limit=50, offset=0)[source]
Return plans, optionally filtered by product.
- async create_subscription(customer_id, plan_id, quantity=1, trial_period_days=None, meta_info=None)[source]
Create a subscription for a customer.
- Parameters:
- Return type:
- Returns:
Created subscription data
- async list_subscriptions(*, customer_id=None, status=None, limit=50, offset=0)[source]
Return subscriptions filtered by optional criteria.
- async cancel_subscription(subscription_id, cancel_at_period_end=True)[source]
Cancel a subscription.
- async process_payment(customer_id, amount, currency, payment_method_id=None, description=None, meta_info=None, mandate_id=None, provider=None)[source]
Process a one-time payment.
- Parameters:
- Return type:
- Returns:
Payment data
- async sync_resources(resources=None, provider=None, filters=None, limit=100, offset=0)[source]
Synchronize local DB state with provider(s).
This is best-effort: for each requested resource we attempt to fetch authoritative data from the configured provider(s) and update local rows where possible. If a provider does not implement the expected retrieval method for a resource, the resource is skipped for that provider.
- Parameters:
resources (
Optional[List[str]]) – list of resource names to sync (customers, products, plans, payments, subscriptions, payment_methods). If None, all supported resources are synced.provider (
Optional[str]) – optional provider name to limit sync to one provider.filters (
Optional[Dict[str,Any]]) – resource-specific filters e.g. {‘customer_id’: ‘…’}limit/offset – pagination for resource listing.
limit (int)
offset (int)
- Return type:
- Returns:
A dict summarizing how many items were examined/updated and any errors encountered for each resource.
- async create_sync_job(resources=None, provider=None, filters=None)[source]
Create a SyncJob record and return its basic details.
Actual work is performed by execute_sync_job which is expected to be scheduled as a background task by the API layer.
- async execute_sync_job(job_id)[source]
Run sync_resources for a previously created job and persist results.
This method will set job status to ‘running’, invoke sync_resources, and finally store the result and mark job ‘completed’ or ‘failed’.
- Parameters:
job_id (str)
- async list_payments(*, customer_id=None, status=None, limit=50, offset=0)[source]
Return payments filtered by optional criteria.