Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Initial Implement Azul Payment Gateway Integration #24

Open
wants to merge 43 commits into
base: master
Choose a base branch
from

Conversation

joelGabriel7
Copy link

@joelGabriel7 joelGabriel7 commented Feb 4, 2025

Azul Payment Gateway Integration

Description

This PR implements a integration with Azul's payment gateway, providing a robust Python SDK for processing payments, refunds, authorization holds, and secure card tokenization. The implementation follows best practices for payment processing and includes comprehensive documentation and testing.

Features

  • Payment Processing

    • Direct card payments with validation
    • Authorization holds for pre-auth scenarios
    • Refund processing with transaction validation
    • Support for taxes (ITBIS) and custom order IDs
  • Card Tokenization (DataVault)

    • Secure card storage
    • Token-based payments
    • Token management (creation/deletion)
    • PCI compliance support
  • Developer Experience

    • Async/await support for all operations
    • Type-safe models with Pydantic validation
    • Comprehensive error handling
    • Detailed documentation and examples

Recent Updates (04/02/2025)

New Features

  • Extended Transaction Operations

    • Added POST transaction support for completing pre-authorized payments
    • Implemented VOID functionality for canceling transactions
    • Added VERIFY endpoint for transaction status verification
    • Enhanced transaction lifecycle management
  • Enhanced Error Handling

    • Added comprehensive error mapping for Azul API responses
    • Implemented custom exception classes for better error identification
  • Testing Improvements

    • Added integration tests for new transaction operations (POST/VOID/VERIFY)
    • Expanded unit test coverage for core services
    • Added test scenarios for transaction lifecycle
  • Documentation Updates

    • Added usage examples for POST, VOID, and VERIFY operations
    • Updated API reference documentation
    • Included transaction lifecycle documentation
    • Added troubleshooting guide

Implementation Details

Core Components

Transaction Service (pyazul/services/transaction.py)

  • Handles all payment-related operations
    • Direct card payments
    • Authorization holds
    • Refunds
    • POST transactions
    • VOID transactions
    • Transaction verification

DataVault Service (pyazul/services/datavault.py)

  • Manages card tokenization operations
    • Token creation
    • Token-based payments
    • Token deletion

Latest Changes (05/02/2025)

  • Model Improvements

    • Migrated PaymentPageModel to Pydantic v2 ConfigDict
    • Removed deprecated class-based Config
    • Fixed Pydantic deprecation warnings
    • Maintained backward compatibility
  • Testing Enhancements

    • Added comprehensive test suite for PaymentPageModel
    • Implemented test cases for:
      • Amount validation
      • ITBIS zero handling ("000" format)
      • Custom field validation
      • Form generation
      • Auth hash verification

Latest Changes (11/02/2025)

Certificate Management Improvements

  • Enhanced Certificate Handling

    • Added support for multiple certificate input formats:
      • File paths (relative or absolute)
      • Direct PEM content
      • Base64 encoded certificates
    • Improved certificate validation and error handling
    • Added secure file permission enforcement
  • Configuration Enhancements

    • Updated certificate loading in config.py with robust validation
    • Added support for environment-specific certificate paths
    • Improved error messages for certificate loading failures
    • Enhanced security with proper file permissions
  • Client Updates

    • Enhanced certificate error handling in client.py
    • Added graceful fallback for certificate loading
    • Improved error reporting for certificate issues

Latest Changes (17/02/2025)

3D Secure Implementation Details

Core Components

Models

  • SecureSaleRequest: Main model for 3DS transactions
  • CardHolderInfo: Cardholder information for risk assessment
  • ThreeDSAuth: Authentication configuration and notification URLs
  • ChallengeIndicator: Enumeration for challenge preferences

Services

  • SecureService: Core service for 3DS flow handling
    • Secure sale processing
    • 3DS method notification handling
    • Challenge processing
    • Session and state management

Client Refactoring

  • Migration to modern SSL context management
  • Request methods consolidation
  • Enhanced error handling and retries
  • Support for 3DS-specific headers

Example Implementation

Secure Payment Demo

  • Complete 3DS flow implementation
  • Test cards for different scenarios
  • Notification and challenge handling
  • Visual state feedback

Test Cards

  • Frictionless with 3DSMethod
  • Frictionless without 3DSMethod
  • Challenge with 3DSMethod
  • Challenge without 3DSMethod

