### Complete Example: Simple Payment Source: https://github.com/ssheduardo/sermepa/blob/master/README.md A full example demonstrating how to set up and initiate a simple payment transaction using the Sermepa TPV library. ```APIDOC ## Complete Example: Simple Payment ```php setAmount(25.50) ->setOrder(date('YmdHis')) // 20240215120000 ->setMerchantcode('999008881') ->setCurrency('978') ->setTransactiontype('0') ->setTerminal('1') ->setMethod('C') ->setNotification('https://tusitio.com/notificacion') ->setUrlOk('https://tusitio.com/ok') ->setUrlKo('https://tusitio.com/ko') ->setVersion('HMAC_SHA256_V1') ->setTradeName('Mi Tienda') ->setTitular('Cliente Ejemplo') ->setProductDescription('Compra en Mi Tienda') ->setEnvironment('test'); $signature = $redsys->generateMerchantSignature($key); $redsys->setMerchantSignature($signature); echo $redsys->createForm(); } catch (TpvException $e) { echo 'Error: ' . $e->getMessage(); } ?> ``` ``` -------------------------------- ### Complete Example: Notification (Callback) Source: https://github.com/ssheduardo/sermepa/blob/master/README.md An example demonstrating how to process the notification callback from the TPV, including parameter decoding, signature validation, and response checking. ```APIDOC ## Complete Example: Notification (Callback) ```php getMerchantParameters($_POST['Ds_MerchantParameters']); // Obtener código de respuesta $DsResponse = (int) $parameters['Ds_Response']; $DsOrder = $parameters['Ds_Order']; // Validar firma y respuesta if ($redsys->check($key, $_POST)) { if ($DsResponse >= 0 && $DsResponse <= 99) { // Pago aprobado // Aquí: actualizar pedido en BDD, enviar confirmación, etc. error_log("Pago exitoso - Pedido: $DsOrder, Respuesta: $DsResponse"); } else { // Pago denegado error_log("Pago denegado - Pedido: $DsOrder, Respuesta: $DsResponse"); } } else { // Firma inválida - posible fraude error_log("Firma inválida - Pedido: $DsOrder"); } } catch (TpvException $e) { error_log('Error TPV: ' . $e->getMessage()); http_response_code(500); } ?> ``` ``` -------------------------------- ### Complete Simple Payment Example Source: https://github.com/ssheduardo/sermepa/blob/master/README.md A full example demonstrating how to set up and generate a payment form for a simple transaction. Includes setting amount, order, currency, callbacks, and generating the merchant signature. ```php setAmount(25.50) ->setOrder(date('YmdHis')) // 20240215120000 ->setMerchantcode('999008881') ->setCurrency('978') ->setTransactiontype('0') ->setTerminal('1') ->setMethod('C') ->setNotification('https://tusitio.com/notificacion') ->setUrlOk('https://tusitio.com/ok') ->setUrlKo('https://tusitio.com/ko') ->setVersion('HMAC_SHA256_V1') ->setTradeName('Mi Tienda') ->setTitular('Cliente Ejemplo') ->setProductDescription('Compra en Mi Tienda') ->setEnvironment('test'); $signature = $redsys->generateMerchantSignature($key); $redsys->setMerchantSignature($signature); echo $redsys->createForm(); } catch (TpvException $e) { echo 'Error: ' . $e->getMessage(); } ``` -------------------------------- ### Pre-Order Date Example Source: https://github.com/ssheduardo/sermepa/blob/master/doc/Parámetros de entrada.html Shows the 'preOrderDate' parameter for pre-ordered purchases, indicating the expected merchandise availability date. The date format must be YYYYMMDD. ```json { "preOrderDate": "string (8 chars)" } ``` -------------------------------- ### Install Redsys PHP Library Source: https://github.com/ssheduardo/sermepa/blob/master/README.md Use Composer to install the Redsys PHP library. Ensure you have PHP 7.1.3+ and the necessary extensions (curl, openssl, json). ```bash composer require sermepa/sermepa ``` -------------------------------- ### 3DS Authentication Data Example Source: https://github.com/ssheduardo/sermepa/blob/master/doc/Parámetros de entrada.html Provides an example of 'threeDSReqAuthData', which contains data supporting a specific authentication process. The exact content is not specified in the current protocol version. ```json { "threeDSReqAuthData": "string (Max 2048)" } ``` -------------------------------- ### Complete Payment Notification (Callback) Example Source: https://github.com/ssheduardo/sermepa/blob/master/README.md Example code for handling payment notifications (callbacks) from the TPV. It decodes parameters, retrieves the response code, and validates the merchant signature to ensure payment integrity. ```php getMerchantParameters($_POST['Ds_MerchantParameters']); // Obtener código de respuesta $DsResponse = (int) $parameters['Ds_Response']; $DsOrder = $parameters['Ds_Order']; // Validar firma y respuesta if ($redsys->check($key, $_POST)) { if ($DsResponse >= 0 && $DsResponse <= 99) { // Pago aprobado // Aquí: actualizar pedido en BDD, enviar confirmación, etc. error_log("Pago exitoso - Pedido: $DsOrder, Respuesta: $DsResponse"); } else { // Pago denegado error_log("Pago denegado - Pedido: $DsOrder, Respuesta: $DsResponse"); } } else { // Firma inválida - posible fraude error_log("Firma inválida - Pedido: $DsOrder"); } } catch (TpvException $e) { error_log('Error TPV: ' . $e->getMessage()); http_response_code(500); } ``` -------------------------------- ### Quick Start: Create Payment Form Source: https://github.com/ssheduardo/sermepa/blob/master/README.md Initialize the Tpv class, set transaction details like amount, order, merchant code, currency, and environment. Generate the merchant signature and create the payment form. ```php use Sermepa\Tpv\Tpv; $redsys = new Tpv(); $redsys->setAmount(2500) // 25.00€ ->setOrder('1234AB') ->setMerchantcode('999008881') ->setCurrency('978') // Euros ->setTransactiontype('0') // Autorización ->setTerminal('1') ->setMethod('C') // Solo tarjeta ->setNotification('https://tusitio.com/notificacion') ->setUrlOk('https://tusitio.com/ok') ->setUrlKo('https://tusitio.com/ko') ->setEnvironment('test'); // Entorno de pruebas $signature = $redsys->generateMerchantSignature('TU_CLAVE_SECRETA'); $redsys->setMerchantSignature($signature); echo $redsys->createForm(); ``` -------------------------------- ### Pre-Order Purchase Indicator Example Source: https://github.com/ssheduardo/sermepa/blob/master/doc/Parámetros de entrada.html Illustrates the 'preOrderPurchaseInd' parameter, which indicates if the cardholder is ordering merchandise with future availability. Accepted values are '01' (Merchandise available) and '02' (Future availability). ```json { "preOrderPurchaseInd": "string (2 chars)" } ``` -------------------------------- ### Gift Card Count Example Source: https://github.com/ssheduardo/sermepa/blob/master/doc/Parámetros de entrada.html Shows the 'giftCardCount' parameter, which specifies the total number of prepaid or gift cards/codes purchased. This field accepts a 2-character numeric value. ```json { "giftCardCount": "string (2 chars)" } ``` -------------------------------- ### Account Change Date Example Source: https://github.com/ssheduardo/sermepa/blob/master/doc/Parámetros de entrada.html Shows the 'chAccChange' parameter, representing the date the cardholder's account was last modified. The format is an 8-character numeric string. ```json { "chAccChange": "string (8 chars)" } ``` -------------------------------- ### Delivery Timeframe Example Source: https://github.com/ssheduardo/sermepa/blob/master/doc/Parámetros de entrada.html Shows the 'deliveryTimeframe' parameter, indicating the expected delivery period for merchandise. Accepted values include '01' for Electronic Delivery, '02' for Same day shipping, '03' for Overnight shipping, and '04' for Two-day or more shipping. ```json { "deliveryTimeframe": "string (2 chars)" } ``` -------------------------------- ### 3DS Authentication Timestamp Example Source: https://github.com/ssheduardo/sermepa/blob/master/doc/Parámetros de entrada.html Shows the 'threeDSReqAuthTimestamp' parameter, which records the UTC date and time of authentication. The format must be YYYYMMDDHHMM. ```json { "threeDSReqAuthTimestamp": "string (12 chars)" } ``` -------------------------------- ### Gift Card Currency Example Source: https://github.com/ssheduardo/sermepa/blob/master/doc/Parámetros de entrada.html Demonstrates the 'giftCardCurr' field for prepaid or gift card purchases, indicating the ISO-4217 currency code of the card. It requires a 3-character numeric value. ```json { "giftCardCurr": "string (3 chars)" } ``` -------------------------------- ### Get Redsys JavaScript Path Source: https://github.com/ssheduardo/sermepa/blob/master/README.md Use this static method to retrieve the URL for the Redsys JavaScript file. Specify the environment ('test' or 'production') and the desired version (e.g., '3' for Redsys API). ```php use Sermepa\Tpv\Tpv; // Obtener URL del script $jsUrl = Tpv::getJsPath('test', '3'); // Entorno test, versión 3 // https://sis-t.redsys.es:25443/sis/NC/sandbox/redsysV3.js ``` -------------------------------- ### 3DS Authentication Method Example Source: https://github.com/ssheduardo/sermepa/blob/master/doc/Parámetros de entrada.html Illustrates the 'threeDSReqAuthMethod' parameter, indicating the mechanism used by the cardholder for authentication. Accepted values range from '01' (No 3DS Requestor authentication) to '99' (Reserved). ```json { "threeDSReqAuthMethod": "string (2 chars)" } ``` -------------------------------- ### Configure Recurring Payments with COF Source: https://context7.com/ssheduardo/sermepa/llms.txt Set up parameters for recurring or installment payments according to the COF protocol. This involves specifying the COF type, initial transaction details, and subscription plan information. ```php setAmount(9.99) ->setOrder('2024007G') ->setMerchantcode('999008881') ->setCurrency('978') ->setTransactiontype('0') ->setTerminal('1') ->setIdentifier('TOKEN_DEL_CLIENTE') ->setMerchantDirectPayment(true) ->setEnvironment('restTest'); // Parámetros COF $redsys->setMerchantCofIni('N'); // 'S' = primera transacción COF, 'N' = sucesiva $redsys->setMerchantCofType('R'); // 'R'=Recurrente, 'I'=Cuotas, 'H'=Reautorización $redsys->setMerchantCofTxnid('TXN123456'); // ID de la primera transacción COF // Para suscripciones con importe total y frecuencia $redsys->setSumtotal(120000); // Importe total del plan (céntimos: 1200.00€) $redsys->setChargeExpiryDate('2025-12-31'); // Fecha fin de la suscripción (AAAA-MM-DD) $redsys->setDateFrecuency(30); // Frecuencia de cobro en días $clave = 'sq7HjrUOBfKmC576ILgskD5srU870gJ7'; $firma = $redsys->generateMerchantSignature($clave); $redsys->setMerchantSignature($firma); $respuesta = json_decode($redsys->send(), true); $parametros = $redsys->getMerchantParameters($respuesta['Ds_MerchantParameters']); echo "Código respuesta: " . $parametros['Ds_Response']; ?> ``` -------------------------------- ### Incorrect Mobile Phone Formats Source: https://github.com/ssheduardo/sermepa/blob/master/doc/Parámetros de entrada.html These examples illustrate incorrect ways to format the 'mobilePhone' parameter. Ensure all required fields ('cc', 'subscriber') are present and correctly populated, and avoid sending just the number without the object structure. ```json "mobilePhone": { "subscriber": "699999999" } ``` ```json "mobilePhone": { "cc": "", "subscriber": "699999999" } ``` ```json "mobilePhone": {"699999999"} ``` ```json "mobilePhone": {""} ``` -------------------------------- ### Reorder Items Indicator Example Source: https://github.com/ssheduardo/sermepa/blob/master/doc/Parámetros de entrada.html Shows the 'reorderItemsInd' parameter, indicating if the cardholder is reordering previously purchased merchandise. Accepted values are '01' (First time ordered) and '02' (Reordered). ```json { "reorderItemsInd": "string (2 chars)" } ``` -------------------------------- ### Execute Automatic Redirection to TPV Source: https://context7.com/ssheduardo/sermepa/llms.txt Generates an HTML form and a JavaScript to automatically submit it, redirecting the user to the payment gateway without manual button clicks. An alternative exists to get the HTML without immediate echoing. ```php setAmount(50.00) ->setOrder('2024002B') ->setMerchantcode('999008881') ->setCurrency('978') ->setTransactiontype('0') ->setTerminal('1') ->setEnvironment('test'); $redsys->setMerchantSignature( $redsys->generateMerchantSignature('sq7HjrUOBfKmC576ILgskD5srU870gJ7') ); // Redirige inmediatamente (hace echo internamente) $redsys->executeRedirection(); // Alternativa: obtener el HTML sin hacer echo $html = $redsys->executeRedirection(true); // El HTML incluye: createForm() + ``` -------------------------------- ### Shipping Method Indicator Example Source: https://github.com/ssheduardo/sermepa/blob/master/doc/Parámetros de entrada.html Demonstrates the 'shipIndicator' parameter, which specifies the chosen shipping method for the transaction. Merchants should select the code that best describes the transaction. Accepted values include '01' (Ship to cardholder's billing address) through '07' (Other). ```json { "shipIndicator": "string (2 chars)" } ``` -------------------------------- ### Get Redsys JavaScript Path Source: https://context7.com/ssheduardo/sermepa/llms.txt Retrieve the URL for the Redsys JavaScript file, essential for modern integrations like NFC, Apple Pay, and Google Pay. Specify the environment ('test' or 'live') and the desired version ('2' or '3'). ```php '; ?> ``` -------------------------------- ### Tokenize Card for Recurring Payments Source: https://context7.com/ssheduardo/sermepa/llms.txt Use `setIdentifier()` without parameters to request a token from the bank for the first payment. Store this token for future recurring payments, allowing customers to avoid re-entering their details. Subsequent payments use the stored token with `setMerchantDirectPayment(true)` to bypass 3DS, DCC, and installments. ```php setIdentifier(); // Sin parámetros = 'REQUIRED' // La respuesta del banco incluirá: // $parametros['Ds_Merchant_Identifier'] => "TOKEN_GENERADO_POR_BANCO" // $parametros['Ds_ExpiryDate'] => "2812" (AAMM caducidad) // PASO 2: Pagos recurrentes — usar el token almacenado $redsys->setIdentifier('TOKEN_GENERADO_POR_BANCO') ->setMerchantDirectPayment(true); // Omite 3DS, DCC y fraccioamiento // El resto del flujo es idéntico a un pago REST normal $firma = $redsys->generateMerchantSignature('MI_CLAVE_SECRETA'); $redsys->setMerchantSignature($firma); $respuesta = json_decode($redsys->send(), true); ?> ``` -------------------------------- ### Instantiate the TPV Class Source: https://context7.com/ssheduardo/sermepa/llms.txt Create a new instance of the TPV class to begin configuring payment gateway settings. The constructor initializes default values for the test environment and signature version. ```php setAmount(9.99) ->setOrder('2024007G') ->setMerchantcode('999008881') ->setCurrency('978') ->setTransactiontype('0') ->setTerminal('1') ->setIdentifier('TOKEN_DEL_CLIENTE') ->setMerchantDirectPayment(true) ->setEnvironment('restTest'); // COF Parameters $redsys->setMerchantCofIni('N'); // 'S' = first COF transaction, 'N' = subsequent $redsys->setMerchantCofType('R'); // 'R'=Recurring, 'I'=Installments, 'H'=Reauthorization $redsys->setMerchantCofTxnid('TXN123456'); // ID of the first COF transaction // For subscriptions with total amount and frequency $redsys->setSumtotal(120000); // Total plan amount (cents: 1200.00€) $redsys->setChargeExpiryDate('2025-12-31'); // Subscription end date (YYYY-MM-DD) $redsys->setDateFrecuency(30); // Payment frequency in days $clave = 'sq7HjrUOBfKmC576ILgskD5srU870gJ7'; $firma = $redsys->generateMerchantSignature($clave); $redsys->setMerchantSignature($firma); $respuesta = json_decode($redsys->send(), true); $parametros = $redsys->getMerchantParameters($respuesta['Ds_MerchantParameters']); echo "Código respuesta: " . $parametros['Ds_Response']; ?> ``` ### Response #### Success Response (200) Returns a JSON object containing merchant parameters. #### Response Example ```json { "Ds_MerchantParameters": "...", "Ds_Signature": "..." } ``` ``` -------------------------------- ### Set Environment Source: https://context7.com/ssheduardo/sermepa/llms.txt Configures the destination URL for the gateway. Accepts values like 'test', 'live', 'restTest', 'restLive', 'insiteSandbox', 'insiteLive', 'insiteRestSandbox', 'insiteRestLive'. Constants from `MerchantEnvironment` can also be used. ```APIDOC ## `setEnvironment(string $environment)` – Seleccionar el entorno de conexión Configura la URL de destino de la pasarela. Acepta los valores: `test`, `live`, `restTest`, `restLive`, `insiteSandbox`, `insiteLive`, `insiteRestSandbox`, `insiteRestLive`. También se pueden usar las constantes de `MerchantEnvironment`. ```php setEnvironment('test'); // Usando constantes (recomendado) $redsys->setEnvironment(MerchantEnvironment::REST_TEST); // Entornos disponibles: // MerchantEnvironment::TEST => https://sis-t.redsys.es:25443/sis/realizarPago // MerchantEnvironment::LIVE => https://sis.redsys.es/sis/realizarPago // MerchantEnvironment::REST_TEST => https://sis-t.redsys.es:25443/sis/rest/trataPeticionREST // MerchantEnvironment::REST_LIVE => https://sis.redsys.es/sis/rest/trataPeticionREST // MerchantEnvironment::INSITE_SANDBOX => InSite con JS sandbox // MerchantEnvironment::INSITE_LIVE => InSite con JS producción ``` ``` -------------------------------- ### Instantiate TPV Class Source: https://context7.com/ssheduardo/sermepa/llms.txt Creates a new instance of the TPV virtual class. The constructor initializes the default environment to 'test', signature version to 'HMAC_SHA256_V1', and default HTML form values. ```APIDOC ## `new Tpv()` – Instanciar la clase principal Crea una nueva instancia del TPV virtual. En el constructor se inicializa el entorno por defecto (`test`), la versión de firma `HMAC_SHA256_V1` y los valores predeterminados del formulario HTML. ```php createInSiteFormJSON(array $config) ``` ### Parameters - **config** (array) - Required - An associative array containing the configuration for the InSite form. - **id** (string) - Required - The ID of the div element that will contain the payment form. - **fuc** (string) - Required - The merchant code (FUC). - **terminal** (string) - Required - The terminal ID. - **order** (string) - Required - The order identifier. - **styleButton** (string) - Optional - CSS styles for the payment button. - **styleBody** (string) - Optional - CSS styles for the payment form body. - **styleBox** (string) - Optional - CSS styles for the data input boxes. - **styleBoxText** (string) - Optional - CSS styles for the text within the input boxes. - **buttonValue** (string) - Optional - The text to display on the payment button. - **idiomaInsite** (string) - Optional - The language code for the form (e.g., 'ES'). - **mostrarLogoInsite** (bool) - Optional - Whether to display the entity's logo. - **estiloReducidoInsite** (bool) - Optional - Whether to use a reduced style. - **estiloInsite** (string) - Optional - The overall style of the form ('inline' or 'twoRows'). ### Request Example ```php setEnvironment('insiteSandbox'); $html = $redsys->createInSiteFormJSON([ 'id' => 'contenedor-pago', 'fuc' => '999008881', // Merchant code (FUC) 'terminal' => '1', 'order' => '2024006F', 'styleButton' => 'background:#28a745; color:white; padding:10px 20px;', 'styleBody' => 'font-family: Helvetica;', 'styleBox' => 'padding: 10px; border: 1px solid #ddd;', 'styleBoxText' => 'font-size: 13px; color: #333;', 'buttonValue' => 'Confirmar pago', 'idiomaInsite' => 'ES', 'mostrarLogoInsite' => true, 'estiloReducidoInsite'=> false, 'estiloInsite' => 'twoRows', // 'inline' or 'twoRows' ]); echo $html; ?> ``` ``` -------------------------------- ### Using Redsys Constants for Configuration Source: https://github.com/ssheduardo/sermepa/blob/master/README.md Leverage predefined constants for currencies, transaction types, consumer languages, and payment methods to avoid transcription errors and ensure correct values are used. ```php use Redsys\Merchant\MerchantCurrencies; use Redsys\Merchant\MerchantTransactionTypes; use Redsys\Merchant\MerchantConsumerLanguages; use Redsys\Merchant\MerchantPaymethods; // Monedas $redsys->setCurrency(MerchantCurrencies::EUR); // 978 $redsys->setCurrency(MerchantCurrencies::USD); // 840 $redsys->setCurrency(MerchantCurrencies::GBP); // 826 // Tipos de transacción $redsys->setTransactiontype(MerchantTransactionTypes::AUTHORIZATION); // 0 $redsys->setTransactiontype(MerchantTransactionTypes::PREAUTHORIZATION); // 1 // Idiomas $redsys->setLanguage(MerchantConsumerLanguages::SPANISH); // 001 $redsys->setLanguage(MerchantConsumerLanguages::ENGLISH); // 002 $redsys->setLanguage(MerchantConsumerLanguages::CATALAN); // 003 // Métodos de pago $redsys->setMethod(MerchantPaymethods::CARD); // C $redsys->setMethod(MerchantPaymethods::BIZUM); // z ``` -------------------------------- ### Get InSite Error Description Source: https://github.com/ssheduardo/sermepa/blob/master/README.md Use the MerchantInsiteError class to retrieve human-readable descriptions for InSite error codes. This helps in diagnosing payment issues. ```php use Redsys\Merchant\MerchantInsiteError; $errorDescription = MerchantInsiteError::getDescription('msg1'); ``` -------------------------------- ### Set Connection Environment Source: https://context7.com/ssheduardo/sermepa/llms.txt Configure the target URL for the payment gateway. Use string literals or recommended constants from MerchantEnvironment for different connection types (test, live, REST, InSite). ```php setEnvironment('test'); // Usando constantes (recomendado) $redsys->setEnvironment(MerchantEnvironment::REST_TEST); // Entornos disponibles: // MerchantEnvironment::TEST => https://sis-t.redsys.es:25443/sis/realizarPago // MerchantEnvironment::LIVE => https://sis.redsys.es/sis/realizarPago // MerchantEnvironment::REST_TEST => https://sis-t.redsys.es:25443/sis/rest/trataPeticionREST // MerchantEnvironment::REST_LIVE => https://sis.redsys.es/sis/rest/trataPeticionREST // MerchantEnvironment::INSITE_SANDBOX => InSite con JS sandbox // MerchantEnvironment::INSITE_LIVE => InSite con JS producción ``` -------------------------------- ### Electronic Delivery Email Address Example Source: https://github.com/ssheduardo/sermepa/blob/master/doc/Parámetros de entrada.html Demonstrates the 'deliveryEmailAddress' field for electronic deliveries. This email address is where the merchandise is delivered. It has a maximum length of 254 characters. ```json { "deliveryEmailAddress": "string (Max 254)" } ``` -------------------------------- ### InSite Methods Source: https://github.com/ssheduardo/sermepa/blob/master/README.md Methods for enabling and managing Redsys InSite payments, including form generation and payment execution. ```APIDOC ## InSite Methods ### Description Provides functionality for integrating Redsys InSite payments, allowing for embedded payment forms and direct payment execution. ### Methods - `setInSite(bool $enable)`: Enables or disables InSite mode. - `getInSiteMode()`: Retrieves the current InSite mode status. - `getInSiteJsUrl()`: Gets the URL for the InSite JavaScript. - `createInSiteForm(array $params)`: Generates an embedded InSite payment form with customizable parameters. - `createInSiteFormJSON(array $params)`: Generates an embedded InSite payment form using JSON parameters. - `sendInSite(string $idOper, string $key)`: Executes an InSite payment using the operation ID and key. ### Parameters for `createInSiteForm()` - `$containerId` (string, Optional): ID of the div container (default: 'card-form'). - `$buttonStyle` (string, Optional): CSS for the payment button. - `$bodyStyle` (string, Optional): CSS for the form body. - `$boxStyle` (string, Optional): CSS for the data input box. - `$inputStyle` (string, Optional): CSS for input fields. - `$buttonText` (string, Optional): Text for the button (HTML encoded). - `$language` (string, Optional): Language code (default: 'ES'). - `$showLogo` (bool, Optional): Whether to show the entity logo (default: true). - `$reducedStyle` (bool, Optional): Use reduced styling (default: false). - `$insiteStyle` (string, Optional): Styling mode ('inline' or 'twoRows', default: 'inline'). ### Example Usage ```php $redsys->setInSite(true); $formHtml = $redsys->createInSiteForm([ 'language' => 'EN', 'buttonText' => 'Pay Now' ]); // echo $formHtml; ``` ``` -------------------------------- ### Configure Recurring Payments Source: https://github.com/ssheduardo/sermepa/blob/master/README.md Set parameters for recurring payments, including the start of the recurring payment cycle, type, transaction ID, total amount, expiry date, and frequency. ```php $redsys->setMerchantCofIni('S'); // Inicio de COF $redsys->setMerchantCofType('R'); // Tipo: R=Recurrente, I=Cuotas $redsys->setMerchantCofTxnid('123456789'); // ID de transacción $redsys->setSumtotal(50000); // Importe total $redsys->setChargeExpiryDate('2025-12-31'); // Fecha expiración $redsys->setDateFrecuency(30); // Frecuencia en días ``` -------------------------------- ### sendInSite(string $idOper, string $key) Source: https://context7.com/ssheduardo/sermepa/llms.txt Executes an InSite payment using a provided operation ID and key. This method is called after the user completes the InSite iframe interaction and Redsys returns a valid `idOper`. ```APIDOC ## sendInSite(string $idOper, string $key) ### Description Executes an InSite payment using a provided operation ID and key. This method is called after the user completes the InSite iframe interaction and Redsys returns a valid `idOper`. ### Method POST (Implied by API interaction) ### Endpoint Not explicitly defined, but interacts with Redsys API. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (parameters are passed as method arguments) ### Request Example ```php setEnvironment('insiteRestSandbox') // 'insiteRestLive' for production ->setAmount(25.50) ->setOrder($pedido) ->setMerchantcode('999008881') ->setCurrency('978') ->setTransactiontype('0') ->setTerminal('1'); $respuestaJson = $redsys->sendInSite($idOper, $clave); $respuesta = json_decode($respuestaJson, true); $parametros = $redsys->getMerchantParameters($respuesta['Ds_MerchantParameters']); $dsResponse = (int) $parametros['Ds_Response']; if ($dsResponse >= 0 && $dsResponse <= 99) { echo "✅ Pago aprobado. Pedido: " . $parametros['Ds_Order']; } else { echo "❌ Pago denegado. Código: $dsResponse"; } } catch (TpvException $e) { echo 'Error TPV: ' . $e->getMessage(); } ?> ``` ### Response #### Success Response (200) Returns a JSON string with the bank's response. #### Response Example ```json { "Ds_MerchantParameters": "...", "Ds_Signature": "..." } ``` ``` -------------------------------- ### Create Saved Card Reference (First Payment) Source: https://github.com/ssheduardo/sermepa/blob/master/README.md Use this method for the initial payment when you intend to save the customer's card for future recurring payments. Call `setIdentifier()` without parameters to indicate that a new identifier is required. ```php // 1. Crear referencia (primer pago) $redsys->setIdentifier(); // Sin parámetros - indica "REQUIRED" // Respuesta del banco contendrá: // $parameters['Ds_Merchant_Identifier'] // $parameters['Ds_ExpiryDate'] ``` -------------------------------- ### Configuration Methods Source: https://github.com/ssheduardo/sermepa/blob/master/README.md Methods for configuring transaction details such as amount, order, currency, transaction type, and payment method. ```APIDOC ## Configuration Methods ### Description Methods to set up transaction details before generating a payment form or sending a request. ### Methods - `setAmount(float $amount)`: Sets the transaction amount. The amount is converted to cents. - `setOrder(string $order)`: Sets the order number (4-12 characters, first 4 must be numeric). - `setMerchantcode(string $merchantCode)`: Sets the merchant code (FUC). - `setCurrency(string $currency)`: Sets the ISO currency code. - `setTransactiontype(string $transactionType)`: Sets the transaction type. - `setTerminal(string $terminal)`: Sets the terminal number. - `setMethod(string $method)`: Sets the payment method (Optional). - `setNotification(string $url)`: Sets the notification URL (callback) (Recommended). - `setUrlOk(string $url)`: Sets the URL for successful payments (Recommended). - `setUrlKo(string $url)`: Sets the URL for failed payments (Recommended). - `setEnvironment(string $environment)`: Sets the connection environment (Optional). - `setVersion(string $version)`: Sets the signature version (Optional). - `setTradeName(string $tradeName)`: Sets the trade name (Optional). - `setTitular(string $titular)`: Sets the payment holder's name (Optional). - `setProductDescription(string $description)`: Sets the product description (Optional). ### Example Usage ```php use Redsys\Merchant\MerchantCurrencies; $redsys->setAmount(100.50); $redsys->setOrder('1234567890'); $redsys->setCurrency(MerchantCurrencies::EUR); // 978 ``` ``` -------------------------------- ### Account Age Indicator Example Source: https://github.com/ssheduardo/sermepa/blob/master/doc/Parámetros de entrada.html Illustrates the 'chAccAgeInd' parameter, indicating the duration the cardholder has held an account with the merchant. Possible values range from '01' (No account) to '05' (More than 60 days). ```json { "chAccAgeInd": "string (2 chars)" } ``` -------------------------------- ### createForm() Source: https://context7.com/ssheduardo/sermepa/llms.txt Generates the complete HTML for the POST form with the three fields required by Redsys: Ds_MerchantParameters, Ds_Signature, and Ds_SignatureVersion. The form points to the configured environment. ```APIDOC ## `createForm()` – Generar formulario HTML de pago Genera el HTML completo del formulario POST con los tres campos requeridos por Redsys: `Ds_MerchantParameters`, `Ds_Signature` y `Ds_SignatureVersion`. El formulario apunta al entorno configurado. ```php setAmount(25.50) ->setOrder(date('YmdHis')) ->setMerchantcode('999008881') ->setCurrency('978') ->setTransactiontype('0') ->setTerminal('1') ->setMethod('C') ->setNotification('https://tusitio.com/notificacion') ->setUrlOk('https://tusitio.com/ok') ->setUrlKo('https://tusitio.com/ko') ->setTradeName('Mi Tienda Online') ->setTitular('Juan García') ->setProductDescription('Pedido #12345') ->setVersion('HMAC_SHA256_V1') ->setEnvironment('test'); // Personalizar botón de envío (opcional) $redsys->setAttributesSubmit('btn_pagar', 'btn_pagar', 'Pagar ahora', 'background:#007bff;color:white;', 'btn-pago'); $firma = $redsys->generateMerchantSignature('sq7HjrUOBfKmC576ILgskD5srU870gJ7'); $redsys->setMerchantSignature($firma); echo $redsys->createForm(); // Salida:
} catch (TpvException $e) { error_log('Error TPV: ' . $e->getMessage()); } ``` ``` -------------------------------- ### Gift Card Purchase Amount Example Source: https://github.com/ssheduardo/sermepa/blob/master/doc/Parámetros de entrada.html Illustrates the 'giftCardAmount' field for prepaid or gift card purchases. This represents the total purchase amount in the primary currency unit, with a maximum of 15 characters. ```json { "giftCardAmount": "string (Max 15)" } ``` -------------------------------- ### Submit Card Details Directly Source: https://context7.com/ssheduardo/sermepa/llms.txt Use `setPan()`, `setExpiryDate()`, and `setCVV2()` to pre-fill card details for the user. This method requires explicit bank authorization and incurs additional PCI DSS responsibilities. Ensure all required TPV parameters are set before submitting. ```php setAmount(30.00) ->setOrder('2024004D') ->setMerchantcode('999008881') ->setCurrency('978') ->setTransactiontype('0') ->setTerminal('1') ->setEnvironment('test'); // Datos de tarjeta (tarjeta de pruebas Redsys) $redsys->setPan('4548812049400004'); // Número de tarjeta $redsys->setExpiryDate('1228'); // Caducidad en formato AAMM $redsys->setCVV2('123'); // Código CVV2 $redsys->setMerchantSignature( $redsys->generateMerchantSignature('sq7HjrUOBfKmC576ILgskD5srU870gJ7') ); echo $redsys->createForm(); ?> ``` -------------------------------- ### Create InSite Form with Language Constants Source: https://github.com/ssheduardo/sermepa/blob/master/README.md Use MerchantInsiteLanguage constants to specify the language for the InSite form. Ensure the correct language code is passed. ```php use Redsys\Merchant\MerchantInsiteLanguage; $redsys->createInSiteForm(..., MerchantInsiteLanguage::SPANISH, ...); // o $redsys->createInSiteForm(..., MerchantInsiteLanguage::ISO_ES, ...); ``` -------------------------------- ### setMethod(string $method) Source: https://context7.com/ssheduardo/sermepa/llms.txt Specifies which payment method to display on the gateway. Defaults to 'C' (card). Throws TpvException if the value is not among the allowed ones. ```APIDOC ## `setMethod(string $method)` – Método de pago Especifica qué método de pago se mostrará en la pasarela. Por defecto es `C` (tarjeta). Lanza `TpvException` si el valor no está entre los permitidos. ```php setMethod(MerchantPaymethods::TARJETA); // 'C' - Solo tarjeta $redsys->setMethod(MerchantPaymethods::BIZUM); // 'z' - Bizum $redsys->setMethod(MerchantPaymethods::PAYPAL); // 'P' - PayPal $redsys->setMethod(MerchantPaymethods::TRANSFERENCIA); // 'R' - Transferencia $redsys->setMethod('xpay'); // GooglePay / ApplePay // Validar $esValido = MerchantPaymethods::isValid('z'); // true ``` ``` -------------------------------- ### executeRedirection Source: https://github.com/ssheduardo/sermepa/blob/master/README.md Initiates an automatic redirection for payment without displaying a button. Optionally returns the HTML for the redirection. ```APIDOC ## executeRedirection ### Description Initiates an automatic redirection for payment without displaying a button. Optionally returns the HTML for the redirection. ### Method `executeRedirection(bool $returnHtml = false)` ### Parameters #### Path Parameters - **`returnHtml`** (boolean) - Optional - If true, the method returns the HTML for redirection instead of performing it directly. Defaults to false. ### Request Example ```php // Perform automatic redirection $redsys->executeRedirection(); // Get HTML for automatic redirection $html = $redsys->executeRedirection(true); ``` ### Response If `returnHtml` is false, performs an HTTP redirect. If `returnHtml` is true, returns an HTML string. ``` -------------------------------- ### Advanced Parameters: SCA Exception Source: https://github.com/ssheduardo/sermepa/blob/master/README.md How to handle Strong Customer Authentication (SCA) exceptions by providing additional parameters. ```APIDOC ## Advanced Parameters: SCA Exception Some banks require additional parameters for SCA exceptions. ### `setParameters(array)` Sets additional parameters, such as SCA exceptions. Example: `$parameters = ['DS_MERCHANT_EXCEP_SCA' => 'MIT']; $redsys->setParameters($parameters);` ```