Files
alfa-bank-sdk/README_FULL_GUIDE.md
2026-01-18 22:00:02 +03:00

179 lines
5.3 KiB
Markdown

# Alfa Bank SDK: The Comprehensive Guide
## 1. Introduction
This SDK provides a unified, strictly-typed PHP interface for the Alfa Bank API. It covers both **Bank-as-a-Service (BaaS)** and **Faster Payments System (SBP)** protocols.
**Key Technologies:**
- **Saloon v3**: Handles HTTP transport, retries, and plugins.
- **Spatie Laravel Data**: Provides Data Transfer Objects (DTOs) for strict typing.
- **OpenSSL**: Manages GOST/RSA signatures and encryption.
---
## 2. Installation & Configuration
### 2.1 Install via Composer
```bash
composer require apoloz/alfa-bank-sdk
```
### 2.2 Laravel Setup
Publish the configuration file:
```bash
php artisan vendor:publish --tag=alfa-bank-config
```
Configure your `.env` file. **Crucially, you need separate keys for Transport (mTLS) and Signing (Business Logic).**
```env
# 1. Transport Security (mTLS) - Required for connection
ALFA_BAAS_CERT_PATH=/path/to/transport.cer
ALFA_BAAS_KEY_PATH=/path/to/transport.key
# 2. Business Logic Signing (CMS/PKCS#7) - Required for creating payments/registries
ALFA_BAAS_SIGNING_CERT_PATH=/path/to/signing.cer
ALFA_BAAS_SIGNING_KEY_PATH=/path/to/signing.key
# 3. Credentials
ALFA_BAAS_CLIENT_ID=your-client-id
ALFA_BAAS_CLIENT_SECRET=your-client-secret
ALFA_BAAS_ENV=sandbox
```
---
## 3. Core Concepts
### 3.1 Facades (Laravel)
Use the facades for clean, static access.
- `AlfaBank`: Access BaaS endpoints (Payments, Accounts, Salary).
- `Sbp`: Access SBP endpoints (QR Codes, C2B/B2C).
### 3.2 DTOs (Data Transfer Objects)
Never pass raw arrays. Use DTOs to ensure your data is valid before it leaves your server.
**Example:**
```php
use Apoloz\AlfaBank\Data\Payments\PaymentData;
$payment = new PaymentData(
amount: 100.00,
payerName: 'My Company',
// ... mandatory fields are enforced here
);
```
### 3.3 Pagination
Iterate through large lists effortlessly.
```php
use Apoloz\AlfaBank\Requests\Statement\GetTransactionsRequest;
$paginator = AlfaBank::paginate(new GetTransactionsRequest($accountNumber));
foreach ($paginator as $transaction) {
// $transaction is a strictly typed DTO
echo $transaction->amount;
}
```
---
## 4. Advanced Security
### 4.1 SBP Body Signing
The SDK handles the complex JSON Canonicalization (JCS) and RSA-SHA256 signing required by the SBP protocol automatically in the `SbpConnector`.
### 4.2 Webhook Verification
To handle webhooks securely:
1. Define a route using the macro:
```php
Route::alfaWebhooks('/api/webhooks/alfa');
```
2. Listen for the `AlfaWebhookReceived` event.
3. The SDK middleware verifies the authenticity of the request.
---
## 5. Troubleshooting
### "Interface not found"
Ensure you have run `composer update` to install `saloonphp/pagination-plugin`.
### "Certificate not found"
Check your `.env` paths. The files must be readable by the PHP process (usually `www-data`).
### "Invalid Signature"
Ensure you are using the correct **Signing Key** (not the Transport key) for business logic operations like `CmsSigner::sign()`.
---
## 6. Architecture & Data Flow
This section visualizes how data moves through the SDK, explaining the invisible work performed by the library (Security, Serialization, Transport).
### 6.1 General Request Lifecycle (BaaS)
When you send a request (e.g., creating a payment), the SDK automatically handles DTO serialization, mTLS authentication, and response mapping.
```mermaid
sequenceDiagram
participant User as Client App
participant SDK as SDK Facade
participant DTO as Request DTO
participant Con as Connector
participant API as Alfa Bank API
User->>DTO: Instantiate (Strict Typing)
User->>SDK: send(Request)
SDK->>Con: Serialize DTO to JSON
Con->>Con: Attach mTLS Certificates
Con->>Con: Attach OAuth Token
Con->>API: HTTPS Request (Signed/Encrypted)
API-->>Con: Raw JSON Response
Con->>SDK: Map JSON to Response DTO
SDK-->>User: Return Response Object
```
### 6.2 SBP Body Signing (JCS)
The Faster Payments System (SBP) requires a specific "Body Signing" mechanism. The SDK implements **JSON Canonicalization Scheme (JCS)** to ensure the signature is valid regardless of key order.
```mermaid
flowchart TD
A["Raw Request Body (Array)"] -->|CmsSigner::canonicalize| B("Recursive Key Sort & JSON Encode")
B -->|"OpenSSL RSA-SHA256"| C{"Sign with Private Key"}
C -->|"Base64 Encode"| D["Signature String"]
D -->|"Add Header"| E["Authorization: Base64"]
E -->|"mTLS Connection"| F(("Alfa Bank SBP Gateway"))
style B fill:#f9f,stroke:#333,stroke-width:2px
style C fill:#bbf,stroke:#333,stroke-width:2px
```
### 6.3 Webhook Processing
The SDK acts as a secure gatekeeper for incoming webhooks, verifying their origin before dispatching them to your application logic.
```mermaid
sequenceDiagram
participant Bank as Alfa Bank
participant Route as Laravel Route
participant Mid as Middleware
participant Factory as WebhookFactory
participant Event as AlfaWebhookReceived
Bank->>Route: POST /webhooks/alfa
Route->>Mid: Intercept Request
Mid->>Mid: Verify Credentials / Signature
alt Invalid
Mid-->>Bank: 401 Unauthorized
else Valid
Mid->>Factory: Extract Payload
Factory->>Factory: Detect Type (BaaS vs SBP)
Factory->>Event: Dispatch Typed DTO
Event-->>Route: Processing Complete
Route-->>Bank: 200 OK
end
```
---
*Generated by Alfa Bank SDK Team*