Skip to main content

Python SDK for Cardinity Payment Gateway API

Project description

Cardinity Python SDK

PyPI version Python versions License Coverage

The Python SDK for the Cardinity Payment Gateway. This library provides a simple and intuitive way to integrate Cardinity's payment processing capabilities into your Python applications.

🚀 Features

  • Complete API Coverage: Full support for all Cardinity API operations
  • 3D Secure v2: Built-in support for strong customer authentication
  • Type Safety: Full type hints for better development experience
  • Comprehensive Testing: Extensive test suite with 92% code coverage
  • Production Ready: Built for scalability and reliability
  • Easy Integration: Simple, intuitive API design
  • Python 3.8+: Support for modern Python versions

📦 Installation

Install the Cardinity Python SDK using pip:

pip install cardinity-python

Or using uv (recommended):

uv add cardinity-python

🏁 Quick Start

Basic Setup

from cardinity import Cardinity

# Initialize the client
cardinity = Cardinity(
    consumer_key="your_consumer_key",
    consumer_secret="your_consumer_secret"
)

Create a Payment

# Create a simple payment
payment = cardinity.create_payment(
    amount="10.00",
    currency="EUR",
    description="Test payment",
    country="LT",
    payment_instrument={
        "pan": "4111111111111111",
        "exp_month": 12,
        "exp_year": 2025,
        "cvc": "123",
        "holder": "John Doe"
    }
)

print(f"Payment created: {payment['id']}")
print(f"Status: {payment['status']}")

Handle 3D Secure Authentication

# Create payment that may require 3DS
payment = cardinity.create_payment(**payment_data)

if payment['status'] == 'pending':
    # 3DS authentication required
    auth_url = payment['authorization_information']['url']
    print(f"Please complete 3DS authentication: {auth_url}")
    
    # After customer completes 3DS, finalize the payment
    finalized = cardinity.finalize_payment(
        payment['id'],
        authorize_data="auth_data_from_3ds_callback"
    )
    print(f"Final status: {finalized['status']}")

📚 Documentation

💡 Examples

Basic Payment Processing

from cardinity import Cardinity, CardinityError

cardinity = Cardinity(
    consumer_key="your_key",
    consumer_secret="your_secret"
)

try:
    payment = cardinity.create_payment(
        amount="25.00",
        currency="EUR",
        description="Product purchase",
        country="LT",
        payment_instrument={
            "pan": "4111111111111111",
            "exp_month": 12,
            "exp_year": 2025,
            "cvc": "123",
            "holder": "Jane Smith"
        }
    )
    
    if payment['status'] == 'approved':
        print("✅ Payment successful!")
    elif payment['status'] == 'pending':
        print("⏳ Awaiting 3DS authentication")
    
except CardinityError as e:
    print(f"❌ Payment failed: {e}")

Recurring Payments

# Create initial payment for future recurring use
initial_payment = cardinity.create_payment(
    amount="0.00",  # Authorization only
    currency="EUR",
    description="Setup recurring payment",
    country="LT",
    payment_instrument={
        "pan": "4111111111111111",
        "exp_month": 12,
        "exp_year": 2025,
        "cvc": "123",
        "holder": "John Doe"
    }
)

# Create recurring payment using the initial payment
recurring_payment = cardinity.create_recurring_payment(
    amount="29.99",
    currency="EUR", 
    description="Monthly subscription",
    payment_id=initial_payment['id']
)

Refund Processing

# Create a refund
refund = cardinity.create_refund(
    payment_id="payment_id_here",
    amount="10.00",
    description="Customer requested refund"
)

print(f"Refund created: {refund['id']}")
print(f"Status: {refund['status']}")

🧪 Testing

The SDK includes comprehensive test coverage:

# Run all tests
pytest

# Run with coverage
pytest --cov=cardinity

# Run integration tests (requires API credentials)
pytest -m integration

# Run performance tests
pytest -m performance

Test Credentials

To get test credentials for development and testing:

  1. Log in to your Cardinity account
  2. Navigate to the API settings or developer section
  3. Generate or retrieve your test/sandbox credentials
  4. Use these credentials for testing:
CONSUMER_KEY = "your_test_consumer_key"
CONSUMER_SECRET = "your_test_consumer_secret"

Test Cards

  • Visa Success: 4111111111111111
  • MasterCard Success: 5555555555554444
  • 3DS Required: 4444333322221111
  • American Express: 378282246310005

Test Amounts:

  • Success: Any amount < 150.00
  • Failure: Any amount >= 150.00

🔐 Security & Authentication

The SDK uses OAuth 1.0 with HMAC-SHA1 signatures for secure API communication:

# Production setup with environment variables
import os

cardinity = Cardinity(
    consumer_key=os.getenv('CARDINITY_CONSUMER_KEY'),
    consumer_secret=os.getenv('CARDINITY_CONSUMER_SECRET')
)

