Download the PHP package sequra/integration-core without Composer
On this page you can find all versions of the php package sequra/integration-core. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download sequra/integration-core
More information about sequra/integration-core
Files in sequra/integration-core
Package integration-core
Short Description Core SeQura integration library
License proprietary
Informations about the package integration-core
SeQura Integration Core Library
Table of Contents
- π Overview
- What is the SeQura Integration Core?
- Problems Solved by Integration Core
- π Installation
- Requirements
- Installing via Composer
- Developer guide
- π Quick Start Guide
- Services
- Repositories
- Using the BootstrapComponent
- Core Infrastructure Services (Required)
- Business Logic Services (Required)
- Order Management Services (Required)
- Integration Services (Required)
- Widget Services (Optional but Recommended)
- Repository Registrations (Required)
- Minimum Implementation Checklist
- π¦ Platform Integration Examples
- π Public API Documentation
- Architecture Overview
- Infrastructure Components
- Admin API Layer
- Checkout API Layer
- Webhook API Layer
- Configuration Webhook API Layer
- API Proxy Layer
- Task Execution System
- ORM & Data Persistence Layer
- Multi-store Context Management
- SeQura API Proxy Layer
- π§© Customization and Extensibility
π Overview
What is the SeQura Integration Core?
The sequra/integration-core library is a platform-agnostic PHP library that provides the foundational business logic and API communication layer for integrating SeQura payment methods into any e-commerce platform. It is built following clean architecture principles, ensuring that the payment processing logic remains centralised and consistent across implementations.
One of the main goals of the library is to provide this shared, centralised logic, while still allowing for customisation and extension to adapt behaviour and structure to different systems. At the same time, it avoids dependencies on system-specific or third-party components, relying only on pure PHP and vanilla JavaScript to keep the core flexible, lightweight, and portable.
The library is designed with the following non-functional requirements, which are to be consistently upheld across all SeQura integrations:
- Platform-agnostic: Works with any PHP-based e-commerce platform
- Modular: Components can be used independently or together
- Extensible: Allows custom implementations of interfaces
- Testable: Clear separation of concerns with dependency injection
These attributes are not just desirable qualities, but mandatory design goals that ensure long-term maintainability and alignment with SeQuraβs architectural principles. They represent core priorities, though not the entirety of the non-functional requirements defined for the CORE. For a complete overview, refer to the architectural documentation, which describes in detail how these and other quality attributes shape both the design and implementation of the system.
Problems Solved by Integration Core
Architectural Overview
To ensure maintainability and alignment with clean architecture principles, the integration-core library separates responsibilities into distinct layers, following the Onion Architecture model.
This structure avoids mixing concerns, keeps the core logic centralised, and ensures consistency across all SeQura integrations.
CORE β Infrastructure
Provides the technical foundation to support business logic, ensuring consistency and portability across platforms:
- Logging β unified logger for consistent monitoring and troubleshooting
- HTTP Infrastructure β standardized communication with external services
- ORM Abstraction β repository pattern for persistence without platform lock-in
- Task Runner β scheduling and background task execution
CORE β Business Logic
Encapsulates SeQuraβs domain logic, centralized and reusable across all platforms:
- API Facades β simplified access to SeQura API endpoints
- Checkout Services β consistent handling of payment initiation and processing
- Order Management Services β standardized order lifecycle handling
- Plugin Administration Services β centralized configuration and credential management
- API Proxy & JS Library β abstraction for frontendβbackend communication
Integration Interfaces
Defines extension points that allow business logic to interact with diverse e-commerce systems without leaking system-specific dependencies.
Concrete Integrations
Implements shop-specific adapters and extensions, bridging CORE with the host platform:
- Platform-specific Implementations β e.g., order state transitions, checkout extensions
- UI/UX Extensions β extensions to checkout or order screens
- Bootstrap Components β initialization of the integration in the host platform
- Event Listeners β handling shop-specific events (orders, payments, refunds, etc.)
π Installation
Requirements
- PHP: >= 7.2
- Extensions:
json,ctype,mbstring - Composer: For dependency management
Installing via Composer
Developer guide
If you are planning to contribute to the development of this library, please refer to the Developer Guide for instructions on setting up your development environment, debugging, and running tests.
π Quick Start Guide
The library uses a bootstrap pattern for initialization. This step must be performed after installing the library.
Its main goal is to ensure independence from the dependency injection (DI) mechanisms of different systems, and to provide a way for services to be overridden or extended in concrete platform integrations.
The dependency inversion principle is applied here as a best practice to achieve this flexibility, but it is not the primary objective of the bootstrap process.
This library provides a BootstrapComponent class that should be extended by the platform integration. The BootstrapComponent is responsible for registering all required services, repositories and dependencies.
Before going deeper into the BootstrapComponent, let's see take a quick look at the concept of Services, Repositories and how to register them.
Services
Services are intended to handle use-cases. The way you should use to register a new Service is through the SeQura\Core\Infrastructure\ServiceRegister class. The following example shows how to register the implementation for the SeQura\WC\Services\Core\Encryptor service required to encrypt and decrypt text.
For retrieving the instance, use this method instead:
Repositories
Repositories define a way to read and write data to a datasource (like a database) and map raw data to entities. They must implement SeQura\Core\Infrastructure\ORM\Interfaces\RepositoryInterface. The integration-core provides for this the SeQura\Core\Infrastructure\ORM\RepositoryRegistry, similar to the service alternative.
To register a new repository implementation, see the following example:
To retrieve a repository:
Using the BootstrapComponent
To use the BootstrapComponent, extend it in your platform integration and implement the init method to register all required services and repositories. Here's an example for a Magento 2 integration:
After implementing the Bootstrap class, you can call Bootstrap::init() in your platform's bootstrap process to initialize the integration core library.
Here are the essential components your bootstrap implementation must provide:
Core Infrastructure Services (Required)
These services must be implemented by every platform integration:
1. Configuration Service
2. Logger Service
3. Encryptor Service
Business Logic Services (Required)
4. Store Service
5. Version Service
6. Category Service
7. Product Service
Order Management Services (Required)
8. Order Creation Service
9. Merchant Data Provider
10. Order Report Service
Integration Services (Required)
11. Selling Countries Service
12. Disconnect Service
Widget Services (Optional but Recommended)
13. Widget Configurator
14. Mini Widget Messages Provider
Repository Registrations (Required)
Your bootstrap must also register repositories for entity persistence:
Minimum Implementation Checklist
β Infrastructure Layer
- [ ] Configuration service extending
Configuration - [ ] Logger service implementing
ShopLoggerAdapter - [ ] Encryptor service implementing
EncryptorInterface - [ ] Serializer service (usually
JsonSerializeris sufficient)
β Platform Integration Layer
- [ ] Store service implementing
StoreServiceInterface - [ ] Version service implementing
VersionServiceInterface - [ ] Category service implementing
CategoryServiceInterface - [ ] Product service implementing
ProductServiceInterface
β Order Management Layer
- [ ] Order creation service implementing
OrderCreationInterface - [ ] Merchant data provider implementing
MerchantDataProviderInterface - [ ] Order report service implementing
OrderReportServiceInterface
β Business Services Layer
- [ ] Selling countries service implementing
SellingCountriesServiceInterface - [ ] Disconnect service implementing
DisconnectServiceInterface
β Data Persistence Layer
- [ ] Repository implementations for all core entities
- [ ] Database schema creation/migration support
β Optional Enhancement Layer
- [ ] Widget configurator for promotional widgets
- [ ] Mini widget messages provider
- [ ] Shop order statuses service
This comprehensive list ensures your platform integration provides all necessary components for the SeQura Core library to function properly across all supported use cases.
π¦ Platform Integration Examples
You can take a look at existing implementations of the integration-core library in the following repositories:
π Public API Documentation
Architecture Overview
The Core will be implemented by following the onion architecture comprised of multiple concentric layers interfacing with each other towards the core that represents the business logic, as displayed in the diagram below. Onion Architecture is based on the inversion of control principle where inner layers' dependencies are abstracted as required interfaces:
The library structure is organized the following way:
Infrastructure Components
The Infrastructure Components form the foundation of any SeQura integration, providing essential services for logging, HTTP communication, configuration storage, task execution, and data persistence. Understanding and properly implementing these components is critical for a robust, scalable integration.
Overview
The infrastructure layer follows Dependency Inversion Principle and uses Abstract Factory Pattern to provide platform-agnostic implementations of core services while allowing platform-specific customizations through interface implementations.
Core Infrastructure Components
1. HTTP Client Infrastructure
- Purpose: Handles all HTTP communication with SeQura APIs
- Features: Request/response handling, SSL verification, proxy support, timeout management
- Extensibility: Custom authentication, retry logic, caching
2. Logging Infrastructure
- Purpose: Centralized logging for debugging, monitoring, and audit trails
- Features: Multiple log levels, structured logging, log rotation, remote logging
- Integration: Platform logging systems, external monitoring tools
Implementation example based on Magento 2:
3. Configuration Infrastructure
- Purpose: Secure storage and retrieval of integration settings
- Features: Encryption, validation, environment management, multi-store support
- Security: Credential protection, secure defaults, audit logging
Implementation example based on Magento 2:
4. Task Execution Infrastructure
- Purpose: Background task processing and queue management
- Features: Priority queues, retry mechanisms, progress tracking, failure recovery
- Scalability: Distributed processing, load balancing, horizontal scaling
5. ORM Infrastructure
- Purpose: Database abstraction and entity management
- Features: Query building, connection management, transaction handling, migration support
- Performance: Connection pooling, query optimization, caching
6. Regex Provider Infrastructure
- Purpose: Provides regular expressions for common validation tasks
- Features: IP address validation, email format validation, URL structure validation
- Extensibility: Custom regex patterns can be added as needed
If you're using the Integration Core UI library you must provide the regular expressions for validating user input in the admin panel when the SequraFE object is initialized. The RegexProvider service provides a function toArray() for this purpose. Example:
Key Infrastructure Benefits
- Reliability: Comprehensive error handling and retry mechanisms
- Security: Encryption, secure defaults, audit logging
- Performance: Caching, connection pooling, resource monitoring
- Scalability: Distributed processing, load balancing capabilities
- Monitoring: Detailed metrics, health checks, alerting
- Maintainability: Structured logging, configuration management
- Flexibility: Platform-agnostic interfaces with custom implementations
Infrastructure Best Practices
- Error Handling: Implement comprehensive error handling with appropriate retry logic
- Security: Encrypt sensitive data, use secure defaults, audit all changes
- Performance: Monitor resource usage, implement caching strategies
- Reliability: Use transactions, implement health checks, monitor system health
- Observability: Implement detailed logging and metrics collection
- Configuration: Validate all configuration, provide migration paths
- Testing: Test infrastructure components thoroughly with realistic scenarios
Admin API Layer
The AdminAPI layer in the SeQura integration-core library provides a standardized interface for platform integrations to interact with SeQura's administrative functionalities. It serves as the primary entry point for all admin panel operations, offering a clean separation between business logic and platform-specific implementations.
Overview
The AdminAPI layer follows a Controller-Service pattern with Aspect-Oriented Programming (AOP) for cross-cutting concerns like error handling and store context management.
Core Components
1. AdminAPI Main Class
- Purpose: Central factory for accessing all admin controllers
- Pattern: Singleton with method chaining and aspect weaving
- Key Method:
get()- Returns an instance with error handling applied
2. Controllers (9 Main Controllers)
ConnectionController
- Purpose: Manages SeQura API connection and authentication
- Key Methods:
getOnboardingData()- Retrieves connection setup dataisConnectionDataValid()- Validates API credentialsvalidateConnectionData()- Full validation with error detailssaveConnectionData()- Persists connection settingsconnect()- Establishes connection with onboarding
PaymentMethodsController
- Purpose: Manages available payment methods and products
- Key Methods:
getPaymentMethods()- Gets merchant's payment methodsgetAllAvailablePaymentMethods()- Gets formatted payment methods for all merchantsgetProducts()- Retrieves merchant products
GeneralSettingsController
- Purpose: Handles general configuration settings
- Key Methods:
getGeneralSettings()- Retrieves current settingssaveGeneralSettings()- Updates configurationgetShopCategories()- Gets platform categories
CountryConfigurationController
- Purpose: Manages country-specific configurations
- Key Methods:
getSellingCountries()- Gets available selling countriesgetCountryConfigurations()- Retrieves country settingssaveCountryConfiguration()- Updates country settings
PromotionalWidgetsController
- Purpose: Manages promotional widget settings
- Key Methods:
getWidgetSettings()- Gets widget configurationsaveWidgetSettings()- Updates widget settings
OrderStatusSettingsController
- Purpose: Manages order status mapping
- Key Methods:
getOrderStatusSettings()- Gets status mappingssaveOrderStatusSettings()- Updates status mappings
TransactionLogsController
- Purpose: Handles transaction logging and monitoring
- Key Methods:
getTransactionLogs()- Retrieves transaction historygetTransactionDetails()- Gets specific transaction info
DisconnectController
- Purpose: Handles SeQura integration disconnection
- Key Methods:
disconnect()- Safely disconnects integrationcleanup()- Performs cleanup operations
DeploymentsController
- Purpose: Manages deployment environments
- Key Methods:
getAllDeployments()- Gets all deploymentsgetNotConnectedDeployments()- Gets unconnected deployments
3. Aspects (Cross-cutting Concerns)
ErrorHandlingAspect
- Purpose: Provides consistent error handling across all controllers
- Features:
- Catches and translates exceptions
- Logs errors with context
- Returns standardized error responses
- Handles API-specific exceptions (unauthorized, invalid parameters)
StoreContextAspect
- Purpose: Manages multi-store context
- Features:
- Sets store context before method execution
- Ensures store-specific data isolation
- Handles store switching
4. Request/Response Objects
- Requests: Strongly-typed input objects that validate and transform data
- Responses: Structured output objects with
toArray()methods for serialization
Practical Example: General Settings Management
Here's a comprehensive example showing how the AdminAPI is used in a Magento admin controller:
Checkout API Layer
The CheckoutAPI layer in the SeQura integration-core library provides customer-facing functionality for the checkout process and promotional widgets. Unlike the AdminAPI which handles backend configuration, the CheckoutAPI focuses on real-time customer interactions during the shopping experience.
Overview
The CheckoutAPI follows the same Controller-Service pattern with Aspect-Oriented Programming (AOP) as the AdminAPI, but is optimized for frontend performance with caching mechanisms and validation layers.
Core Components
1. CheckoutAPI Main Class
- Purpose: Central factory for accessing checkout-related controllers
- Pattern: Singleton with method chaining and aspect weaving
- Key Method:
get()- Returns an instance with error handling applied - Performance Focus: Optimized for fast responses to customer-facing requests
2. Controllers (3 Main Controllers)
SolicitationController
- Purpose: Handles order solicitation and payment method discovery
- Key Methods:
solicitFor(CreateOrderRequestBuilder $builder)- Creates a solicitation request to SeQura APIgetIdentificationForm(string $cartId, string $product, string $campaign, bool $ajax)- Retrieves customer identification form
Use Case: When a customer reaches checkout, this controller determines which SeQura payment options are available based on cart contents, shipping address, and merchant configuration.
CachedPaymentMethodsController
- Purpose: Provides cached payment method data for performance optimization
- Key Methods:
getCachedPaymentMethods(GetCachedPaymentMethodsRequest $request)- Retrieves payment methods from local cache
Use Case: Instead of making API calls on every page load, this controller serves cached payment method data, improving checkout performance.
PromotionalWidgetsCheckoutController
- Purpose: Manages promotional widgets display during the shopping journey
- Key Methods:
getPromotionalWidgetInitializeData(PromotionalWidgetsCheckoutRequest $request)- Gets widget initialization datagetAvailableWidgetForCartPage(PromotionalWidgetsCheckoutRequest $request)- Returns cart page widgetsgetAvailableMiniWidgetForProductListingPage(PromotionalWidgetsCheckoutRequest $request)- Returns product listing mini-widgetsgetAvailableWidgetsForProductPage(PromotionalWidgetsCheckoutRequest $request)- Returns product page widgets
Use Case: Displays SeQura promotional messages and financing options on product pages, category pages, and cart to increase conversion rates.
3. Built-in Validation
The CheckoutAPI includes comprehensive validation layers:
4. Request/Response Objects
- PromotionalWidgetsCheckoutRequest: Contains context data (country, currency, IP, product ID)
- GetCachedPaymentMethodsRequest: Contains merchant ID for cache lookup
- Responses: Structured data optimized for frontend consumption
Practical Example: Product Page Widget Integration
Here's a comprehensive example showing how the CheckoutAPI is used in a Magento product page:
Practical Example: Payment Method Solicitation
Here's how checkout payment method discovery works:
Practical Example: Cart Page Widget
Performance Optimizations
1. Caching Strategy
2. Validation Short-circuits
3. Context-aware Responses
Webhook API Layer
The WebhookAPI layer in the SeQura integration-core library handles incoming webhook notifications from SeQura to synchronize order status changes with the platform. This is a critical component for maintaining data consistency between SeQura's system and the merchant's platform when payment statuses change.
Overview
The WebhookAPI follows a simplified Controller pattern with validation, handling, and asynchronous processing to ensure reliable webhook processing even under high load or temporary system issues.
Core Components
1. WebhookAPI Main Class
- Purpose: Factory for accessing webhook handler with store context
- Pattern: Simple factory with store context aspect
- Key Method:
webhookHandler(string $storeId)- Returns webhook controller with store context applied
2. WebhookController
- Purpose: Handles incoming webhook requests from SeQura
- Key Method:
handleRequest(array $payload)- Validates and processes webhook payload - Response Strategy: Returns appropriate HTTP status codes as expected by SeQura
3. WebhookValidator
- Purpose: Validates webhook authenticity and content
- Validation Steps:
- Order Existence: Verifies the order reference exists in the system
- Signature Verification: Validates webhook signature against stored merchant credentials
- State Validation: Ensures the webhook state is one of the allowed values (
approved,cancelled,needs_review)
4. WebhookHandler
- Purpose: Processes validated webhooks and orchestrates order updates
- Key Methods:
handle(Webhook $webhook)- Main processing methodvalidateOrder(Webhook $webhook)- Additional order validationacknowledgeOrder(string $orderRef, string $state)- Acknowledges order to SeQura API
5. OrderUpdateTask
- Purpose: Asynchronous task for updating order status in the platform
- Features:
- Store Context Aware: Maintains proper store context during execution
- Asynchronous Execution: Prevents webhook timeouts by processing in background
- Error Resilience: Can be retried if initial processing fails
6. Webhook Model
- Purpose: Represents webhook data structure
- Key Properties:
signature- Security signature for validationorderRef- Primary order referencesqState- SeQura order state (approved,cancelled,needs_review)productCode- Payment product usedorderRef1- Secondary order referenceapprovedSince/needsReviewSince- Timing information
Webhook Processing Flow
Practical Example: Magento Webhook Endpoint
Here's a comprehensive example showing how the WebhookAPI is implemented in a Magento webhook endpoint:
Practical Example: Platform-Specific Order Update Service
The ShopOrderService interface must be implemented by each platform:
Webhook Security and Validation
Asynchronous Processing
Expected HTTP Response Codes
SeQura expects specific HTTP response codes:
- 200, 201, 202: Success - webhook processed successfully
- 302, 307: Redirect - acceptable for success
- 404: Not Found - order doesn't exist
- 409: Conflict - temporary issue, SeQura will retry
- 410: Gone - permanent failure, SeQura won't retry
- 501: Not Implemented - unknown event type
Task Execution System
The Task Execution System is the backbone of the SeQura integration-core library's asynchronous processing capabilities. It handles background tasks like webhook processing, order reporting, and long-running operations that cannot be executed synchronously without impacting user experience.
Overview
The task system follows an Event-Driven Queue Architecture with reliable execution, retry mechanisms, and comprehensive monitoring. It's designed to handle high-volume operations while maintaining data consistency and system responsiveness.
Core Components
1. Task (Abstract Base Class)
- Purpose: Base class for all background operations
- Key Features:
- Progress reporting and alive signals
- Automatic serialization/deserialization
- Error handling and recovery
- Priority-based execution
- Store context awareness
2. QueueService
- Purpose: Manages task lifecycle and execution queue
- Key Methods:
enqueue()- Adds tasks to processing queuestart()- Begins task executionfinish()- Completes successful tasksfail()- Handles task failures with retry logicabort()- Terminates tasks permanently
3. QueueItem
- Purpose: Represents a task instance in the queue
- Status Flow:
QUEUEDβIN_PROGRESSβCOMPLETED/FAILED/ABORTED - Properties: Priority, retry count, execution context, timestamps
4. Priority System
- Priority::HIGH - Critical tasks (webhooks, order updates)
- Priority::NORMAL - Standard operations (reporting, sync)
- Priority::LOW - Background maintenance tasks
Creating Custom Tasks
Here's how to create and implement custom tasks:
Using the Queue Service
Here's how to enqueue and manage tasks:
Task Monitoring and Health Checks
Key Benefits of the Task System
- Asynchronous Processing: Non-blocking operations improve user experience
- Reliability: Automatic retry mechanisms handle temporary failures
- Scalability: Queue-based processing handles high-volume operations
- Monitoring: Progress tracking and health monitoring capabilities
- Store Context: Proper multi-store isolation and context management
- Priority Management: Critical tasks (webhooks) get priority over background tasks
- Error Recovery: Failed tasks can be analyzed and retried
- Resource Management: Prevents system overload through controlled execution
Task Execution Best Practices
- Progress Reporting: Always call
reportProgress()for long operations - Alive Signals: Use
reportAlive()in loops to prevent timeout - Store Context: Capture store context in constructor, use in execution
- Error Handling: Distinguish between retryable and permanent failures
- Serialization: Ensure all task data is properly serializable
- Resource Cleanup: Clean up resources in failure/abort handlers
- Monitoring: Implement health checks for production systems
Usage Pattern
ORM & Data Persistence Layer
The ORM (Object-Relational Mapping) & Data Persistence Layer provides a platform-agnostic abstraction for storing and retrieving SeQura integration data. It enables the core library to work with different database systems while maintaining consistent data operations.
Overview
The ORM follows a Repository Pattern with Entity-based modeling and Query abstraction to provide database-independent data operations. Each platform implements repositories using their native database capabilities.
Core Components
1. Entity (Abstract Base Class)
- Purpose: Base class for all data models
- Key Features:
- Automatic serialization/deserialization
- Field mapping and validation
- Configuration-driven schema
- Platform-agnostic data representation
2. RepositoryRegistry
- Purpose: Central registry mapping entities to repository implementations
- Pattern: Registry pattern for dependency injection
- Key Methods:
registerRepository(),getRepository()
3. RepositoryInterface
- Purpose: Contract for all data access operations
- Operations:
select(),selectOne(),save(),update(),delete(),count()
4. QueryFilter
- Purpose: Database-agnostic query building
- Features: Conditions, sorting, pagination, joins
Creating Custom Entities
Here's how to create custom entities for storing integration-specific data:
Implementing Platform-Specific Repositories
Each platform must implement repositories for entity persistence:
[!IMPORTANT]
Remember that you need to register your custom repositories during bootstrap
Using the ORM for Data Operations
Here's how to use the ORM system in your services:
Advanced Query Examples
Key Benefits of the ORM System
- Platform Independence: Same code works across different platforms
- Type Safety: Strongly-typed entities prevent data corruption
- Query Abstraction: Database-independent query building
- Repository Pattern: Clean separation of data access logic
- Store Context: Automatic multi-store data isolation
- Configuration-Driven: Schema defined in entity configuration
- Performance: Indexed queries and efficient data access
- Extensibility: Easy to add custom entities and repositories
ORM Best Practices
- Entity Design: Keep entities focused and cohesive
- Repository Implementation: Use platform-native optimizations
- Index Strategy: Add indexes for frequently queried fields
- Query Optimization: Use specific filters to avoid full table scans
- Data Migration: Plan for schema changes and data migration
- Store Context: Always consider multi-store implications
- Cleanup: Implement data retention policies for large tables
Usage Pattern
Multi-store Context Management
The Multi-store Context Management system ensures proper data isolation and operations across different stores, websites, or tenant environments. This is crucial for platforms that serve multiple merchants or store configurations from a single SeQura integration instance.
Overview
The multi-store system follows a Context Switching Pattern with automatic store isolation to ensure that operations, configurations, and data access are properly scoped to the correct store context without manual intervention.
Core Components
1. StoreContext (Singleton)
- Purpose: Manages current store context and provides context switching capabilities
- Pattern: Thread-safe singleton with context stack management
- Key Methods:
doWithStore(),getStoreId(),getInstance()
2. Store Context Aspect
- Purpose: Automatically applies store context to API operations
- Integration: Used in AdminAPI, CheckoutAPI, and WebhookAPI
- Benefits: Transparent store context management
Understanding Store Context
Store context ensures that:
- Configuration: Each store has its own SeQura settings
- Data Isolation: Orders, logs, and entities are store-specific
- API Calls: Requests use correct store credentials
- Background Tasks: Asynchronous operations maintain proper context
Store Context Usage Patterns
Here's how to properly manage store context in different scenarios:
Store-Aware Repository Implementation
Repositories automatically handle store context filtering:
Task Execution with Store Context
Background tasks maintain store context throughout execution:
Configuration Per Store
Store-specific configuration management:
API Context Integration
The AdminAPI, CheckoutAPI, and WebhookAPI automatically handle store context:
Key Benefits of Multi-store Context
- Automatic Data Isolation: Data is automatically filtered by store
- Configuration Separation: Each store has independent settings
- Credential Management: API calls use correct store credentials
- Task Context Preservation: Background tasks maintain store context
- Error Isolation: Issues in one store don't affect others
- Scalability: Easy to add new stores without code changes
- Security: Prevents data leakage between stores
Multi-store Best Practices
- Always Use Context: Never skip store context for multi-store operations
- Context Validation: Verify store context is set before operations
- Error Handling: Handle store-specific errors gracefully
- Performance: Batch operations by store when possible
- Monitoring: Track operations per store for monitoring
- Testing: Test with multiple store contexts
- Migration: Plan for store data migration scenarios
Usage Pattern
Configuration Webhook API Layer
The Configuration WebhookAPI layer in the SeQura integration-core library handles incoming webhook notifications from SeQura to synchronize all integration settings from Merchant portal, allowing faster support and removing the need to grant seQura integrators access to their e-commerce platform.
Overview
The Configuration WebhookAPI follows a simplified Controller pattern with validation, handling, and configuration synchronization to ensure reliable webhook processing even under high load or temporary system issues.
Core Components
1. Configuration WebhookAPI Main Class
- Purpose: Factory for accessing webhook handler with store context
- Pattern: Simple factory with store context aspect
- Key Method:
configurationHandler(string $storeId)- Returns configuration webhook controller with store context applied
2. ConfigurationWebhookController
- Purpose: Handles incoming configuration webhook requests from SeQura
- Key Method:
handleRequest(array $payload)- Validates and processes webhook payload - Response Strategy: Returns appropriate HTTP status codes as expected by SeQura
3. ConfigurationWebhookValidationService
- Purpose: Validates configuration webhook authenticity and content
- Validation Steps:
- Validate signature: Signature is required and must match the signature of the SeQura integration stored securely in the database
4. TopicHandlerRegistry
- Purpose: Registry for storing topic handlers
- Key Method:
register(string $topic, TopicHandlerInterface $handler)- Registers topic handler for a specific topic - Topic Handlers: Each topic handler, registered in Bootstrap can be overridden in integration if necessary, handles a specific webhook topic:
- GetAdvancedSettingsHandler: Handles
get-advanced-settingswebhook topic - SaveAdvancedSettingsHandler: Handles
save-advanced-settingswebhook topic - GetGeneralSettingsHandler: Handles
get-general-settingswebhook topic - SaveGeneralSettingsHandler: Handles
save-general-settingswebhook topic - GetLogContentHandler: Handles
get-log-contentwebhook topic - RemoveLogContentHandler: Handles
remove-log-contentwebhook topic - GetOrderStatusListHandler: Handles
get-order-status-listwebhook topic - GetOrderStatusSettingsHandler: Handles
get-order-status-settingswebhook topic - SaveOrderStatusSettingsHandler: Handles
save-order-status-settingswebhook topic - GetSellingCountriesHandler: Handles
get-selling-countrieswebhook topic - GetShopCategoriesHandler: Handles
get-shop-categorieswebhook topic - GetShopProductsHandler: Handles
get-shop-productswebhook topic - GetStoreInfoHandler: Handles
get-store-infowebhook topic - SaveWidgetSettingsHandler: Handles
save-widget-settingswebhook topic
- GetAdvancedSettingsHandler: Handles
Webhook Processing Flow
SeQura API Proxy Layer
The SeQura API Proxy Layer provides a robust, authenticated communication layer between the integration and SeQura's APIs. It handles authentication, request formatting, response parsing, and error management for all SeQura API interactions.
Overview
The API proxy system follows a Proxy Pattern with Factory-based authentication and HTTP abstraction to provide reliable, secure communication with SeQura's services while abstracting the complexity of API authentication and request management.
Core Components
1. BaseProxy
- Purpose: Foundation for all API communication
- Features: HTTP client abstraction, error handling, request/response formatting
- Environment Support: Automatic sandbox/live environment switching
2. AuthorizedProxy
- Purpose: Handles authenticated requests with merchant credentials
- Authentication: Basic auth with base64 encoding + merchant ID headers
- Security: Automatic credential management and token generation
3. AuthorizedProxyFactory
- Purpose: Creates authenticated proxy instances
- Dependencies: Connection service, deployment service, HTTP client
- Validation: Ensures valid credentials and deployment configuration
4. Specialized Proxies
- OrderProxy: Order creation, updates, payment methods
- MerchantProxy: Merchant information and configuration
- OrderReportProxy: Delivery and statistical reporting
- ConnectionProxy: Authentication and connection testing
API Proxy Implementation
Here's how to implement and use the SeQura API proxy system:
Proxy Factory Implementation
Custom factory for creating authenticated proxies:
Error Handling and Retry Logic
Robust error handling for API communication:
API Monitoring and Health Checks
Monitor API health and performance:
Key Benefits of the API Proxy Layer
- Authentication Management: Automatic credential handling and token generation
- Environment Abstraction: Seamless sandbox/live environment switching
- Error Handling: Comprehensive error catching and retry logic
- Request/Response Formatting: Automatic data transformation
- Security: Secure credential storage and transmission
- Monitoring: Built-in performance and health monitoring
- Extensibility: Easy to add new API endpoints and features
- Reliability: Retry mechanisms and graceful degradation
API Proxy Best Practices
- Error Handling: Always handle API exceptions appropriately
- Retry Logic: Implement exponential backoff for transient errors
- Caching: Cache proxy instances and responses when appropriate
- Monitoring: Track API performance and error rates
- Security: Never log sensitive authentication data
- Environment Management: Use correct environment for each operation
- Rate Limiting: Respect API rate limits and implement throttling
Usage Pattern
π§© Customization and Extensibility
The Customization and Extensibility system allows developers to extend, modify, and customize the SeQura integration-core library to meet specific platform requirements, business logic, and integration scenarios. This section provides comprehensive examples of how to extend the core library for your specific e-commerce platform.
Extension Architecture Overview
The integration-core follows SOLID principles and uses dependency injection patterns that make it highly extensible through:
- Service Registration: Custom implementations of core interfaces
- Event-Driven Architecture: Hooks for custom business logic
- Repository Pattern: Custom data persistence implementations
- Plugin System: Modular extensions without core modifications
- Configuration Override: Platform-specific configuration management
Core Extension Points
The library provides several key extension points where developers can inject custom functionality:
- Service Implementations: Custom business logic services
- Repository Implementations: Platform-specific data persistence
- Event Handlers: Custom responses to integration events
- API Transformers: Custom data transformation logic
- Configuration Providers: Platform-specific configuration
- Task Implementations: Custom background processing
- Proxy Extensions: Custom API communication patterns
Service Registration and Custom Implementations
To extend and override core services, you can register custom implementations in your Bootstrap after calling the parent method and using the same identifier in the BootstrapComponent.
Example of registering a custom service:
All versions of integration-core with dependencies
ext-json Version *
ext-ctype Version *
ext-mbstring Version *