### Install creagia/redsys-php via Composer Source: https://github.com/creagia/redsys-php/blob/main/README.md Install the package using Composer. Run this command in your project root. ```bash composer require creagia/redsys-php ``` -------------------------------- ### Usage Example Source: https://github.com/creagia/redsys-php/blob/main/_autodocs/api-reference/request-parameters.md Example of creating a RequestParameters instance, setting merchant code and terminal, and using toArray() and toEncodedString(). ```APIDOC ## Usage ### Description Example of creating a RequestParameters instance with various parameters, setting merchant code and terminal, and using toArray() and toEncodedString(). ### Example ```php use Creagia\Redsys\Enums\ConsumerLanguage; use Creagia\Redsys\Enums\Currency; use Creagia\Redsys\Enums\PayMethod; use Creagia\Redsys\Enums\TransactionType; use Creagia\Redsys\Support\RequestParameters; $params = new RequestParameters( amountInCents: 123_45, order: '22013100005', currency: Currency::EUR, transactionType: TransactionType::Autorizacion, consumerLanguage: ConsumerLanguage::Spanish, payMethods: PayMethod::Card, productDescription: 'Subscription', merchantUrl: 'https://example.com/redsysNotification', urlOk: 'https://example.com/paymentOk', urlKo: 'https://example.com/paymentKo', ); $params->merchantCode = '999008881'; // normally set by RedsysRequest::create() $params->terminal = 1; $array = $params->toArray(); // ['DS_MERCHANT_AMOUNT' => 12345, 'DS_MERCHANT_TRANSACTIONTYPE' => 0, // 'DS_MERCHANT_CURRENCY' => 978, 'DS_MERCHANT_ORDER' => '22013100005', ...] $encoded = $params->toEncodedString(); // base64 JSON for Ds_MerchantParameters ``` ``` -------------------------------- ### Basic Construction with Test Environment Source: https://github.com/creagia/redsys-php/blob/main/_autodocs/api-reference/redsys-client.md Example of initializing the client with the test environment and retrieving base URLs. ```php use Creagia\Redsys\Enums\Environment; use Creagia\Redsys\RedsysClient; $redsysClient = new RedsysClient( merchantCode: 999008881, secretKey: 'sq7HjrUOBfKmC576ILgskD5srU870gJ7', terminal: 1, environment: Environment::Test, ); echo $redsysClient->getBaseUrl(); // https://sis-t.redsys.es:25443/sis echo $redsysClient->getRestBaseUrl(); // https://sis-t.redsys.es:25443/sis/rest ``` -------------------------------- ### Custom Environment Configuration Source: https://github.com/creagia/redsys-php/blob/main/_autodocs/api-reference/redsys-client.md Example of initializing the client with a custom environment and handling potential configuration errors. ```php use Creagia\Redsys\Enums\Environment; use Creagia\Redsys\RedsysClient; try { $redsysClient = new RedsysClient( merchantCode: 999008881, secretKey: 'sq7HjrUOBfKmC576ILgskD5srU870gJ7', terminal: 1, environment: Environment::Custom, customBaseUrl: 'https://localGateway.test', ); } catch (\Exception $e) { // 'Redsys custom environment without custom URL defined' // thrown when Environment::Custom is used without customBaseUrl report($e); } ``` -------------------------------- ### Arr usage example Source: https://github.com/creagia/redsys-php/blob/main/_autodocs/api-reference/support.md Shows how to use Arr::blank() and Arr::filled() with various values, including expected boolean results. ```php use Creagia\Redsys\Support\Arr; Arr::blank(null); // true Arr::blank(''); // true Arr::blank(' '); // true Arr::blank(0); // false Arr::blank([1]); // false Arr::filled('x'); // true Arr::filled(''); // false ``` -------------------------------- ### Usage example: creating RequestParameters and encoding Source: https://github.com/creagia/redsys-php/blob/main/_autodocs/api-reference/request-parameters.md Shows how to instantiate RequestParameters with enums and properties, set merchantCode and terminal, convert to array, and encode to base64 JSON. The output array includes DS_MERCHANT_AMOUNT, DS_MERCHANT_TRANSACTIONTYPE, etc. ```php use Creagia\Redsys\Enums\ConsumerLanguage; use Creagia\Redsys\Enums\Currency; use Creagia\Redsys\Enums\PayMethod; use Creagia\Redsys\Enums\TransactionType; use Creagia\Redsys\Support\RequestParameters; $params = new RequestParameters( amountInCents: 123_45, order: '22013100005', currency: Currency::EUR, transactionType: TransactionType::Autorizacion, consumerLanguage: ConsumerLanguage::Spanish, payMethods: PayMethod::Card, productDescription: 'Subscription', merchantUrl: 'https://example.com/redsysNotification', urlOk: 'https://example.com/paymentOk', urlKo: 'https://example.com/paymentKo', ); $params->merchantCode = '999008881'; // normally set by RedsysRequest::create() $params->terminal = 1; $array = $params->toArray(); // ['DS_MERCHANT_AMOUNT' => 12345, 'DS_MERCHANT_TRANSACTIONTYPE' => 0, // 'DS_MERCHANT_CURRENCY' => 978, 'DS_MERCHANT_ORDER' => '22013100005', ...] $encoded = $params->toEncodedString(); // base64 JSON for Ds_MerchantParameters ``` -------------------------------- ### Usage - Reading notification data after verification Source: https://github.com/creagia/redsys-php/blob/main/_autodocs/api-reference/notification-parameters.md Example of reading notification data after verification using RedsysResponse and NotificationParameters. ```APIDOC ## Usage - Reading notification data after verification ### Description Example of reading notification data after verification using RedsysResponse and NotificationParameters. ### Code Example ```php use Creagia\Redsys\RedsysClient; use Creagia\Redsys\RedsysResponse; $notification = new RedsysResponse($redsysClient); $notification->setParametersFromResponse($_POST); try { $p = $notification->checkResponse(); $order = $p->order; // '22013100005' $amount = $p->amount; // 12345 (cents) $currency = $p->currency; // 978 $responseCode = $p->responseCode; // '0000' $authCode = $p->responseAuthorisationCode; $token = $p->merchantIdentifier; // COF token for storing $cofTxnId = $p->cofTransactionId; } catch (\Creagia\Redsys\Exceptions\DeniedRedsysPaymentResponseException $e) { // denied payment } ``` ``` -------------------------------- ### PostRequestError usage example Source: https://github.com/creagia/redsys-php/blob/main/_autodocs/api-reference/support.md Shows how to handle a PostRequestError from sendPostRequest(), including accessing code, message, and responseParameters, and falling back to checkResponse() for successful responses. ```php use Creagia\Redsys\Support\PostRequestError; $result = $redsysRequest->sendPostRequest(); if ($result instanceof PostRequestError) { // $result->code 'SIS0001' // $result->message 'Error Interno' // $result->responseParameters raw body abort(402, "Payment failed: {$result->code} {$result->message}"); } // otherwise $result is a RedsysResponse — verify it $notification = $result->checkResponse(); ``` -------------------------------- ### Usage with custom DTO Source: https://github.com/creagia/redsys-php/blob/main/_autodocs/api-reference/data-transfer-object.md Shows how to use EnumCaster with a custom DTO. The example defines an enum Status and a MyDto class with attributes for mapping and casting. It demonstrates creating a DTO from an array with case-insensitive keys, accessing the casted enum property, and converting back to an array with the mapped field names. ```php use Creagia\Redsys\Support\DataTransferObject\CastWith; use Creagia\Redsys\Support\DataTransferObject\Casters\EnumCaster; use Creagia\Redsys\Support\DataTransferObject\DataTransferObject; use Creagia\Redsys\Support\DataTransferObject\MapFrom; use Creagia\Redsys\Support\DataTransferObject\MapTo; enum Status: string { case Active = 'A'; case Inactive = 'I'; } class MyDto extends DataTransferObject { public function __construct( #[MapTo('FIELD_ONE')] #[MapFrom('FIELD_ONE')] public string $fieldOne, #[MapTo('FIELD_STATUS')] #[MapFrom('FIELD_STATUS')] #[CastWith(EnumCaster::class, Status::class)] public ?Status $status = null, ) {} } $dto = MyDto::fromArray(['field_status' => 'A']); // case-insensitive keys by default $dto->status === Status::Active; // true, auto-cast $dto->toArray(); // ['FIELD_ONE' => ..., 'FIELD_STATUS' => 'A'] ``` -------------------------------- ### Constructor: new RedsysClient() Source: https://github.com/creagia/redsys-php/blob/main/_autodocs/api-reference/redsys-client.md Creates a new RedsysClient instance with merchant credentials and environment configuration. Throws an exception if custom environment is used without a custom base URL. ```APIDOC ## Constructor: new RedsysClient() ### Description Creates a new RedsysClient instance with merchant credentials and environment configuration. Throws an exception if custom environment is used without a custom base URL. ### Method Constructor ### Endpoint N/A (PHP class constructor) ### Parameters #### Constructor Parameters - **merchantCode** (int) - Required - Merchant (FUC) code assigned by Redsys. - **secretKey** (string) - Required - HMAC secret key provided by Redsys. - **terminal** (int) - Required - Terminal number. - **environment** (Environment) - Required - Environment::Test, Environment::Production, or Environment::Custom. - **customBaseUrl** (?string) - Optional - Base URL for custom environment (default: null). ### Request Example ```php $redsysClient = new RedsysClient( merchantCode: 999008881, secretKey: 'sq7HjrUOBfKmC576ILgskD5srU870gJ7', terminal: 1, environment: Environment::Test, ); ``` ### Response #### Success Response - Returns a RedsysClient instance. #### Error Handling - Throws \Exception('Redsys custom environment without custom URL defined') if environment is Environment::Custom and customBaseUrl is empty/falsy. ### Response Example N/A (constructor returns instance) ``` -------------------------------- ### Usage - Inspecting undocumented fields Source: https://github.com/creagia/redsys-php/blob/main/_autodocs/api-reference/notification-parameters.md Example of inspecting undocumented fields collected by fromArray(). ```APIDOC ## Usage - Inspecting undocumented fields ### Description Example of inspecting undocumented fields collected by `fromArray()`. ### Code Example ```php $p = $notification->checkResponse(); $unknown = $p->extraParameters ?? []; // e.g. ['DS_SOMETHING_NEW' => 'value'] ``` ``` -------------------------------- ### Rebuilding from Existing Payload Source: https://github.com/creagia/redsys-php/blob/main/_autodocs/api-reference/request-parameters.md Example of rebuilding RequestParameters from an existing Ds_MerchantParameters payload using fromArray(). ```APIDOC ## Rebuilding from Existing Payload ### Description Example of rebuilding RequestParameters from an existing Ds_MerchantParameters payload using fromArray(). Used internally by RedsysFakeGateway. ### Example ```php $decoded = (array) json_decode(base64_decode($fields['Ds_MerchantParameters'])); $params = RequestParameters::fromArray($decoded); // enum fields auto-cast ``` ``` -------------------------------- ### Usage - Rebuilding from a decoded payload Source: https://github.com/creagia/redsys-php/blob/main/_autodocs/api-reference/notification-parameters.md Example of rebuilding NotificationParameters from a decoded payload using fromArray(). ```APIDOC ## Usage - Rebuilding from a decoded payload ### Description Example of rebuilding NotificationParameters from a decoded payload using `fromArray()`. Also used internally by `RedsysFakeGateway`. ### Code Example ```php $parameters = NotificationParameters::fromArray($merchantParametersArray); ``` ``` -------------------------------- ### Build and render redirection form Source: https://github.com/creagia/redsys-php/blob/main/_autodocs/api-reference/redsys-request.md Initializes the RedsysClient and creates a request to generate the HTML form for redirection. ```php use Creagia\Redsys\Enums\Currency; use Creagia\Redsys\Enums\Environment; use Creagia\Redsys\Enums\TransactionType; use Creagia\Redsys\RedsysClient; use Creagia\Redsys\RedsysRequest; use Creagia\Redsys\Support\RequestParameters; $redsysClient = new RedsysClient( merchantCode: 999008881, secretKey: 'sq7HjrUOBfKmC576ILgskD5srU870gJ7', terminal: 1, environment: Environment::Test, ); $redsysRequest = RedsysRequest::create( $redsysClient, new RequestParameters( amountInCents: 123_45, order: '22013100005', currency: Currency::EUR, transactionType: TransactionType::Autorizacion, merchantUrl: 'https://example.com/redsysNotification', urlOk: 'https://example.com/paymentOk', urlKo: 'https://example.com/paymentKo', ) ); echo $redsysRequest->getRedirectFormHtml(); ``` -------------------------------- ### Credential-On-File token request Source: https://github.com/creagia/redsys-php/blob/main/_autodocs/api-reference/redsys-request.md Demonstrates how to request a card token and subsequently charge using a stored token. ```php use Creagia\Redsys\Enums\CofType; $redsysRequest = RedsysRequest::create($redsysClient, new RequestParameters(...)) ->requestingCardToken(cofType: CofType::Recurring); // later, charge the stored token: $redsysRequest = RedsysRequest::create($redsysClient, new RequestParameters(...)) ->usingCardToken( cofType: CofType::Recurring, cofTransactionId: $cofTransactionId, merchantIdentifier: $merchantIdentifier, ); ``` -------------------------------- ### Error handling for invalid enum values Source: https://github.com/creagia/redsys-php/blob/main/_autodocs/api-reference/data-transfer-object.md Example of handling a LogicException when an invalid enum value is provided to the fromArray method. ```APIDOC ## Error handling for invalid enum values ### Description Example of handling a LogicException when an invalid enum value is provided to the fromArray method. ### Code Example ```php use Creagia\Redsys\Support\DataTransferObject\Casters\EnumCaster; try { $dto = MyDto::fromArray(['FIELD_STATUS' => 'Z']); } catch (\LogicException $e) { // "Couldn't cast enum [Status] with value [Z]" } ``` ``` -------------------------------- ### Create RedsysClient with custom environment and customBaseUrl Source: https://github.com/creagia/redsys-php/blob/main/README.md Use this snippet to configure a RedsysClient to use a custom environment, which requires setting the `customBaseUrl` property. This is useful for testing against a mock or fake Redsys gateway, such as the local gateway provided by the creagia/laravel-redsys package. ```php $redsysClient = new RedsysClient( merchantCode: env('redsys.merchantCode'), secretKey: env('redsys.key'), terminal: env('redsys.terminal'), environment: \Creagia\Redsys\Enums\Environment::Custom, customBaseUrl: 'https://localGateway.test', ); ``` -------------------------------- ### Usage (custom DTO) Source: https://github.com/creagia/redsys-php/blob/main/_autodocs/api-reference/data-transfer-object.md Example of using EnumCaster with a custom DataTransferObject, including the CastWith attribute, fromArray method, and toArray method. ```APIDOC ## Usage (custom DTO) ### Description Example of using EnumCaster with a custom DataTransferObject, including the CastWith attribute, fromArray method, and toArray method. ### Code Example ```php use Creagia\Redsys\Support\DataTransferObject\CastWith; use Creagia\Redsys\Support\DataTransferObject\Casters\EnumCaster; use Creagia\Redsys\Support\DataTransferObject\DataTransferObject; use Creagia\Redsys\Support\DataTransferObject\MapFrom; use Creagia\Redsys\Support\DataTransferObject\MapTo; enum Status: string { case Active = 'A'; case Inactive = 'I'; } class MyDto extends DataTransferObject { public function __construct( #[MapTo('FIELD_ONE')] #[MapFrom('FIELD_ONE')] public string $fieldOne, #[MapTo('FIELD_STATUS')] #[MapFrom('FIELD_STATUS')] #[CastWith(EnumCaster::class, Status::class)] public ?Status $status = null, ) {} } $dto = MyDto::fromArray(['field_status' => 'A']); // case-insensitive keys by default $dto->status === Status::Active; // true, auto-cast $dto->toArray(); // ['FIELD_ONE' => ..., 'FIELD_STATUS' => 'A'] ``` ``` -------------------------------- ### Custom Environment Exception Source: https://github.com/creagia/redsys-php/blob/main/_autodocs/api-reference/redsys-client.md Exception thrown when the environment is set to Custom but no customBaseUrl is provided. ```php throw new \Exception('Redsys custom environment without custom URL defined'); ``` -------------------------------- ### RedsysClient Constructor Source: https://github.com/creagia/redsys-php/blob/main/_autodocs/api-reference/redsys-client.md The constructor signature for initializing the RedsysClient. ```php public function __construct( public int $merchantCode, public string $secretKey, public int $terminal, public Environment $environment, public ?string $customBaseUrl = null, ) ``` -------------------------------- ### CofType enum with string cases Source: https://github.com/creagia/redsys-php/blob/main/_autodocs/types.md Defines the CofType enum with string backing values for Credential-On-File transaction types, such as Installments, Recurring, and Reauthorization. ```php enum CofType: string { case Installments = "I"; case Recurring = "R"; case Reauthorization = "H"; case Resubmission = "E"; case Delayed = "D"; case Incremental = "M"; case NoShow = "N"; case Others = "C"; } ``` -------------------------------- ### Create a Redsys redirection request Source: https://github.com/creagia/redsys-php/blob/main/README.md Creates a RedsysClient with environment configuration and a RedsysRequest with mandatory and optional parameters. Returns the redirection form HTML via getRedirectFormHtml(). ```php use Creagia\Redsys\Enums\Currency; use Creagia\Redsys\Enums\TransactionType; use Creagia\Redsys\RedsysClient; use Creagia\Redsys\RedsysRequest; use Creagia\Redsys\Support\RequestParameters; $redsysClient = new RedsysClient( merchantCode: env('redsys.merchantCode'), secretKey: env('redsys.key'), terminal: env('redsys.terminal'), environment: \Creagia\Redsys\Enums\Environment::Test, ); $redsysRequest = RedsysRequest::create( $redsysClient, new RequestParameters( amountInCents: 123_45, order: '22013100005', currency: Currency::EUR, transactionType: TransactionType::Autorizacion, merchantUrl: 'https://example.com/redsysNotification', urlOk: 'https://example.com/paymentOk', urlKo: 'https://example.com/paymentKo', ) ); echo $redsysRequest->getRedirectFormHtml() ``` -------------------------------- ### Constructor Parameters Source: https://github.com/creagia/redsys-php/blob/main/_autodocs/api-reference/request-parameters.md Lists the optional constructor parameters for the Redsys PHP library, including their types, defaults, and corresponding DS_* fields. ```APIDOC ## Constructor Parameters ### Description These are the optional parameters that can be passed to the constructor of the Redsys PHP library. Each parameter is a nullable string and defaults to `null`. They map to specific `DS_*` fields used in payment requests. ### Parameters | Parameter | Type | Required | Default | DS Field | Description | |-----------|------|----------|---------|----------|-------------| | `xpayOrigen` | `?string` | no | `null` | `DS_XPAYORIGEN` | Apple Pay / Google Pay origin | | `xpayType` | `?string` | no | `null` | `DS_XPAYTYPE` | Apple Pay / Google Pay type | | `shippingAddressPyp` | `?string` | no | `null` | `DS_MERCHANT_SHIPPINGADDRESSPYP` | Shipping address | | `merchantDescriptor` | `?string` | no | `null` | `DS_MERCHANT_MERCHANTDESCRIPTOR` | Merchant descriptor | | `persoCode` | `?string` | no | `null` | `DS_MERCHANT_PERSOCODE` | Personalisation code | | `matchingData` | `?string` | no | `null` | `DS_MERCHANT_MATCHINGDATA` | Case-matching data | | `acquirerIdentifier` | `?string` | no | `null` | `DS_ACQUIRER_IDENTIFIER` | Acquirer identifier | | `mpiExternal` | `?string` | no | `null` | `DS_MERCHANT_MPIEXTERNAL` | External MPI flag | | `customerMobile` | `?string` | no | `null` | `DS_MERCHANT_CUSTOMER_MOBILE` | Customer mobile (paygold / pay-per-link) | | `customerMail` | `?string` | no | `null` | `DS_MERCHANT_CUSTOMER_MAIL` | Customer e-mail | | `p2fExpiryDate` | `?string` | no | `null` | `DS_MERCHANT_P2F_EXPIRYDATE` | Pay-to-friend link expiry | | `customerSmsText` | `?string` | no | `null` | `DS_MERCHANT_CUSTOMER_SMS_TEXT` | SMS text | | `p2fXmlData` | `?string` | no | `null` | `DS_MERCHANT_P2F_XMLDATA` | Pay-to-friend XML data | | `dcc` | `?string` | no | `null` | `DS_MERCHANT_DCC` | Dynamic Currency Conversion flag | | `excepSca` | `?string` | no | `null` | `DS_MERCHANT_EXCEP_SCA` | SCA exemption (see [`ExcepSca`](../types.md#excepsca)) | | `ota` | `?string` | no | `null` | `DS_MERCHANT_OTA` | On-the-Air data | ``` -------------------------------- ### Signing a payload manually with Signature::calculateSignature Source: https://github.com/creagia/redsys-php/blob/main/_autodocs/api-reference/signature.md Example of manually signing a payload using the Signature class. The resulting base64 HMAC-SHA256 signature is used as Ds_Signature. ```php use Creagia\Redsys\Support\Signature; $signature = Signature::calculateSignature( encodedParameters: 'eyJEU19NRVJDSEFOVF9BTU9VTlQiOiIxMjM0NSIs...', order: '22013100005', secretKey: 'sq7HjrUOBfKmC576ILgskD5srU870gJ7', ); // base64 HMAC-SHA256 — used as Ds_Signature ``` -------------------------------- ### RequestParameters constructor Source: https://github.com/creagia/redsys-php/blob/main/_autodocs/configuration.md Constructor for payment configuration. Requires amount, transaction type, and currency. All other parameters are optional and map to Redsys DS_MERCHANT_* / DS_* fields. ```APIDOC ## RequestParameters constructor ### Description Creates a RequestParameters object that holds the full payment configuration for a Redsys request. ### Method __construct() ### Parameters #### Required Parameters - **amountInCents** (int) - Required - Amount in cents (`123_45` = 123.45 €). - **transactionType** (TransactionType) - Required - e.g. `TransactionType::Autorizacion`. - **currency** (Currency) - Required - e.g. `Currency::EUR`. #### Optional Parameters All remaining constructor options are optional (`?string`/`?int`/enum types, default `null`) and are mapped to their Redsys `DS_MERCHANT_*` / `DS_*` field: - **order** (?string) - Optional - Order identifier. - **authorisationCode** (?string) - Optional - Authorisation code. - **cofIni** (?string) - Optional - COF initial flag. - **cofTransactionId** (?string) - Optional - COF transaction ID. - **cofType** (?string) - Optional - COF type. - **consumerLanguage** (?string) - Optional - Consumer language. - **cvv2** (?string) - Optional - CVV2. - **directPayment** (?string) - Optional - Direct payment flag. - **emv3ds** (?string) - Optional - EMV 3DS data. - **expiryDate** (?string) - Optional - Card expiry date. - **group** (?string) - Optional - Group. - **merchantIdentifier** (?string) - Optional - Merchant identifier. - **idOper** (?string) - Optional - Operation ID. - **merchantCode** (?string) - Optional - Merchant code (overwritten from client). - **merchantData** (?string) - Optional - Merchant data. - **merchantName** (?string) - Optional - Merchant name. - **merchantUrl** (?string) - Optional - Merchant URL. - **pan** (?string) - Optional - Card PAN. - **payMethods** (?string) - Optional - Payment methods. - **productDescription** (?string) - Optional - Product description. - **taxReference** (?string) - Optional - Tax reference. - **terminal** (?string) - Optional - Terminal (overwritten from client). - **titular** (?string) - Optional - Cardholder name. - **transactionDate** (?string) - Optional - Transaction date. - **urlOk** (?string) - Optional - Success URL. - **urlKo** (?string) - Optional - Failure URL. - **xpayData** (?string) - Optional - XPay data. - **xpayOrigen** (?string) - Optional - XPay origin. - **xpayType** (?string) - Optional - XPay type. - **shippingAddressPyp** (?string) - Optional - Shipping address for PYP. - **merchantDescriptor** (?string) - Optional - Merchant descriptor. - **persoCode** (?string) - Optional - Perso code. - **matchingData** (?string) - Optional - Matching data. - **acquirerIdentifier** (?string) - Optional - Acquirer identifier. - **mpiExternal** (?string) - Optional - External MPI. - **customerMobile** (?string) - Optional - Customer mobile. - **customerMail** (?string) - Optional - Customer email. - **p2fExpiryDate** (?string) - Optional - P2F expiry date. - **customerSmsText** (?string) - Optional - Customer SMS text. - **p2fXmlData** (?string) - Optional - P2F XML data. - **dcc** (?string) - Optional - DCC flag. - **excepSca** (?string) - Optional - SCA exception. - **ota** (?string) - Optional - OTA. ``` -------------------------------- ### getParameters() Source: https://github.com/creagia/redsys-php/blob/main/_autodocs/api-reference/redsys-request.md Returns the request parameters mapped to their Redsys field names (DS_MERCHANT_* / DS_* keys), with blank values filtered out. This is the same array that gets JSON-encoded into Ds_MerchantParameters. ```APIDOC ## getParameters() ### Description Returns the request parameters mapped to their Redsys field names (`DS_MERCHANT_*` / `DS_*` keys), with blank values filtered out. This is the same array that gets JSON-encoded into `Ds_MerchantParameters`. ### Method `getParameters` ### Signature ```php public function getParameters(): array ``` ### Returns - `array` - The request parameters mapped to Redsys field names, with blank values filtered out. ``` -------------------------------- ### Run tests with Composer Source: https://github.com/creagia/redsys-php/blob/main/README.md Executes the test suite for the redsys-php project using Composer. Run this command from the project root to verify the codebase. ```bash composer test ``` -------------------------------- ### Verifying a third-party payload with Signature::calculateSignature Source: https://github.com/creagia/redsys-php/blob/main/_autodocs/api-reference/signature.md Example of verifying a third-party payload in a custom controller. It compares the calculated signature with the received one using hash_equals, applying strtr to convert URL-safe characters back to standard base64. ```php use Creagia\Redsys\Support\Signature; $expected = Signature::calculateSignature( encodedParameters: $response['Ds_MerchantParameters'], order: $decoded['DS_ORDER'], secretKey: $secretKey, ); if (! hash_equals($expected, strtr($response['Ds_Signature'], '-_', '+/'))) { throw new \RuntimeException('Signature mismatch'); } ``` -------------------------------- ### RedsysFakeGateway::__construct() Source: https://github.com/creagia/redsys-php/blob/main/_autodocs/api-reference/redsys-fake-gateway.md Constructor for the RedsysFakeGateway class. Initializes the gateway with the request fields array and the secret key used to sign the fake response. ```APIDOC ## RedsysFakeGateway::__construct() ### Description Initializes a new RedsysFakeGateway instance with the request fields array and the merchant secret key. ### Method Constructor ### Signature ```php public function __construct( private array $request, private string $secretKey ) ``` ### Parameters - **request** (array) - Required - The request fields array from `RedsysRequest::getRequestFieldsArray()` (keys `Ds_SignatureVersion`, `Ds_MerchantParameters`, `Ds_Signature`) - **secretKey** (string) - Required - The same secret key used by the client/request being tested; required to sign the fake response ### Returns No return value (constructor). ``` -------------------------------- ### POST {baseUrl}/realizarPago Source: https://github.com/creagia/redsys-php/blob/main/_autodocs/endpoints.md Redirection payment endpoint used to initiate a payment. The client library builds an HTML form that auto-submits to this endpoint with the signed merchant parameters. The shopper is redirected to the success or failure URL after payment, and a server-to-server notification is sent to the merchant URL. ```APIDOC ## POST {baseUrl}/realizarPago ### Description Redirection payment endpoint used to initiate a payment. The client library builds an HTML form that auto-submits to this endpoint with the signed merchant parameters. The shopper is redirected to the success or failure URL after payment, and a server-to-server notification is sent to the merchant URL. ### Method POST ### Endpoint {baseUrl}/realizarPago ### Parameters #### Request Body (form fields) - **Ds_SignatureVersion** (string) - Required - Signature version, always 'HMAC_SHA256_V1'. - **Ds_MerchantParameters** (string) - Required - Base64-encoded JSON of the mapped request parameters (DS_MERCHANT_* / DS_* keys). Blank values are filtered out. - **Ds_Signature** (string) - Required - HMAC-SHA256 signature computed over Ds_MerchantParameters with the merchant secret key. ### Request Example
### Response #### Success Response (302 Redirect) The shopper is redirected to DS_MERCHANT_URLOK (success) or DS_MERCHANT_URLKO (failure). #### Server-to-Server Notification A POST notification is sent to DS_MERCHANT_MERCHANTURL when the payment finishes. The notification body contains the same three Ds_* fields; Ds_MerchantParameters decodes to the response fields described in NotificationParameters. ``` -------------------------------- ### Error handling for invalid enum values Source: https://github.com/creagia/redsys-php/blob/main/_autodocs/api-reference/data-transfer-object.md Shows how to catch a LogicException when an invalid enum value is provided. The example attempts to create a DTO with an invalid status value 'Z' and catches the exception, which contains the message "Couldn't cast enum [Status] with value [Z]". ```php use Creagia\Redsys\Support\DataTransferObject\Casters\EnumCaster; try { $dto = MyDto::fromArray(['FIELD_STATUS' => 'Z']); } catch (\LogicException $e) { // "Couldn't cast enum [Status] with value [Z]" } ``` -------------------------------- ### RedsysResponse Constructor Source: https://github.com/creagia/redsys-php/blob/main/_autodocs/api-reference/redsys-response.md The constructor requires a RedsysClient instance, which provides the secret key necessary for signature verification. ```php public function __construct( private RedsysClient $redsysClient ) ``` -------------------------------- ### Create a Credential-On-File (token) request Source: https://github.com/creagia/redsys-php/blob/main/README.md Creates a RedsysRequest with tokenization helper requestingCardToken() and CofType::Recurring. Returns the redirection form HTML. ```php use Creagia\Redsys\RedsysRequest; use Creagia\Redsys\Support\RequestParameters; use Creagia\Redsys\Enums\CofType; $redsysRequest = RedsysRequest::create( redsysClient: $redsysClient, requestParameters: new RequestParameters(...) )->requestingCardToken( cofType: CofType::Recurring ); echo $redsysRequest->getRedirectFormHtml() ``` -------------------------------- ### create() (static) Source: https://github.com/creagia/redsys-php/blob/main/_autodocs/api-reference/redsys-request.md Static factory method that creates a new RedsysRequest instance, copying merchant code and terminal from the provided RedsysClient onto the request parameters. Optionally accepts a Guzzle HTTP client for POST requests. ```APIDOC ## `create()` (static) ### Description Creates a new RedsysRequest instance. Copies the merchant code and terminal from the provided RedsysClient onto the request parameters. Optionally accepts a Guzzle HTTP client used for POST requests. ### Method static ### Signature ```php public static function create( RedsysClient $redsysClient, RequestParameters $requestParameters, ?ClientInterface $client = null ): static ``` ### Parameters - **redsysClient** (RedsysClient) - Required - Client holding credentials, terminals and environment; its `merchantCode` and `terminal` are copied onto the request parameters. - **requestParameters** (RequestParameters) - Required - Payment details (amount, order, currency, transaction type, …). - **client** (?ClientInterface) - Optional - HTTP client used by `sendPostRequest()`; defaults to a new `GuzzleHttp\Client()`. Pass a mock here to test POST flows. ### Returns Returns a new `static` instance. ### Behavior - Sets `$request->parameters->merchantCode = $redsysClient->merchantCode` - Sets `$request->parameters->terminal = $redsysClient->terminal` (overwriting any values set on the `RequestParameters`) ``` -------------------------------- ### RedsysRequest::requestingCardToken() and usingCardToken() Source: https://github.com/creagia/redsys-php/blob/main/_autodocs/api-reference/redsys-request.md Handles Credential-On-File token requests: requesting a token for a card and later charging using the stored token. ```APIDOC ## RedsysRequest::requestingCardToken() and usingCardToken() ### Description Handles Credential-On-File token requests: requesting a token for a card and later charging using the stored token. ### Method requestingCardToken() and usingCardToken() ### Endpoint RedsysRequest::requestingCardToken(CofType $cofType) RedsysRequest::usingCardToken(CofType $cofType, string $cofTransactionId, string $merchantIdentifier) ### Parameters #### requestingCardToken() - **cofType** (CofType) - Required - Type of Credential-On-File (e.g., Recurring). #### usingCardToken() - **cofType** (CofType) - Required - Type of Credential-On-File (e.g., Recurring). - **cofTransactionId** (string) - Required - The transaction ID from the token request. - **merchantIdentifier** (string) - Required - Merchant identifier for the stored token. ### Request Example ```php use Creagia\Redsys\Enums\CofType; $redsysRequest = RedsysRequest::create($redsysClient, new RequestParameters(...)) ->requestingCardToken(cofType: CofType::Recurring); // later, charge the stored token: $redsysRequest = RedsysRequest::create($redsysClient, new RequestParameters(...)) ->usingCardToken( cofType: CofType::Recurring, cofTransactionId: $cofTransactionId, merchantIdentifier: $merchantIdentifier, ); ``` ### Response #### Success Response - Returns a RedsysRequest instance configured for token operations. ``` -------------------------------- ### RedsysRequest::create() and getRedirectFormHtml() Source: https://github.com/creagia/redsys-php/blob/main/_autodocs/api-reference/redsys-request.md Creates a new Redsys request with the provided client and request parameters, then renders the HTML redirection form. ```APIDOC ## RedsysRequest::create() and getRedirectFormHtml() ### Description Creates a new Redsys request with the provided client and request parameters, then renders the HTML redirection form. ### Method create() ### Endpoint RedsysRequest::create(RedsysClient $client, RequestParameters $parameters) ### Parameters #### Constructor Parameters (RedsysClient) - **merchantCode** (int) - Required - Merchant code provided by Redsys. - **secretKey** (string) - Required - Secret key for signing requests. - **terminal** (int) - Required - Terminal number. - **environment** (Environment) - Required - Environment (Test or Production). #### RequestParameters - **amountInCents** (int) - Required - Amount in cents. - **order** (string) - Required - Order identifier. - **currency** (Currency) - Required - Currency enum (e.g., EUR). - **transactionType** (TransactionType) - Required - Transaction type enum (e.g., Autorizacion). - **merchantUrl** (string) - Required - URL for Redsys notifications. - **urlOk** (string) - Required - URL for successful payment redirect. - **urlKo** (string) - Required - URL for failed payment redirect. ### Request Example ```php use Creagia\Redsys\Enums\Currency; use Creagia\Redsys\Enums\Environment; use Creagia\Redsys\Enums\TransactionType; use Creagia\Redsys\RedsysClient; use Creagia\Redsys\RedsysRequest; use Creagia\Redsys\Support\RequestParameters; $redsysClient = new RedsysClient( merchantCode: 999008881, secretKey: 'sq7HjrUOBfKmC576ILgskD5srU870gJ7', terminal: 1, environment: Environment::Test, ); $redsysRequest = RedsysRequest::create( $redsysClient, new RequestParameters( amountInCents: 123_45, order: '22013100005', currency: Currency::EUR, transactionType: TransactionType::Autorizacion, merchantUrl: 'https://example.com/redsysNotification', urlOk: 'https://example.com/paymentOk', urlKo: 'https://example.com/paymentKo', ) ); echo $redsysRequest->getRedirectFormHtml(); ``` ### Response #### Success Response - **getRedirectFormHtml()** (string) - Returns the HTML form for redirection to Redsys. ``` -------------------------------- ### Handle Redsys redirection notification Source: https://github.com/creagia/redsys-php/blob/main/_autodocs/api-reference/redsys-response.md Initializes the RedsysClient and processes a POST request from Redsys. Includes exception handling for denied payments, invalid signatures, and Redsys error codes. ```php use Creagia\Redsys\Enums\Environment; use Creagia\ Redsys\Exceptions\DeniedRedsysPaymentResponseException; use Creagia\Redsys\RedsysClient; use Creagia\Redsys\RedsysResponse; $redsysClient = new RedsysClient( merchantCode: 999008881, secretKey: 'sq7HjrUOBfKmC576ILgskD5srU870gJ7', terminal: 1, environment: Environment::Test, ); $notification = new RedsysResponse($redsysClient); $notification->setParametersFromResponse($_POST); // Redsys POSTs Ds_SignatureVersion, Ds_MerchantParameters, Ds_Signature try { $data = $notification->checkResponse(); // $data->order, $data->amount, $data->responseCode ... completeOrder($data->order); } catch (DeniedRedsysPaymentResponseException $e) { // Denied: $e->redsysCode (e.g. '0184'), $e->getMessage() (e.g. 'Error en la autenticación del titular') } catch (\Creagia\Redsys\Exceptions\InvalidRedsysResponseException $e) { // Signature mismatch or malformed input — do not trust the request } catch (\Creagia\Redsys\Exceptions\ErrorRedsysResponseException $e) { // Redsys replied with an error code (Ds_ErrorCode) } ``` -------------------------------- ### Update RedsysRequest constructor from v1 to v2 Source: https://github.com/creagia/redsys-php/blob/main/UPGRADING.md Shows the transition from the old RedsysRequest constructor to the new static create method using RequestParameters, including the change to integer-based currency amounts. ```php // From $redsysRequest = new RedsysRequest($redsysClient); $redsysRequest->createPaymentRequest( amount: 123.45, order: '22013100005', currency: Currency::EUR, transactionType: TransactionType::Autorizacion, ); // To $redsysRequest = RedsysRequest::create( $redsysClient, new RequestParameters( amountInCents: 123_45, order: '22013100005', currency: Currency::EUR, transactionType: TransactionType::Autorizacion, merchantUrl: 'https://example.com/redsysNotification', urlOk: 'https://example.com/paymentOk', urlKo: 'https://example.com/paymentKo', ) ); ``` -------------------------------- ### RedsysResponse::__construct Source: https://github.com/creagia/redsys-php/blob/main/_autodocs/api-reference/redsys-response.md Constructor for RedsysResponse. Initializes the response handler with a RedsysClient whose secretKey is used for signature verification. ```APIDOC ## RedsysResponse::__construct ### Description Creates a new RedsysResponse instance. The provided RedsysClient is used for signature verification. ### Method Constructor ### Signature public function __construct(private RedsysClient $redsysClient) ### Parameters - **redsysClient** (RedsysClient) - Required - Client whose secretKey is used for signature verification. ### Notes All public properties are uninitialised until setParametersFromResponse() is called. ``` -------------------------------- ### Inspect unverified notification parameters Source: https://github.com/creagia/redsys-php/blob/main/_autodocs/api-reference/redsys-response.md Demonstrates how to access raw notification parameters after parsing but before performing signature verification. ```php $notification->setParametersFromResponse($_POST); // parses but does not verify $raw = $notification->parameters; // NotificationParameters DTO, unverified $data = $notification->checkResponse(); // verifies signature + authorisation ``` -------------------------------- ### Environment enum with Test, Production, and Custom cases Source: https://github.com/creagia/redsys-php/blob/main/_autodocs/types.md Defines the Environment enum with string-backed cases for 'test', 'production', and 'custom'. The Custom case requires a 'customBaseUrl' on the client. Used by RedsysClient::getBaseUrl() and getRestBaseUrl(). ```php enum Environment: string { case Test = 'test'; case Production = 'production'; case Custom = 'custom'; } ``` -------------------------------- ### RedsysRequest::create() Source: https://github.com/creagia/redsys-php/blob/main/_autodocs/configuration.md Factory method to create a RedsysRequest instance. It requires a RedsysClient and RequestParameters, and optionally accepts an HTTP client for testing. ```APIDOC ## RedsysRequest::create() ### Description Creates a new RedsysRequest instance using the provided client and payment parameters. ### Method create() ### Parameters - **redsysClient** (RedsysClient) - Required - Supplies credentials, terminal, URLs and signature version. - **requestParameters** (RequestParameters) - Required - Full payment configuration; `merchantCode` and `terminal` are overwritten from the client. - **client** (?ClientInterface) - Optional - HTTP client used by `sendPostRequest()`; inject a mock for testing. Defaults to `new GuzzleHttp\Client()`. ### Returns RedsysRequest instance. ``` -------------------------------- ### usingCardToken() Source: https://github.com/creagia/redsys-php/blob/main/_autodocs/configuration.md Fluent helper that sets COF type, initial flag to No, transaction ID, and merchant identifier for using an existing card token. ```APIDOC ## usingCardToken() ### Description Sets COF type, cofIni to No, cofTransactionId, and merchantIdentifier for using an existing card token. ### Method usingCardToken() ### Parameters - **cofType** (CofType) - Required - The COF type to set. - **cofTransactionId** (string) - Required - The COF transaction ID. - **merchantIdentifier** (string) - Required - The merchant identifier. ### Effect - Sets `cofType` - Sets `cofIni = CofInitial::No` - Sets `cofTransactionId` - Sets `merchantIdentifier` ```