Security Best Practices:

  • Never commit API credentials to version control
  • Use environment variables for credentials
  • Validate all payment data before processing
  • Implement proper error handling
  • Use HTTPS in production

🌍 Environment Configuration

Production Environment

cardinity = Cardinity(
    consumer_key="your_live_consumer_key",
    consumer_secret="your_live_consumer_secret",
    base_url="https://api.cardinity.com/v1"  # Default
)

Sandbox/Test Environment

cardinity = Cardinity(
    consumer_key="your_test_consumer_key",
    consumer_secret="your_test_consumer_secret"
)

📋 API Operations

The SDK supports all Cardinity API operations:

Payments

  • create_payment() - Create new payments
  • get_payment() - Retrieve payment information
  • finalize_payment() - Complete 3DS authentication
  • create_recurring_payment() - Create recurring payments

Refunds

  • create_refund() - Process refunds
  • get_refund() - Retrieve refund information

Additional Operations

  • create_settlement() - Create settlements
  • create_void() - Void payments
  • create_payment_link() - Create payment links
  • get_chargeback() - Retrieve chargeback information

🔄 Migration from Node.js

Migrating from the Cardinity Node.js SDK? Check our Migration Guide for:

  • Side-by-side code comparisons
  • Parameter name changes
  • Error handling differences
  • Step-by-step migration process

Quick Comparison:

// Node.js SDK
const client = Cardinity({
  consumerKey: 'key',
  consumerSecret: 'secret'
});

client.payments.create({
  amount: '10.00',
  paymentInstrument: { pan: '4111111111111111' }
});
# Python SDK
client = Cardinity(
    consumer_key='key',
    consumer_secret='secret'
)

client.create_payment(
    amount='10.00',
    payment_instrument={'pan': '4111111111111111'}
)

⚡ Performance

The SDK is optimized for performance:

  • Async Support: Built on modern Python async patterns
  • Connection Pooling: Efficient HTTP connection management
  • Request Optimization: Minimal overhead per API call
  • Memory Efficient: Low memory footprint

Performance benchmarks (on average hardware):

  • Payment creation: ~200ms
  • Payment retrieval: ~150ms
  • Concurrent requests: 50+ req/sec

🛠️ Development

Setup Development Environment

# Clone the repository
git clone https://github.com/trendpro/cardinity-python.git
cd cardinity-python

# Install with development dependencies
uv sync --all-extras

# Run tests
uv run pytest

# Build documentation
uv run sphinx-build docs docs/_build

Contributing

We welcome contributions! Please see our Contributing Guide for:

  • Development setup instructions
  • Code style guidelines
  • Testing requirements
  • Pull request process

📖 API Reference

For complete API documentation, see:

🆘 Support

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

🏷️ Versioning

We use Semantic Versioning for version management. For available versions, see the tags on this repository.

🎯 Roadmap

  • Webhook validation utilities
  • Advanced retry mechanisms
  • GraphQL API support
  • Enhanced logging and debugging
  • Performance monitoring integration

🙏 Acknowledgments

  • Built with ❤️ by the Cardinity team
  • Inspired by the Node.js SDK
  • Thanks to all contributors and users

Ready to start processing payments?

  1. Sign up for a Cardinity account
  2. Get your API credentials
  3. Install the SDK: pip install cardinity-python
  4. Follow the Quick Start Guide

For questions or support, don't hesitate to contact us!

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

cardinity_python-1.0.0rc4.tar.gz (8.4 MB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

cardinity_python-1.0.0rc4-py3-none-any.whl (32.0 kB view details)

Uploaded Python 3

File details

Details for the file cardinity_python-1.0.0rc4.tar.gz.

File metadata

  • Download URL: cardinity_python-1.0.0rc4.tar.gz
  • Upload date:
  • Size: 8.4 MB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.7.13

File hashes

Hashes for cardinity_python-1.0.0rc4.tar.gz
Algorithm Hash digest
SHA256 7d0d6df36b3b582332920a6f6a03605777864ae96a6ee1c886598af06f1dee40
MD5 793fed218137df3885b2178ea52f33a7
BLAKE2b-256 546ab5d38c0f2de18b74e682511e7815e1fd605c7befeee7a7ba124b17eaa853

See more details on using hashes here.

File details

Details for the file cardinity_python-1.0.0rc4-py3-none-any.whl.

File metadata

File hashes

Hashes for cardinity_python-1.0.0rc4-py3-none-any.whl
Algorithm Hash digest
SHA256 dd0e5646e76aaecd5d03b50f3110168ded28a0e97de69cf1acd926a5e2b9478f
MD5 5346fb715e8715d9a2bbed797a880b34
BLAKE2b-256 4265528cfe69a150b4b179efb4fc145eafc65f1f3be23056d6aa3fb84d98b628

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page