Key Improvements

Architecture

  • Enhanced SSL certificate management
  • Unified request methods
  • Robust session handling system
  • Transaction state tracking

Authentication

  • Complete frictionless flow support
  • Challenge flow implementation
  • Method notification processing
  • Dynamic form generation

UI/UX

  • Modern payment interfaces
  • Dynamic state feedback
  • Enhanced error messaging
  • Clear user guidance

Documentation

  • Flow-specific implementation guides
  • Authentication flow diagrams
  • Test card information
  • Troubleshooting guide

- Added PaymentTransaction base model with amount validation

- Implemented SaleTransaction, HoldTransaction, RefundTransaction models

- Added CardData validation with proper field constraints

- Enhanced validation utilities for amount and ITBIS handling

This improves payment processing reliability and provides proper validation for Azul transactions.
- Added AzulAPI client with retry mechanism
- Implemented request/response error handling
- Added logging for debugging

feat(api): add environment and endpoint management
- Added Environment enum and AzulEndpoints class
- Implemented environment-based URL selection
- Added custom URL support

refactor(api): extract common request logic
- Added shared request configuration
- Unified request handling methods
- Improved type hints and error messages
- Added TransactionService for payments
- Added DataVaultService for tokenization
- Implemented async  methods
- Add AzulBaseModel with common payment fields (Channel, Amount, Itbis)
- Implement distinct transaction models:
  * SaleTransactionModel for direct card payments
  * HoldTransactionModel for authorization holds
  * RefundTransactionModel for refunds
  * TokenSaleModel for token-based transactions
- Add DataVault operation models:
  * DataVaultCreateModel for token creation
  * DataVaultDeleteModel for token deletion
- Set default values and validations:
  * Default Channel=EC and PosInputMode=E-Commerce
  * Required card fields for direct payments
  * Optional card fields for token payments
  * Literal types for transaction types (Sale, Hold, Refund)

This change provides type-safe models for each payment operation,
ensuring proper data validation and improving API reliability.
…ault services

- Add detailed class-level documentation explaining service purposes:
  * TransactionService for payment processing (sales, holds, refunds)
  * DataVaultService for card tokenization operations
- Document all public methods with:
  * Clear descriptions of functionality
  * Complete Args/Returns/Raises sections
  * Detailed API response field descriptions
  * Common error scenarios
- Include PCI compliance context for DataVault usage
- Add type hints and return value specifications

This documentation helps developers understand:
- The purpose and capabilities of each service
- Expected inputs and outputs for each operation
- How to handle API responses and errors
- Best practices for secure card data handling
Core Features:
- Implement async HTTP client with certificate-based authentication
- Add automatic environment detection (PROD/TEST)
- Handle request retries with alternate URLs for production
- Add comprehensive error handling and logging

Technical Details:
- Add certificate and private key management
- Implement request preparation with required merchant params
- Add response validation and error parsing
- Set up configurable timeouts and headers
- Add logging for debugging and monitoring

Security:
- Implement secure certificate-based authentication
- Handle sensitive auth headers (Auth1, Auth2)
- Validate API responses for error conditions
- Support custom URLs for different environments

This client provides a secure and reliable foundation for
all Azul API operations, with proper error handling and
logging for production use.
Payment Tests:
- Add comprehensive test cases for card payments and refunds
- Document fixture data with detailed explanations
- Add test assertions with descriptive messages
- Implement proper test isolation with fixtures

Hold Tests:
- Add authorization hold test scenarios
- Document hold transaction flow and purpose
- Add validation for authorization codes and RRN

DataVault Tests:
- Implement complete token lifecycle testing
- Add token creation and validation tests
- Test token-based sales scenarios
- Verify proper error handling for invalid tokens

Test Improvements:
- Add detailed docstrings explaining test purposes
- Document expected outcomes and assertions
- Add descriptive comments for test data
- Improve error messages for failed assertions
- Ensure proper test isolation and data cleanup

This change improves test maintainability and serves as
documentation for the payment integration workflow.
Payment Examples:
- Add detailed payment flow example with card processing
- Add refund example with transaction reference handling
- Add hold/authorization example for pre-auth scenarios
- Add complete DataVault token lifecycle example

Documentation Improvements:
- Add detailed docstrings explaining each example's purpose
- Include step-by-step process descriptions
- Document specific use cases and scenarios
- Add security notes for token handling
- Improve code comments and output messages

