Files
alfa-bank-sdk/README.md
2026-01-18 23:53:31 +03:00

5.5 KiB

Alfa Bank SDK (Unofficial)

This is an unofficial PHP SDK for the Alfa Bank API, built using Saloon and Spatie Laravel Data.

Requirements

Installation

composer require apoloz/alfa-bank-sdk

Architecture & Data Flow

The SDK abstracts complex banking protocols into a clean, object-oriented interface.

1. Unified Request Architecture

Every request follows a strict "Input DTO -> Request -> Connector -> Output DTO" pipeline.

graph LR
    User[Client App] --> DTO_IN[Request DTO]
    DTO_IN --> REQ[Request Class]
    REQ --> CON[Connector]
    CON -->|mTLS + Signature| API((Alfa Bank))
    API -->|Raw JSON| CON
    CON --> REQ
    REQ -->|Data Mapping| DTO_OUT[Response DTO/Collection]
    DTO_OUT --> User
    
    style CON fill:#f96,stroke:#333,stroke-width:2px
    style DTO_IN fill:#bbf,stroke:#333
    style DTO_OUT fill:#9f6,stroke:#333

2. Authentication & Security Flow (BaaS)

The BaaS API requires a two-step handshake: mTLS for the tunnel and OAuth 2.0 for authorization.

sequenceDiagram
    participant App as Client Application
    participant SDK as AlfaBank SDK
    participant API as Alfa Bank Gateway

    Note over App, API: 1. Connection (mTLS)
    SDK->>API: Client Hello (X.509 Certificate)
    API-->>SDK: Server Hello & Encrypted Tunnel established

    Note over App, API: 2. Authorization (OAuth 2.0)
    App->>SDK: login(id, secret)
    SDK->>API: POST /token (Client Credentials)
    API-->>SDK: Access Token (JWT)
    SDK->>SDK: Store Token in Authenticator

    Note over App, API: 3. Business Requests
    App->>SDK: send(CreatePaymentRequest)
    SDK->>API: POST /payments (Header: Bearer Token)
    API-->>SDK: 201 Created

3. SBP Security (JCS & Body Signing)

Unlike BaaS, SBP requires signing the actual JSON body using a recursive key-sorting algorithm (JCS).

flowchart TD
    A["Raw Data (Array)"] -->|Recursive ksort| B("Canonical Array")
    B -->|JSON_UNESCAPED_UNICODE| C("JCS JSON String")
    C -->|RSA-SHA256 Sign| D("Binary Signature")
    D -->|Base64 Encode| E["'Authorization' Header"]
    E -->|HTTPS + mTLS| F((Alfa Bank SBP Gateway))
    
    subgraph SDK Automatics
    B
    C
    D
    end

4. Webhook Pipeline (Laravel Integration)

The SDK acts as a security firewall for incoming bank notifications.

sequenceDiagram
    participant Bank as Alfa Bank
    participant Mid as VerifyAlfaWebhook (Middleware)
    participant Fact as WebhookFactory
    participant Event as AlfaWebhookReceived (Event)
    participant Listener as Your Listener

    Bank->>Mid: POST /webhooks/alfa
    Mid->>Mid: 1. Validate Credentials
    alt Authorized
        Mid->>Fact: 2. Parse Raw JSON
        Fact->>Fact: 3. Detect Type (BaaS/SBP)
        Fact->>Event: 4. Dispatch(Typed DTO)
        Event->>Listener: 5. Handle Business Logic
        Mid-->>Bank: 200 OK
    else Unauthorized
        Mid-->>Bank: 401 Unauthorized
    end

Security & Setup (Crucial)

Alfa Bank uses a comprehensive security model requiring two distinct sets of keys:

  1. Transport (mTLS): To establish the SSL connection.
  2. Signing (JWS/CMS): To digitally sign the request body.

Where to get keys?

  • Sandbox: Provided by the bank support or downloaded from the Developer Portal.
  • Production:
    • Transport (mTLS): Generate a private key and CSR using OpenSSL. Send the CSR to alfa_api@alfabank.ru.
    • Signing: Generated by you (the client). Register the public certificate in "Alfa Business Online".

1. Converting PFX to PEM

If the bank provided a .pfx file for signing, convert it to PEM:

# Extract Private Key
openssl pkcs12 -in signing.pfx -nocerts -out signing_key.pem -nodes

# Extract Public Certificate
openssl pkcs12 -in signing.pfx -clcerts -nokeys -out signing_cert.pem

2. Initialization

use Apoloz\AlfaBank\AlfaBank;
use Apoloz\AlfaBank\Enums\Environment;

$baas = AlfaBank::baas(
    certificatePath: '/path/to/transport_cert.pem', 
    privateKeyPath: '/path/to/transport_key.pem',
    signingCertificatePath: '/path/to/signing_cert.pem',
    signingPrivateKeyPath: '/path/to/signing_key.pem',
    environment: Environment::SANDBOX
);

Core Usage

Making Requests

SBP: Generate QR Code

use Apoloz\AlfaBank\Sbp\Requests\GetQrCodeRequest;
use Apoloz\AlfaBank\Sbp\Data\QrCodeRequestData;

$response = $sbp->send(new GetQrCodeRequest(
    new QrCodeRequestData(TermNo: '...', amount: '100')
));

$link = $response->dto()->payload;

Standard Payments

use Apoloz\AlfaBank\Requests\Payments\CreatePaymentRequest;
use Apoloz\AlfaBank\Data\Payments\PaymentData;

$payload = new PaymentData(amount: 100.50, ...);
$response = $baas->send(new CreatePaymentRequest($payload));
echo $response->dto()->id;

Advanced Features

Pagination

The SDK supports automatic pagination for all list endpoints:

use Apoloz\AlfaBank\Requests\Accounts\GetAccountsRequest;

$paginator = $baas->paginate(new GetAccountsRequest());

foreach ($paginator->items() as $account) {
    echo $account->number; // Typed AccountData object
}

Diagnostics

Run the built-in Artisan command to verify your configuration:

php artisan alfa:check

License

MIT