API SDK DOCUMENTATION
PaymentFlow SDK Documentation (Python)
Installation
Install via pip:
pip install paymentflow-sdk
Requirements:
•Python 3.7 or higher
•Library request (installed automatically)
Quick Start
from paymentFlow import PaymentFlowClient
# Initialise client
payment = client.payments.create(
amount=2500, # Amount in cents ($25.00)
currency = ‘ USD ‘,
customer_email= ‘customer@example.com ‘,
description= ‘Order #12345 ‘
)
print (f “ Payment ID: {payment . ID} “ )
print (f “ Status: {payment . status} “)
Authentication
The SDK requires an API key for authentication. Obtain your API key from the PaymentFlow dashboard under settings → API Keys
Initialise the client:
from paymentflow import PaymentFlowClient
client = PaymentFlowClient (
api_keys= ‘pk_live_abc123… ‘ ,
environment= ‘ production ‘ # or ‘sandbox’ for testing
)
Environmental Options:
•production - Live transactions
•sandbox - Test mode with fake payment processing
API key types:
•Publishable keys (pk_live_…or pk_test_…)
•Safe for clients side code.
•Secret keys (sk_live_… or sk_test_…) - This is the server-side only and can never be exposed publicly.
Core Concepts
Payments
A payment represents a single transaction. Payment statuses includes:
•Pending: Created but not yet processed
•Processing: Payment provider is handling transaction
•Succeeded: Payment completed successfully
•Failed: Payment declined or encountered error
•Cancelled: Manually cancelled before processing
Customers: Customers object store payment information for repeat transactions
Refunds: Refunded funds to customers might either be partial or full.
API Reference
Payments
Create Payment
payment = client . payment . create(
amount=5000
currency= ‘USD’ ,
customer_email = ‘user@example .com ‘,
description= ‘ Product purchase ‘,
metadata= {‘ order_id ‘ : ‘12345 ‘ } ,
idempotency_key= ‘unique_key_123 ‘
)
Parameters:
•Amount (integer required) - Payment amount in smallest currency unit. (cents for USD)
•Currency (string required) - Three-letter ISO currency code (USD, EUR, GBP,etc.)
•Customer email (optional string) - Customer email for both the receipts and records.
•Description (optional string) - Internal description of payment purposes.
•Metadata (optional dictionary) - Custom key-value pairs (max 50 keys and 500 chars per value)
•Idempotency_key (optional string) - Unique string to prevent duplicate charges.
Returns: Payment object
Raises:
•PaymentFlowError - General API errors
•AuthenticationError - Invalid API key
•ValidationError - Invalid parameters
Retrieved Payment
payment = client . payments . retrieve ( ‘ pay_abc123 ‘)
Parameters:
•payment_id (string required) - ID of payment required for retrieval.
Returns: Payment object
List Payments
payments = client . payment . list(
limit=25,
starting_after= ‘pay_abc123 ‘,
customer_email= ‘ user@example.com ‘
)
for payment in payments . data
print (f “ (payment . id) : {payment.amount} {payment.currency} “ )
Parameters:
•Limit (integer are optional) - Number of results (1-100, default 10)
•starting_after (optional string) - Cursor for pagination
•customer_email (optional string) - Filter by customer email
•status (optional string) - Filter by status (pending,succeeded,failed)
Returns: Paginated list of payment benefits
Cancel Payment
payment = client.payments.cancel (‘pay_abc123’)
Refunds
Create Refunds
refund = client , refunds . create(
payment_id= ‘pay_abc123 ‘ ,
amount = 2500 ,
reason = ‘customer_request ‘
)
Parameters:
•payment_id (string required) - ID of your refunded payment
•amount (optional integer) - Refunded amount (omit for full refund)
•reason (optional string) - Reason code: customer_request, fraudulent duplicates.
•metadata (optional dictionary) - Custom key-value data.
Returns: Refunds object
Constraints:
•Cannot refund more than original amount payed.
•Cannot refund either failed or cancelled payments
•Refunds are typically processed within 5-10 days.
Retrieve Refund
refund = client.refunds.retrieve (‘ref_abc123 ‘ )
Parameters:
•refund_id (required string) - ID of refund to retrieve
Returns: Refund object
Customers
Create Customer
customer = client . customer . create (
email = ‘ customer@example . com ‘ ,
name= ‘ Jane Doe ‘,
metadata= [ ‘ user_id ‘ : ‘67890’ )
)
Parameters:
•email (string required) - customer email address
•name (optional string) - customer full name
•phone (optional string) - customer phone number
•metadata (optional dictionary) - custom key-value data
Returns: Customer object
Retrieve Customer
customer=client.customers.retrieve(‘cus_abc123’)
Parameters:
•customer_id (required string) - ID of customer to retrieve
Returns: Customer object
Update Customer
customer = client . customer . update (
‘cus_abc123’ ,
email = ‘newemail@example.com ‘,
metadata=(‘user_id ‘: ‘67890’,’vip’ : ‘true’)
)
Parameters:
•customer_id (required string) - ID of customer needed for update
•email (optional string) - New email address
•name (optional string) - New name
•phone (optional string) - New phone number
•metadata (optional dictionary) - Updated metadata
Returns: Updated customer object
Delete Customer
delete = client . customer . delete (‘cus_abc123’)
Parameters:
•customer_id (required string) - ID of customer for account deletion
Returns: Dictionary with id and deleted status: (‘Id’: ‘cus_abc123’, ‘deleted’ : True)
Handling of Errors
from paymentflow import PaymentFlowError, AuthenticationError, ValidationError
try:
payment = client.payments.create (
amount=1000
currency= ‘USD’
)
except AuthenticationError as e:
print (f"Authentication failed: {e . message}”)
# Check your API key
except ValidationError as e:
print (f"Invalid parameters: {e.message}”)
print (f”Field: [e. field}”)
# Fix the invalid parameter
except PaymentFlowError as e:
print (f”API error : {e . message}”)
print (f”Error code : {e . code}”)
# General error handling
Examples of Exceptions
•PaymentFlowError - Base exception class for all SDK errors
•AuthenticationError - Invalid or expired API key
•ValidationError - Invalid parameters missing required fields
•RateLimitError - Too many requests sent within a short time
•NetworkError - Connection issues or timeouts
Webhooks
Verify webhook signatures to ensure original requests from PaymentFlow:
from paymentflow import Webhook
webhook_secret = ‘whsec_abc123…’ # From dashboard
def handle_webhook (payload,signature_header):
try:
event = Webhook . construct_event (
payload,
signature_header
webhook_secret
)
except ValueError:
# Invalid payload
return 400
except SignatureVerificationError :
# Invalid signature
return 401
# Handle event
if event . type == ‘payment succeeded’ :
payment = event . data
print (f”Payment {payment . id} succeeded”)
return 200
Available event types:
•payment.succeeded - Payment completed successfully
•payment.failed - Payment was declined or failed
•payment.cancelled - Payment was manually cancelled
•refund.created - Refund was initiated
•refund.completed: Refund was processed and has been returned
Testing
Use sandbox mode for testing without processing real payments:
client = PaymentFlowClient(
api_key= ‘pk_test_… ‘ ,
environment= ‘ sandbox ‘
)
Test card numbers:
•4242424242424242 - Payment successful
•40000000000000002 - Card declined
•40000000000009995 - Insufficient funds error
•40000000000000069 - Card expiry error
All test cards can make use of either future expiration dates or three-digit CVC.
Best Practices:
1: Use Idempotency keys for payment creation: Helps to prevent duplicate charges if request is retried due to network issues.
import vvid
payment = client.payments.create (
amount=5000 ,
currency= ‘ USD ‘,
Idempotency_key=str (vvid . vvid4 ( ) )
)
2: Store customers IDs in your databases: Link PaymentFlow customer IDs to your user records for repeat transactions.
3: Implement webhook handlers: Don't rely solely on synchronous API responses. Use webhooks for asynchronous event processing especially in payments confirmation.
4: Never log full API keys: Mask sensitive information in logs.
api_key_masked = api_key[:7] + ‘...’ + api_key [-4:]
logger.info (f”Using API key: {api_key_masked}”)
5: Handle all exception types explicitly: Don't use generic exception handlers in production. Catch specific exceptions and handle appropriately.
6: Use metadata fields: Link payments to your internal records using metadata.
payment = client.payments.create (
amount=5000,
currency= ‘USD’
metadata= {
‘ order_id ‘ : ‘12345 ‘
‘ customer_user_id ‘ : ‘ 67890 ‘,
‘ campaign ‘ : ‘ summer_sale ‘
}
)
Rate Limits
API requests are limited to some rates in order to prevent abuse.
•Sandbox environment: 100 requests per minute.
•Production environment: 1,000 requests per minute.
Exceeding rates limits returns.
RateLimitError exception: Implement any exponential backoff retry logic.
import time
max_retries = 3
retry_delay = 1
for attempt in range (max_retries) :
try:
payment= client.payments.create(amount=1,000, currency=’USD’)
except RateLimitError :
if attempt < max_retries - 1:
time . sleep (retry_delay)
retry_delay *= 2. # Exponential backoff else:
raise
Pagination
List out operations that shows paginated results. Use the starting_ after parameter to fetch subsequent pages.
# First page
payment = client.payments.list (limit =10)
# Next page
if payments .has _ more:
last_payment_id = payments.data[-1] .id
next_payment = client.payment.list (
limit=10
starting_after=last_payment_id
)
Pagination fields:
•data: Array of objects (Payments, Customers,etc.)
•has_more - Boolean indicating if more results exist.
•total_count - Total number of matching objects (may be approximate for large datasets)
Idempotency
Making the same request multiple times with the same Idempotency_key brings about the same result but this time without side effects. This prevents duplicate charges if your requests is retried due to network failures.
# First request
payment1 = client.payments.create(
amount=5000
currency= ‘USD’
Idempotency_key= ‘order_12345 ‘
)
# Retry with the same key returns via original payment2 = client.payments.create (
amount=5000,
currency= ‘ USD ‘
Idempotency_key= ‘order_12345 ‘
)
# payment1.id == payment2.id (same payment object)
Idempotency keys are valid only for 24 hours. After that, the same key creates a new resource.
Metadata
Attach custom key-value data to objects using metadata parameter. They're also useful for linking PaymentFlow objects to your internal systems.
Rules:
•Maximum of 50 keys per object
•Key names sum up to 40 characters
•Values up to 500 characters
•Both keys and values must be strings
payment = client.payments.create (
amount=5000 ,
currency= ‘ USD ‘,
metadata={
‘ order_id ‘ : ‘12345’ ,
‘customer_tier’ : ‘premium’,
‘ referral_code ‘ : ‘ SUMMER2025 ‘
}
)
# Retrieve later
print (payment.metadata [‘order_id’] ) # ‘12345’
Versioning
The SDK automatically handles API versioning. The current version is pinned to ensure consistent behaviour.
To upgrade to a new API release:
pip install - - upgrade paymentflow - sdk
Check release notes at github.com/paymentflow/python-sdk/releases for breaking changes.
Support Resources
Documentation: docs.paymentflow.com
API Reference: docs.paymentflow.com/api
API Status : status.paymentflow.com
Support Email: support@paymentflow.com
Github Repository: github.com/paymentflow/python-sdk
Community Forum: community.paymentflow.com
Response time:
•Critical issues (payment processing down): 1 hour
•High priority (Integration blockers): 4 hours
•Normal inquiries: 24 hours
Changelog
Version 2.1.0 (Current)
•Added support for refund webhooks
•Improved error messages for validation failures
•Fixed pagination bug with large result sets.
Version 2.0.0
•Breaking change: Renamed payment and status values for clarity
•Added customer object support
•Implemented automatic retry logic for network failures
See full changelog at github.com/paymentflow/python-sdk/blob/main/CHANGELOG
Comments
Post a Comment