Example Features:
- Direct card payment with proper error handling
- Refund processing with transaction ID validation
- Authorization holds for reservations
- Token creation, usage, and deletion flow
- Clear response handling and formatting

These examples serve as both documentation and implementation
guides, showing proper usage of the Azul payment integration
in real-world scenarios.
- Added a new test in  to verify the transaction method.
- Created a fixture for  to provide a configured instance.
- Ensured the test checks for successful transaction verification and transaction presence.
- Add schemas to verifyPayment to validate transaction
- Added  for handling void transactions.
- Updated  to use Post as the .
- Added  for verifying transactions.
- Ensured  is correctly utilized in transaction models.
- Cleaned up and organized schema definitions for better readability.
- Implemented  method to support pre-authorization transactions.
- Added  method to process post-authorization transactions.
- Improved error handling and logging for transaction operations.
- Refactored transaction service for better modularity and maintainability.
- Added test for  transaction method to ensure correct verification.
- Implemented test for  transaction to validate voiding functionality.
- Created test for  transaction to check post-authorization process.
- Utilized fixtures for consistent setup across transaction tests.
- Enhanced test coverage and reliability for transaction service.
- Refactored  client to reduce code duplication and enhance readability.
- Centralized certificate handling and improved error management.
- Added  to handle SSL configuration errors.
- Enhanced logging for better traceability of client operations.
- Created  to demonstrate hold and post transaction flow.
- Added  to illustrate transaction verification process.
- Enhanced examples to provide clear usage patterns for transaction services.
- Add amount format validation and conversion
- Add support for ITBIS calculation
- Add string representation with formatted amounts
- Add field descriptions and documentation
- Add validation for custom fields
- Add secure form generation with auto-submit
- Add HMAC-SHA512 hash calculation
- Add environment-based URL handling
- Add comprehensive documentation
- Remove unnecessary logging
- Add payment form creation endpoint
- Add amount visualization endpoint
- Add example amount handling
- Add error handling
- Add clean documentation
- Replace class-based Config with model_config = ConfigDict

- Add comprehensive test suite for PaymentPageModel

- Add test cases for amount validation and form generation

- Fix Pydantic deprecation warning

- Maintain backward compatibility with existing functionality
… support for multiple certificate input formats (file paths, PEM content, base64) - Enhance certificate loading in config.py with better validation - Update client.py to handle certificate errors gracefully - Add detailed error messages for certificate loading failures - Improve security by enforcing proper file permissions - Add support for environment-specific certificate paths
…h credential depends on type transaction if is 3D or not
- Created SecureSaleRequest model for 3DS transactions with validation
- Implemented CardHolderInfo model with optional fields and documentation
- Added ThreeDSAuth model with URL validation and serialization
- Added ChallengeIndicator enum for authentication preferences
- Implemented custom validation for URLs and critical fields
- Improved data type handling and serialization formats
…ement

- Added SecureService for handling 3DS authenticated payments
- Implemented process_sale for initiating secure transactions
- Added support for 3DSMethod and challenge handling
- Improved session and form management with UI feedback
- Implemented tracking system for 3DS methods
- Optimized authentication flow and error handling
- Added detailed logging for debugging
- Created FastAPI application for 3DS payment demonstration
- Added test cards with different configurations
- Implemented endpoints for payment processing
- Added custom error handling and user feedback
- Implemented complete 3DS flow with method and challenge support
- Improved session handling with secure_id
- Added visual feedback system for transaction states
- Created modern UI components for payment flow feedback
- Added dynamic status handling for transactions and errors
- Implemented consistent styling across all templates
- Added responsive design and visual feedback system
- Improved error handling with detailed messages
- Added animated icons and interactive elements
- Removed code duplication by consolidating request methods in client
- Unified _make_request and _async_request into a single method
- Updated API client to handle SSL certificates properly
- Added delay in void transaction tests to handle processing time
- Improved test configuration in pyproject.toml
- Updated gitignore patterns for development files
- Fixed SSL deprecation warnings in client implementation
- Enhanced error handling for transaction state conflicts
- Added conftest.py to handle PYTHONPATH configuration
- Updated MANIFEST.in to include required package files
- Configured setup.py for proper package installation
- Organized package initialization in api and core modules
- Improved module discovery and import handling
- Enhanced development environment configuration
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant