Python SDK

The Python SDK supports both synchronous and asynchronous operations, with Django integration and comprehensive test coverage. It's designed to be Pythonic, easy to use, and compatible with Python 3.7+.

Installation

Install the SDK using pip:

pip install carifinance

Or using Poetry:

poetry add carifinance

Basic usage

from carifinance import CariFinance

# Initialize with your API key
cari_finance = CariFinance(api_key="sk_test_51NzaWTBOIWoX8E7wnMd1...")

# The SDK will automatically detect if you're using a test or live key

Creating charges

You can create a new charge for a single payment:

# Create a charge
charge = cari_finance.charges.create(
    amount=2000,  # Amount in cents (e.g., $20.00)
    currency="usd",
    provider="card",
    card={
        "token": "tok_visa"  # Token obtained from the client-side SDK
    },
    description="Payment for order #123",
    customer={
        "name": "John Doe",
        "email": "john.doe@example.com"
    }
)

# Check if charge was successful
if charge.status == "succeeded":
    # Payment was successful
    print(f"Payment successful! Charge ID: {charge.id}")
else:
    # Payment failed
    print(f"Payment failed: {charge.failure_message}")

Working with customers

You can create and manage customers:

# Create a new customer
customer = cari_finance.customers.create(
    name="Jane Smith",
    email="jane.smith@example.com",
    phone="+18765551234",
    address={
        "line1": "123 Main St",
        "city": "Roseau",
        "country": "DM"
    }
)

# Retrieve a customer
customer = cari_finance.customers.retrieve("cus_12345")

# Update a customer
customer = cari_finance.customers.update("cus_12345",
    phone="+18765559876"
)

# Delete a customer
cari_finance.customers.delete("cus_12345")

# List customers
customers = cari_finance.customers.list(
    limit=10,
    email="jane.smith@example.com"
)

# Iterate through customers
for customer in customers:
    print(f"Customer: {customer.name}, Email: {customer.email}")

Async support

The SDK supports asynchronous operations with asyncio:

import asyncio
from carifinance.async_client import AsyncCariFinance

async def create_charge():
    # Initialize the async client
    async_client = AsyncCariFinance(api_key="sk_test_51NzaWTBOIWoX8E7wnMd1...")

    # Create a charge asynchronously
    charge = await async_client.charges.create(
        amount=2000,
        currency="usd",
        provider="card",
        card={"token": "tok_visa"},
        description="Async payment"
    )

    print(f"Created charge with ID: {charge.id}")

    # Close the client when done
    await async_client.close()

# Run the async function
asyncio.run(create_charge())

Django integration

For Django applications, add the SDK to your settings.py:

# settings.py
INSTALLED_APPS = [
    # ... other apps
    'carifinance.django',
]

CARI_FINANCE = {
    'api_key': 'sk_test_51NzaWTBOIWoX8E7wnMd1...',
    'webhook_secret': 'whsec_...',  # For webhook handling
}

Create a view to handle payments:

# views.py
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.conf import settings
from carifinance.django import get_client

@csrf_exempt
def create_payment(request):
    if request.method == 'POST':
        import json
        data = json.loads(request.body)

        # Get the client from Django settings
        cari_finance = get_client()

        try:
            # Create a charge
            charge = cari_finance.charges.create(
                amount=data.get('amount'),
                currency=data.get('currency', 'usd'),
                provider='card',
                card={'token': data.get('token')},
                description=data.get('description', 'Payment from Django app')
            )

            return JsonResponse({
                'success': True,
                'charge': {
                    'id': charge.id,
                    'status': charge.status,
                    'amount': charge.amount,
                    'currency': charge.currency
                }
            })
        except Exception as e:
            return JsonResponse({
                'success': False,
                'error': str(e)
            }, status=400)

    return JsonResponse({'error': 'Invalid request method'}, status=405)

Add webhook handling:

# urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('api/payments/', views.create_payment, name='create_payment'),
    path('webhooks/cari-finance/', views.webhook_handler, name='cari_webhooks'),
]

# views.py
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from carifinance.django import webhook_handler as cari_webhook_handler

@csrf_exempt
def webhook_handler(request):
    # This delegates to the SDK's webhook handler
    return cari_webhook_handler(request)

Error handling

The SDK uses exceptions to handle errors:

from carifinance.exceptions import CardError, InvalidRequestError, APIError

try:
    charge = cari_finance.charges.create(
        amount=2000,
        currency="usd",
        # other parameters...
    )
except CardError as e:
    # Card was declined
    print(f"Card error: {e}")
except InvalidRequestError as e:
    # Invalid parameters were supplied
    print(f"Invalid request: {e}")
except APIError as e:
    # Generic API error
    print(f"API error: {e}")

Additional resources

For more detailed information about the Python SDK, refer to these resources:

Was this page helpful?