feat: Add Laravel tinker examples and update nominal accounts functionality

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
This commit is contained in:
2026-01-24 23:40:20 +03:00
parent 0e66eb2859
commit fdb400d5f0
24 changed files with 571 additions and 111 deletions

View File

@@ -7,56 +7,42 @@ use Apoloz\AlfaBank\Enums\Environment;
use Apoloz\AlfaBank\Requests\NominalAccounts\Beneficiaries\CreateBeneficiaryRequest;
use Apoloz\AlfaBank\Data\NominalAccounts\Beneficiaries\CreateBeneficiaryRequestData;
use Apoloz\AlfaBank\Data\NominalAccounts\Beneficiaries\AddressData;
use Apoloz\AlfaBank\Data\NominalAccounts\Payouts\DigestSignatureData;
use Spatie\LaravelData\DataCollection;
/**
* Example: Creating a Beneficiary for a Nominal Account.
* This flow requires a digital signature (CMS).
*/
// 1. Initialize
// In Laravel Tinker: $baas = app(\Apoloz\AlfaBank\Core\AlfaBankConnector::class);
// In Standalone:
$baas = AlfaBank::baas(
certificatePath: 'path/to/cert.pem',
privateKeyPath: 'path/to/key.pem',
environment: Environment::SANDBOX
certificatePath: __DIR__ . '/certs/client.cer',
privateKeyPath: __DIR__ . '/certs/private.key',
environment: Environment::SANDBOX,
clientId: getenv('ALFA_BAAS_CLIENT_ID'),
clientSecret: getenv('ALFA_BAAS_CLIENT_SECRET')
);
// 1. Prepare beneficiary data
// 2. Auth
// $baas->login(); // Or refresh token logic
// 3. Prepare Payload
$payload = new CreateBeneficiaryRequestData(
type: 'FL_RESIDENT',
countryOfTaxResidence: 'RU',
name: 'Ivanov Ivan Ivanovich',
inn: '771234567890',
addresses: AddressData::collect([
[
'type' => 'REGISTRATION_ADDRESS',
'address' => 'Moscow, Lenina st, 10',
'country' => 'RU'
]
], DataCollection::class),
digestSignatures: DigestSignatureData::collect([
[
'base64Encoded' => 'MOCK_SIGNATURE', // In real life, use CmsSigner::sign()
'signatureType' => 'cms'
]
], DataCollection::class)
name: 'Ivanov Ivan',
addresses: new DataCollection(AddressData::class, [
new AddressData('REGISTRATION_ADDRESS', 'Moscow', 'RU')
])
// Note: digestSignatures is now optional!
);
// 2. Login and send request
// For Nominal Accounts, use H2H Auth (Refresh Token)
// See examples/13_h2h_auth_service.php for setting this up.
// CREDENTIALS SOURCE:
// - client-id: Developer Portal -> App -> Overview
// - client-secret: Developer Portal -> App -> Keys (Click Eye Icon) OR SDK Generator
$auth = AlfaBank::auth(
'client-id', 'client-secret', 'https://callback',
'path/to/cert.pem', 'path/to/key.pem', Environment::SANDBOX
);
$auth->refreshToken('saved-refresh-token'); // Authenticates the connector
// 4. Sign Payload (New DX!)
$payload->sign($baas->getSigner());
// 5. Send
$response = $baas->send(new CreateBeneficiaryRequest($payload));
echo "Status: " . $response->status() . "\n";
echo "ID: " . $response->dto()->id . "\n";
if ($response->successful()) {
$data = $response->dto(); // BeneficiaryResponseData
echo "Beneficiary creation accepted. ID: {$data->id}, Status: {$data->status}\n";

View File

@@ -45,30 +45,23 @@ try {
$auth->refreshToken('saved_refresh_token_from_db');
// --- ЭТАП 1: Создание Бенефициара (Контрагента) ---
echo "1. Регистрация бенефициара...\n";
$beneficiaryData = new CreateBeneficiaryRequestData(
$benData = new CreateBeneficiaryRequestData(
type: 'FL_RESIDENT',
countryOfTaxResidence: 'RU',
name: 'Иванов Иван',
addresses: AddressData::collect([
['type' => 'REGISTRATION_ADDRESS', 'address' => 'г. Москва, ул. Ленина 1', 'country' => 'RU']
], DataCollection::class),
digestSignatures: DigestSignatureData::collect([
[
'base64Encoded' => CmsSigner::sign('Data to sign', $signCert, $signKey),
'signatureType' => 'cms'
]
], DataCollection::class),
name: 'Иванов Иван Иванович',
inn: '771234567890'
new AddressData('REGISTRATION_ADDRESS', 'Moscow', 'RU')
])
);
// Автоматическая подпись
$benData->sign($baas->getSigner());
$response = $baas->send(new CreateBeneficiaryRequest($benData));
$beneficiaryId = $response->dto()->id;
echo "Beneficiary Created: $beneficiaryId\n";
$response = $baas->send(new CreateBeneficiaryRequest($beneficiaryData));
$beneficiaryId = $response->dto()->requestId; // В некоторых версиях API возвращается UUID
echo "Бенефициар создан. ID запроса: $beneficiaryId\n";
// --- ЭТАП 2: Верификация (Скоринг) ---
// --- ЭТАП 2: Идентификация Входящего Платежа ---
// После создания банк должен проверить бенефициара
echo "2. Запуск верификации (скоринга)...";
$baas->send(new ScoreBeneficiaryRequest($beneficiaryId));

View File

@@ -11,6 +11,10 @@ use Apoloz\AlfaBank\Requests\NominalAccounts\Beneficiaries\GetBeneficiariesReque
/**
* FINAL GOAL EXAMPLE: Get List of Nominal Account Beneficiaries
*
* Usage:
* 1. Standalone: php examples/15_nominal_accounts_list.php
* 2. Laravel Tinker: Copy-paste the code below (replace config with app() helper).
*
* This script assumes you have already:
* 1. Generated/Received Certificates.
* 2. Obtained Client ID & Secret (via Portal or Script 14).

View File

@@ -0,0 +1,96 @@
<?php
/**
* LARAVEL TINKER WORKFLOW: Scoring -> Creation -> Signing
*
* This script is designed to be copy-pasted directly into `php artisan tinker`.
* It demonstrates the new simplified DX with automatic signing.
*
* Prerequisites:
* 1. .env is configured (ALFA_BAAS_CLIENT_ID, ALFA_BAAS_CERT_PATH, etc.)
* 2. Run: php artisan tinker
*/
use Apoloz\AlfaBank\Core\AlfaBankConnector;
use Apoloz\AlfaBank\Requests\NominalAccounts\Beneficiaries\ScoreBeneficiaryRequest;
use Apoloz\AlfaBank\Data\NominalAccounts\Beneficiaries\ScoreBeneficiaryRequestData;
use Apoloz\AlfaBank\Requests\NominalAccounts\Beneficiaries\CreateBeneficiaryRequest;
use Apoloz\AlfaBank\Data\NominalAccounts\Beneficiaries\CreateBeneficiaryRequestData;
use Apoloz\AlfaBank\Data\NominalAccounts\Beneficiaries\AddressData;
// 1. Get Configured Connector
// Laravel automatically injects config from config/alfa-bank.php
$baas = app(AlfaBankConnector::class);
// 2. Authenticate
// Uses Client Credentials (if configured) or Refresh Token logic if you have one.
// For server-to-server tasks, login() is usually sufficient.
echo "Logging in...\n";
$baas->login();
// --- STEP A: SCORING (Check if we can work with this person) ---
echo "--- Step A: Scoring ---\n";
$scoreData = new ScoreBeneficiaryRequestData(
type: 'FL_RESIDENT',
inn: '771234567890',
name: 'Иванов Иван Иванович'
);
try {
$scoreResponse = $baas->send(new ScoreBeneficiaryRequest($scoreData));
$scoreResult = $scoreResponse->dto(); // ScoreBeneficiaryResponseData
echo "Scoring Result: " . $scoreResult->result . "\n";
echo "Description: " . $scoreResult->description . "\n";
if ($scoreResult->result !== 'SUCCESS') {
echo "Stopping: Scoring failed.\n";
return;
}
} catch (\Exception $e) {
echo "Scoring Error: " . $e->getMessage() . "\n";
return;
}
// --- STEP B: CREATION (With Automatic Signing) ---
echo "\n--- Step B: Creation ---\n";
$createData = new CreateBeneficiaryRequestData(
type: 'FL_RESIDENT',
countryOfTaxResidence: 'RU',
name: 'Иванов Иван Иванович', // Must match scoring
inn: '771234567890',
phoneNumber: '79001234567',
email: 'ivanov@example.com',
addresses: AddressData::collect([
new AddressData(
type: 'REGISTRATION_ADDRESS',
address: '123456, г. Москва, ул. Тверская, д. 1',
country: 'RU'
)
])
);
// MAGIC HAPPENS HERE:
// Automatically signs the JSON payload using the connector's certificates.
echo "Signing data...\n";
$createData->sign($baas->getSigner());
try {
$createResponse = $baas->send(new CreateBeneficiaryRequest($createData));
$beneficiary = $createResponse->dto(); // CreateBeneficiaryResponseData
echo "SUCCESS! Beneficiary Created.\n";
echo "ID: " . $beneficiary->id . "\n";
echo "Status: " . $beneficiary->status . "\n";
echo "Request ID: " . $beneficiary->requestId . "\n";
} catch (\Exception $e) {
echo "Creation Error: " . $e->getMessage() . "\n";
if (method_exists($e, 'getResponse')) {
echo "Response Body: " . $e->getResponse()->body() . "\n";
}
}

View File

@@ -0,0 +1,102 @@
use Apoloz\AlfaBank\Data\NominalAccounts\Identification\AmountDistributionData;
use Apoloz\AlfaBank\Requests\NominalAccounts\Payouts\PayoffRequest;
use Apoloz\AlfaBank\Data\NominalAccounts\Payouts\PayoffRequestData;
use Apoloz\AlfaBank\Data\Common\RecipientData;
use Apoloz\AlfaBank\Data\NominalAccounts\Payouts\PayoutRequisiteData;
use Apoloz\AlfaBank\Services\PhpseclibCardEncryptor;
use Spatie\LaravelData\DataCollection;
// --- CONFIGURATION ---
// Replace these with real data from your system/webhook
$nominalAccount = '40702810...'; // Ваш Номинальный счет
$transactionId = '1220112MOCO...'; // ID входящего платежа (из Вебхука или Выписки)
$beneficiaryId = 'BEN-8d4a...'; // ID Бенефициара (которого создали в примере 17)
$amount = '100.00'; // Сумма операции (в рублях)
// Public key for CARD encryption (Download from Bank Portal)
$cardPublicKeyPath = storage_path('certs/alfa_card_enc_key.pub');
// 1. Setup Connector
$baas = app(AlfaBankConnector::class);
$baas->login();
echo "Connector ready.\n";
// ==========================================
// STEP 1: IDENTIFICATION (Assign funds to Beneficiary)
// ==========================================
echo "\n--- Step 1: Identification ---\n";
$identifyData = new IdentifyRequestData(
transactionId: $transactionId,
accountNumber: $nominalAccount,
amountDistribution: AmountDistributionData::collect([
[
'beneficiaryId' => $beneficiaryId,
'amount' => $amount
]
], DataCollection::class)
);
// Automatic Signing
$identifyData->sign($baas->getSigner());
try {
$idResponse = $baas->send(new IdentifyTransactionRequest($identifyData));
echo "Identification Status: " . $idResponse->status() . "\n";
echo "Funds assigned to beneficiary.\n";
} catch (\Exception $e) {
echo "Identification Failed: " . $e->getMessage() . "\n";
}
// ==========================================
// STEP 2: PAYOUT (Withdraw to Bank Card)
// ==========================================
echo "\n--- Step 2: Payout (Card) ---\n";
// A. Encrypt the Card Number (PAN)
// This is required for security. The raw PAN is never sent.
if (!file_exists($cardPublicKeyPath)) {
echo "Error: Card Encryption Key not found at $cardPublicKeyPath\n";
return;
}
$encryptor = new PhpseclibCardEncryptor(file_get_contents($cardPublicKeyPath));
$encryptedPan = $encryptor->encrypt('2200000000000000'); // Real PAN here
echo "PAN Encrypted.\n";
// B. Prepare Payout Request
$payoutData = new PayoffRequestData(
type: 'FL_RESIDENT',
accountNumber: $nominalAccount,
recipient: new RecipientData($beneficiaryId),
amount: $amount,
purpose: 'Выплата средств по договору оферты',
// Direct details (Bank Card / PAN)
payoutRequisite: new PayoutRequisiteData(
type: 'CARD',
pan: $encryptedPan
)
);
// C. Sign and Send
echo "Signing payout request...\n";
$payoutData->sign($baas->getSigner());
try {
$payResponse = $baas->send(new PayoffRequest($payoutData));
$result = $payResponse->dto();
echo "Payout Initiated!\n";
echo "Transaction ID: " . ($result->id ?? 'N/A') . "\n";
echo "Status: " . ($result->status ?? 'PENDING') . "\n";
} catch (\Exception $e) {
echo "Payout Failed: " . $e->getMessage() . "\n";
if (method_exists($e, 'getResponse')) {
echo "Details: " . $e->getResponse()->body() . "\n";
}
}

View File

@@ -0,0 +1,107 @@
<?php
/**
* LARAVEL TINKER WORKFLOW: Secure Card Registration -> Payout by ID
*
* Scenario:
* 1. User enters Card Number (PAN).
* 2. You encrypt PAN and register it as a "Requisite" in Alfa Bank.
* 3. You save only the `requisiteId` in your database.
* 4. Later, you pay out to this user using only the ID (Zero PAN storage).
*
* Usage: Copy-paste into `php artisan tinker`.
*/
use Apoloz\AlfaBank\Core\AlfaBankConnector;
use Apoloz\AlfaBank\Requests\NominalAccounts\Beneficiaries\Requisites\CreateRequisiteRequest;
use Apoloz\AlfaBank\Data\NominalAccounts\Beneficiaries\Requisites\CreateRequisiteRequestData;
use Apoloz\AlfaBank\Requests\NominalAccounts\Payouts\PayoffRequest;
use Apoloz\AlfaBank\Data\NominalAccounts\Payouts\PayoffRequestData;
use Apoloz\AlfaBank\Data\Common\RecipientData;
use Apoloz\AlfaBank\Data\NominalAccounts\Payouts\PayoutRequisiteData;
use Apoloz\AlfaBank\Services\PhpseclibCardEncryptor;
// --- CONFIGURATION ---
$nominalAccount = '40702810...';
$beneficiaryId = 'BEN-123...';
$rawPan = '4276000000001234'; // Вводится пользователем (не сохранять в БД!)
$cardPubKeyPath = storage_path('certs/alfa_card_enc_key.pub');
// 1. Setup
$baas = app(AlfaBankConnector::class);
$baas->login();
// ==========================================
// STEP 1: SECURE REGISTRATION (Tokenization)
// ==========================================
echo "--- Step 1: Registering Card Requisite ---
";
// A. Encrypt PAN for transport
$encryptor = new PhpseclibCardEncryptor(file_get_contents($cardPubKeyPath));
$encryptedPan = $encryptor->encrypt($rawPan);
// B. Request Creation of Requisite in Alfa Bank
$reqData = new CreateRequisiteRequestData(
type: 'CARD',
pan: $encryptedPan,
beneficiaryId: $beneficiaryId,
isMain: true
);
$reqData->sign($baas->getSigner());
try {
$reqResponse = $baas->send(new CreateRequisiteRequest($reqData));
$requisiteId = $reqResponse->dto()->id; // E.g. "REQ-998877"
echo "SUCCESS! Card Registered.
";
echo "Requisite ID: $requisiteId (SAVE THIS TO DATABASE)
";
echo "Mask: " . substr($rawPan, 0, 6) . "******" . substr($rawPan, -4) . "
";
} catch (\Exception $e) {
echo "Registration Failed: " . $e->getMessage() . "
";
return;
}
// ==========================================
// STEP 2: PAYOUT (Using Requisite ID)
// ==========================================
echo "\n--- Step 2: Payout using Requisite ID ---
";
// Now we don't need PAN anymore. We use the ID we just got.
$payoutData = new PayoffRequestData(
type: 'FL_RESIDENT',
accountNumber: $nominalAccount,
recipient: new RecipientData($beneficiaryId),
amount: '100.00',
purpose: 'Выплата вознаграждения',
// Instead of PAN, we provide the Requisite ID
payoutRequisite: new PayoutRequisiteData(
type: 'CARD',
requisiteId: $requisiteId
)
);
$payoutData->sign($baas->getSigner());
try {
$payResponse = $baas->send(new PayoffRequest($payoutData));
$result = $payResponse->dto();
echo "Payout Sent!
";
echo "ID: " . ($result->id ?? 'N/A') . "
";
} catch (\Exception $e) {
echo "Payout Failed: " . $e->getMessage() . "
";
}

38
examples/README.md Normal file
View File

@@ -0,0 +1,38 @@
# Alfa Bank SDK Examples
This directory contains executable PHP scripts demonstrating various features of the SDK.
## How to Run
### 1. Standalone (CLI)
You can run any script directly from the terminal if you have PHP installed.
Ensure you have run `composer install` in the SDK root first.
```bash
cd alfa-bank-sdk
php examples/01_baas_flow.php
```
### 2. Laravel Tinker
Most examples are designed to be copy-paste friendly for `php artisan tinker`.
**General Steps:**
1. Open your Laravel project terminal.
2. Run `php artisan tinker`.
3. Instead of the manual `AlfaBank::baas(...)` initialization, use the Laravel helper:
```php
$baas = app(\Apoloz\AlfaBank\Core\AlfaBankConnector::class);
$baas->login(); // Or refresh token
```
4. Copy the rest of the logic (DTO creation, signing, sending) from the example file.
**Dedicated Tinker Workflow:**
See `17_laravel_tinker_scoring_creation.php` for a complete, copy-paste ready workflow for creating beneficiaries.
## Key Examples
- **01_baas_flow.php**: Basic setup and connection check.
- **13_h2h_auth_service.php**: How to get your first OAuth token.
- **14_generate_client_secret.php**: If you lost your Client Secret.
- **15_nominal_accounts_list.php**: Fetching lists (Beneficiaries).
- **17_laravel_tinker_scoring_creation.php**: **START HERE** for Nominal Accounts integration.