### 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)" } ``` -------------------------------- ### 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)" } ``` -------------------------------- ### 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 ``` -------------------------------- ### 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 ``` -------------------------------- ### 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)" } ``` -------------------------------- ### 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 ``` -------------------------------- ### 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)" } ``` -------------------------------- ### 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)" } ``` -------------------------------- ### 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": "..." } ``` ```