### Example model with computed total and controller usage Source: https://github.com/creagia/laravel-redsys Complete model example computing total from items sum, plus controller call to createRedsysRequest and redirect. Shows typical usage flow. ```php namespace App\Models; use Creagia\LaravelRedsys\Concerns\CanCreateRedsysRequests; use Creagia\LaravelRedsys\Contracts\RedsysPayable; use Illuminate\Database\Eloquent\Model; class Order extends Model implements RedsysPayable { use CanCreateRedsysRequests; public function getTotalAmount(): int { return (int) collect($this->items)->sum('price_cents'); } public function paidWithRedsys(): void { $this->update(['status' => 'paid']); } } ``` ```php return Order::find($id)->createRedsysRequest('Cart payment', PayMethod::Card)->redirect(); ``` -------------------------------- ### Install laravel-redsys via Composer Source: https://github.com/creagia/laravel-redsys/blob/main/README.md Run this command to install the package using Composer. ```bash composer require creagia/laravel-redsys ``` -------------------------------- ### CreateRedsysClient usage example Source: https://github.com/creagia/laravel-redsys Resolves the CreateRedsysClient action from the Laravel container and invokes it to get a RedsysClient instance. ```php use Creagia\LaravelRedsys\Actions\CreateRedsysClient; $client = app(CreateRedsysClient::class)(); // RedsysClient ``` -------------------------------- ### Implementation example of RedsysPayable Source: https://github.com/creagia/laravel-redsys Shows a model implementing RedsysPayable with CanCreateRedsysRequests trait. getTotalAmount returns total_cents, paidWithRedsys updates status to 'paid'. ```php use Creagia\LaravelRedsys\Concerns\CanCreateRedsysRequests; use Creagia\LaravelRedsys\Contracts\RedsysPayable; class Order extends Model implements RedsysPayable { use CanCreateRedsysRequests; public function getTotalAmount(): int { return $this->total_cents; } public function paidWithRedsys(): void { $this->update(['status' => 'paid']); // email confirmation, inventory update, ... } } ``` -------------------------------- ### redirect() usage example Source: https://github.com/creagia/laravel-redsys Shows how to use redirect() from a controller: find an Order, create a Redsys request with a description and payment method, then return the redirect response. ```php public function pay() { $request = Order::find(1)->createRedsysRequest('Product description', PayMethod::Card); return $request->redirect(); // return this from a controller } ``` -------------------------------- ### Query and filter redsysCards relation Source: https://github.com/creagia/laravel-redsys Use eager loading with constraints on the redsysCards relation, or apply orderByDesc to get the most recent card. Works like any Eloquent MorphMany relation. ```php $cards = Team::with(['redsysCards' => fn ($q) => $q->latest()])->find($id); $lastCard = $user->redsysCards()->orderByDesc('created_at')->first(); ``` -------------------------------- ### Facade usage example Source: https://github.com/creagia/laravel-redsys Shows typical facade usage. The 'redsys-request' binding is not registered by the provider in this checkout, so this call would resolve an unbound class unless the application registers the singleton itself. ```php \Creagia\LaravelRedsys\Facades\RedsysRequest::someMethod(); ``` -------------------------------- ### Usage example: find request by order number and call paidWithRedsys Source: https://github.com/creagia/laravel-redsys Queries a Request by order_number from a Redsys response, checks if the related model is RedsysPayable, and calls paidWithRedsys() on it. ```php $request = Request::query() ->where('order_number', $redsysResponse->parameters->order) ->first(); if ($request && $request->model instanceof RedsysPayable) { $request->model->paidWithRedsys(); } ``` -------------------------------- ### Initial token request with storeCardOnModel Source: https://github.com/creagia/laravel-redsys Create a Redsys request on a payable model, request a card token with CofType::Recurring, and store the card on the given model (e.g., a Team). Returns a redirect response. ```php $redsysRequest = $productModel->createRedsysRequest( productDescription: 'Product description', payMethod: PayMethod::Card, )->requestingCardToken(CofType::Recurring)->storeCardOnModel($team); return $redsysRequest->redirect(); ``` -------------------------------- ### redsysCards() method signature Source: https://github.com/creagia/laravel-redsys Returns a MorphMany relation of RedsysCard where the morph model points to the owning model. Maps to redsys_cards.model_type and redsys_cards.model_id columns. ```php public function redsysCards() ``` -------------------------------- ### Querying notification logs with relationship Source: https://github.com/creagia/laravel-redsys Example of fetching the latest notification logs with the related redsysRequest, then accessing merchant_parameters and getStatus() for each log. ```php use Creagia\LaravelRedsys\RedsysNotificationLog; $logs = RedsysNotificationLog::with('redsysRequest')->latest()->get(); foreach ($logs as $log) { $params = $log->merchant_parameters; // array $status = $log->getStatus(); } ``` -------------------------------- ### post() usage example Source: https://github.com/creagia/laravel-redsys Shows how to call post() and handle a transport error response. Check if the response is an instance of PostRequestError to access its message and code properties; catch exceptions for upstream errors. ```php try { $response = $builder->post(); if ($response instanceof \Creagia\Redsys\Support\PostRequestError) { // transport error response: $response->message, $response->code } } catch (\Exception $e) { // handled by HandleRedsysResponse / upstream exceptions } ``` -------------------------------- ### Using getStatus() with switch Source: https://github.com/creagia/laravel-redsys Example of handling the RedsysRequestStatus enum returned by getStatus(). Covers Success, Error, and Pending cases, where Pending means no Ds_Response was notified. ```php use Creagia\LaravelRedsys\RedsysNotificationLog; use Creagia\LaravelRedsys\RedsysRequestStatus; $status = $log->getStatus(); // RedsysRequestStatus enum switch ($status) { case RedsysRequestStatus::Success: // handle break; case RedsysRequestStatus::Error: // handle break; case RedsysRequestStatus::Pending: // never notified a Ds_Response break; } ``` -------------------------------- ### usingCard() with stored card Source: https://github.com/creagia/laravel-redsys Uses a stored RedsysCard for a future transaction, forcing payMethods to PayMethod::Card. The example retrieves the first card from a paying model and passes it with CofType::Recurring. ```php public function usingCard(CofType $cofType, RedsysCard $redsysCard): RequestBuilder ``` ```php $redsysCard = $payingModel->redsysCards()->first(); $builder = RequestBuilder::newRequest(new RequestParameters( amountInCents: 19_99, currency: Currency::EUR, transactionType: TransactionType::Autorizacion, ))->usingCard(CofType::Recurring, $redsysCard); ``` -------------------------------- ### Access stored cards and display number and expiration Source: https://github.com/creagia/laravel-redsys Retrieve the latest card for a team, then iterate over all cards for a user and echo the card number and formatted expiration. ```php $redsysCard = $team->redsysCards()->latest()->first(); foreach ($user->redsysCards as $card) { echo $card->number.' '.$card->formattedExpiration(); } ``` -------------------------------- ### GET /redsys/unsuccessful-payment/{uuid} Source: https://github.com/creagia/laravel-redsys Renders the unsuccessful payment view. This is the default target of urlKo when unsuccessful_payment_route_name config is null. ```APIDOC ## GET /redsys/unsuccessful-payment/{uuid} ### Description Renders the unsuccessful payment view. This is the default target of urlKo when unsuccessful_payment_route_name config is null. ### Method GET ### Endpoint /redsys/unsuccessful-payment/{uuid} ### Parameters #### Path Parameters - **uuid** (string) - Required - Accepted but unused by the controller. ### Response #### Success Response (200) - **View** (Illuminate\View\View) - Renders the `redsys::unsuccessful` view. ``` -------------------------------- ### RedsysCard usage example Source: https://github.com/creagia/laravel-redsys Retrieves the latest card for a team and outputs its properties. `formattedExpiration()` returns `"07/26"` for an `expiration_date` of `2607`. ```php $redsysCard = $team->redsysCards()->latest()->first(); echo $redsysCard->number; echo $redsysCard->formattedExpiration(); // "07/26" echo $redsysCard->merchant_identifier; echo $redsysCard->cof_transaction_id; ``` -------------------------------- ### Upgrade from v1 to v2: redirection route replaced by redirect() Source: https://github.com/creagia/laravel-redsys/blob/main/UPGRADING.md Shows the old and new ways to redirect after creating a Redsys request. The old route-based redirect is replaced by calling `redirect()` on the request object. ```php // From return redirect($redsysPayment->getRedirectRoute()); // To return $redsysRequest->redirect(); ``` -------------------------------- ### notificationLogs() method declaration and usage Source: https://github.com/creagia/laravel-redsys Defines a HasMany relation to RedsysNotificationLog via redsys_notification_logs.redsys_request_id. The example retrieves all notification logs for a request. ```php public function notificationLogs(): HasMany ``` ```php $logs = $request->notificationLogs()->get(); ``` -------------------------------- ### getRequest() and reading fields Source: https://github.com/creagia/laravel-redsys Returns the underlying RedsysRequest instance for reading generated fields or calling upstream methods. The example shows retrieving the request fields array. ```php public function getRequest(): RedsysRequest ``` ```php $fields = $builder->getRequest()->getRequestFieldsArray(); ``` -------------------------------- ### GET /redsys/successful-payment/{uuid} Source: https://github.com/creagia/laravel-redsys Renders the successful payment view. This is the default target of urlOk when successful_payment_route_name config is null. ```APIDOC ## GET /redsys/successful-payment/{uuid} ### Description Renders the successful payment view. This is the default target of urlOk when successful_payment_route_name config is null. ### Method GET ### Endpoint /redsys/successful-payment/{uuid} ### Parameters #### Path Parameters - **uuid** (string) - Required - Accepted but unused by the controller; renders regardless. ### Response #### Success Response (200) - **View** (Illuminate\View\View) - Renders the `redsys::successful` view. ``` -------------------------------- ### GET /redsys/successful-payment/{uuid} Source: https://github.com/creagia/laravel-redsys Successful payment view endpoint. Displays the successful payment view for a given UUID. ```APIDOC ## [GET] /redsys/successful-payment/{uuid} ### Description Successful payment view endpoint. Displays the successful payment view for a given UUID. ### Method GET ### Endpoint /redsys/successful-payment/{uuid} ### Parameters #### Path Parameters - **uuid** (string) - Required - Payment UUID. ### Response No response documented. ### Notes - No middleware configured. - No route name assigned. - Auth: none configured. ``` -------------------------------- ### GET /redsys/unsuccessful-payment/{uuid} Source: https://github.com/creagia/laravel-redsys Unsuccessful payment view endpoint. Displays the unsuccessful payment view for a given UUID. ```APIDOC ## [GET] /redsys/unsuccessful-payment/{uuid} ### Description Unsuccessful payment view endpoint. Displays the unsuccessful payment view for a given UUID. ### Method GET ### Endpoint /redsys/unsuccessful-payment/{uuid} ### Parameters #### Path Parameters - **uuid** (string) - Required - Payment UUID. ### Response No response documented. ### Notes - No middleware configured. - No route name assigned. - Auth: none configured. ``` -------------------------------- ### newRequest() static factory Source: https://github.com/creagia/laravel-redsys Creates a new RequestBuilder instance from a RequestParameters object. The example shows constructing a RequestParameters with product description, amount in cents, currency, and transaction type. ```php public static function newRequest(RequestParameters $requestParameters): RequestBuilder ``` ```php use Creagia\LaravelRedsys\RequestBuilder; use Creagia\Redsys\Enums\Currency; use Creagia\Redsys\Enums\TransactionType; use Creagia\Redsys\Support\RequestParameters; $builder = RequestBuilder::newRequest(new RequestParameters( productDescription: 'Description', amountInCents: 123_12, currency: Currency::EUR, transactionType: TransactionType::Autorizacion, )); ``` -------------------------------- ### HandleRedsysResponse usage example Source: https://github.com/creagia/laravel-redsys Reuse the action in a custom notification handler by resolving it from the container and passing the matching Request and the parsed RedsysResponse. ```php use Creagia\LaravelRedsys\Actions\HandleRedsysResponse; use Creagia\LaravelRedsys\Request; $request = Request::where('order_number', $redsysResponse->parameters->order)->first(); app(HandleRedsysResponse::class)($request, $redsysResponse); ``` -------------------------------- ### Future COF request reusing stored card token Source: https://github.com/creagia/laravel-redsys Fetch the latest stored card for a team and build a new request using that card with CofType::Recurring. The request is posted directly without a redirect. ```php $redsysCard = $team->redsysCards()->latest()->first(); $builder = RequestBuilder::newRequest(new RequestParameters( amountInCents: $product->getTotalAmount(), currency: Currency::EUR, transactionType: TransactionType::Autorizacion, ))->usingCard(CofType::Recurring, $redsysCard); return $builder->post(); ``` -------------------------------- ### Upgrade from v1 to v2: createRedsysRequest method signature change Source: https://github.com/creagia/laravel-redsys/blob/main/UPGRADING.md Shows the old and new method calls for creating a Redsys request. The old method `createRedsysPayment` is replaced by `createRedsysRequest` with named arguments and a `payMethod` parameter. ```php // From $redsysPayment = $yourModel->createRedsysPayment( 'Product description', RedsysCurrency::EUR, RedsysConsumerLanguage::Auto, ); // To $redsysRequest = $yourModel->createRedsysRequest( productDescription: 'Product description', payMethod: PayMethod::Bizum, ); ``` -------------------------------- ### formattedExpiration() method signature Source: https://github.com/creagia/laravel-redsys Returns a string in `MM/YY` form from the `expiration_date` (`YYMM`) integer. For example, an `expiration_date` of `2607` yields `"07/26"`. ```php public function formattedExpiration(): string ``` -------------------------------- ### redsysCards() Source: https://github.com/creagia/laravel-redsys Defines a polymorphic one-to-many relationship between the model using this trait and the RedsysCard model. Returns a MorphMany relation builder for querying the stored card tokens owned by the current model instance. ```APIDOC ## redsysCards() ### Description Defines a polymorphic one-to-many relationship between the model using this trait and the RedsysCard model. Returns a MorphMany relation builder for querying the stored card tokens owned by the current model instance. ### Method redsysCards() ### Return Illuminate\Database\Eloquent\Relations\MorphMany of RedsysCard where the morph `model` points to the owning model. ### Usage Example ```php $redsysCard = $team->redsysCards()->latest()->first(); foreach ($user->redsysCards as $card) { echo $card->number.' '.$card->formattedExpiration(); } ``` ### Querying and Filtering Example ```php $cards = Team::with(['redsysCards' => fn ($q) => $q->latest()])->find($id); $lastCard = $user->redsysCards()->orderByDesc('created_at')->first(); ``` ``` -------------------------------- ### Handle RedsysSuccessfulEvent in a listener Source: https://github.com/creagia/laravel-redsys Example listener for RedsysSuccessfulEvent. Accesses the redsys_requests model via $event->redsysPayment->model and notifies it with an OrderPaid notification using the payment amount and notification data. ```php namespace App\Listeners; use Creagia\LaravelRedsys\Events\RedsysSuccessfulEvent; class NotifyCustomerOfSuccess { public function handle(RedsysSuccessfulEvent $event): void { $order = $event->redsysPayment->model; $order->notify(new OrderPaid($event->redsysPayment->amount, $event->notificationData)); } } ``` -------------------------------- ### requestingCardToken() with CofType Source: https://github.com/creagia/laravel-redsys Marks the request with save_card = true so a RedsysCard is stored on a successful response. The example chains associateWithModel() and storeCardOnModel() to associate the request with a product model and store the card on a user model. ```php public function requestingCardToken(CofType $cofType): RequestBuilder ``` ```php $redsysRequest = RequestBuilder::newRequest($params) ->associateWithModel($productModel) ->requestingCardToken(CofType::Recurring) ->storeCardOnModel($userModel); ``` -------------------------------- ### Publishing commands for migrations and config Source: https://github.com/creagia/laravel-redsys Commands to publish the package's migration and config files. Run the migration publish first, then migrate, then publish the config. ```bash php artisan vendor:publish --tag="redsys-migrations" php artisan migrate php artisan vendor:publish --tag="redsys-config" ``` -------------------------------- ### Publish and run migrations Source: https://github.com/creagia/laravel-redsys/blob/main/README.md Publish the package migrations and then run them to create the necessary database tables. ```bash php artisan vendor:publish --tag="redsys-migrations" ``` ```bash php artisan migrate ``` -------------------------------- ### LaravelRedsysServiceProvider configurePackage method Source: https://github.com/creagia/laravel-redsys Defines the package configuration for laravel-redsys, including config file, views, web routes, and a migration. The provider auto-registers via composer.json and extends Spatie's PackageServiceProvider. ```php class LaravelRedsysServiceProvider extends PackageServiceProvider { public function configurePackage(Package $package): void { $package ->name('laravel-redsys') ->hasConfigFile() ->hasViews() ->hasRoute('web') ->hasMigration('create_redsys_payments_table'); } } ``` -------------------------------- ### Run test suite with composer test Source: https://github.com/creagia/laravel-redsys/blob/main/README.md Executes the project's test suite using Composer. Run this command from the project root to verify the package works correctly. ```bash composer test ``` -------------------------------- ### Initial custom Credential-On-File request Source: https://github.com/creagia/laravel-redsys/blob/main/README.md Creates an initial request using RequestBuilder with custom parameters, optionally associating the request to Eloquent models. Uses requestingCardToken and storeCardOnModel. ```php use Creagia\Redsys\Enums\CofType; use Creagia\Redsys\Enums\PayMethod; /** * Use this example for a custom request, optionally associating the request to Eloquent models */ public function initialCustomRequest() { $redsysRequest = RequestBuilder::newRequest(new RequestParameters( amountInCents: 19_99, currency: Currency::EUR, transactionType: TransactionType::Autorizacion, ))->associateWithModel( $yourProductModel )->requestingCardToken( CofType::Recurring )->storeCardOnModel( $yourPayingModel // User, Team, ... ); return $redsysRequest->redirect(); } ``` -------------------------------- ### Suggested catch strategy for multiple exceptions Source: https://github.com/creagia/laravel-redsys Recommended pattern for catching RedsysConfigError, RedsysRequestNotFound, and InvalidRedsysResponseException together, with a \Throwable fallback. This handles specific configuration, lookup, and signature problems before falling back to a generic catch-all. ```php use Creagia\LaravelRedsys\Exceptions\RedsysConfigError; use Creagia\LaravelRedsys\Exceptions\RedsysRequestNotFound; use Creagia\Redsys\Exceptions\InvalidRedsysResponseException; try { $builder->post(); } catch (RedsysConfigError | RedsysRequestNotFound | InvalidRedsysResponseException $e) { // handle specific configuration / lookup / signature problems } catch (\Throwable $e) { // fallback } ``` -------------------------------- ### Basic redirect flow with createRedsysRequest() Source: https://github.com/creagia/laravel-redsys Creates a Redsys request with a product description and Bizum payment method, then redirects to Redsys. The request is automatically associated with the order model. ```php // Basic redirect flow public function checkout() { $redsysRequest = $this->order->createRedsysRequest( productDescription: 'Product description', payMethod: PayMethod::Bizum, ); return $redsysRequest->redirect(); } ``` -------------------------------- ### Publish config file Source: https://github.com/creagia/laravel-redsys/blob/main/README.md Publish the package configuration file to your application's config directory. ```bash php artisan vendor:publish --tag="redsys-config" ``` -------------------------------- ### RedsysPayable interface definition Source: https://github.com/creagia/laravel-redsys Defines the contract an Eloquent model must implement to be payable via Redsys. Includes getTotalAmount() returning amount in cents and paidWithRedsys() called on successful payment. ```php namespace Creagia\LaravelRedsys\Contracts; use Illuminate\Database\Eloquent\Model; /** * @mixin Model */ interface RedsysPayable { public function getTotalAmount(): int; public function paidWithRedsys(): void; } ``` -------------------------------- ### CreateRedsysClient constructor call Source: https://github.com/creagia/laravel-redsys Constructs the RedsysClient using values from the redsys config: merchantCode, secretKey, terminal, environment, and customBaseUrl. ```php new RedsysClient( merchantCode: config('redsys.tpv.merchantCode'), secretKey: config('redsys.tpv.key'), terminal: config('redsys.tpv.terminal'), environment: $environment, customBaseUrl: $customBaseUrl, ) ``` -------------------------------- ### Initial Credential-On-File request with model association Source: https://github.com/creagia/laravel-redsys/blob/main/README.md Creates an initial request to obtain a card token, associating the request and card to Eloquent models. Uses createRedsysRequest and requestingCardToken with CofType::Recurring. ```php use Creagia\Redsys\Enums\CofType; use Creagia\Redsys\Enums\PayMethod; /** * Use this example to associate the request and card easily to Eloquent models */ public function initialRequest() { $redsysRequest = $yourProductModel->createRedsysRequest( productDescription: 'Product description', payMethod: PayMethod::Card, )->requestingCardToken( CofType::Recurring )->storeCardOnModel( $yourPayingModel // User, Team, ... ); return $redsysRequest->redirect(); } ``` -------------------------------- ### POST {prefix}/localGateway/realizarPago Source: https://github.com/creagia/laravel-redsys Processes a local gateway payment. Accepts Ds_* form fields and returns an HTML view. ```APIDOC ## POST {prefix}/localGateway/realizarPago ### Description Processes a local gateway payment. Accepts Ds_* form fields and returns an HTML view. ### Method POST ### Endpoint {prefix}/localGateway/realizarPago ### Parameters #### Request Body - **Ds_* form fields** (form data) - Required - The Ds_* form fields. ### Response #### Success Response (200) - **View** (HTML) - Returns an HTML view. ``` -------------------------------- ### Include InteractsWithRedsysCards trait in a model Source: https://github.com/creagia/laravel-redsys Add the trait to any Eloquent model that will own stored Redsys card tokens, such as User, Team, or Subscription. The trait provides the redsysCards() morph relation. ```php use Creagia\LaravelRedsys\Concerns\InteractsWithRedsysCards; class Team extends Model { use InteractsWithRedsysCards; // ... } ``` -------------------------------- ### POST /redsys/localGateway/realizarPago Source: https://github.com/creagia/laravel-redsys Local gateway landing page used when the environment is set to 'local'. It decodes the merchant parameters and renders a Tailwind UI with Auth/Deny forms. ```APIDOC ## POST /redsys/localGateway/realizarPago ### Description Local gateway landing page (custom base URL used when `redsys.environment = 'local'`). ### Method POST ### Endpoint /redsys/localGateway/realizarPago ### Parameters #### Request Body - **Ds_MerchantParameters** (string) - Required - Merchant parameters. - **Ds_Signature** (string) - Required - Signature. - **Ds_SignatureVersion** (string) - Required - Signature version. ### Response #### Success Response (200) - **View** (Illuminate\Contracts\View\View) - HTML view. ### Auth Guarded by app-environment check only. Throws `\Exception('Local Gateway is only available on local environment. Update your .env file.')` if app env is not `local`. ``` -------------------------------- ### Full published config file (config/redsys.php) Source: https://github.com/creagia/laravel-redsys The complete configuration file with environment variables and defaults. Required keys: environment, merchantCode, and key; missing ones throw RedsysConfigError. ```php env('REDSYS_ENVIRONMENT'), 'tpv' => [ 'terminal' => env('REDSYS_TERMINAL', 1), 'currency' => Currency::EUR, 'merchantCode' => env('REDSYS_MERCHANT_CODE'), 'key' => env('REDSYS_KEY'), ], 'routes_prefix' => env('REDSYS_ROUTE_PREFIX', 'redsys'), 'successful_payment_route_name' => env('REDSYS_SUCCESSFUL_ROUTE_NAME', null), 'unsuccessful_payment_route_name' => env('REDSYS_UNSUCCESSFUL_ROUTE_NAME', null), 'order_num_auto_prefix' => true, 'order_num_prefix' => env('REDSYS_ORDER_NUM_PREFIX', 0), ]; ``` -------------------------------- ### redirect() Source: https://github.com/creagia/laravel-redsys Returns an HTTP response containing an auto-submitting HTML form that redirects the user to the payment gateway. Persists the request before generating the form. ```APIDOC ## redirect() ### Description Returns an HTTP response containing an auto-submitting HTML form that redirects the user to the payment gateway. Persists the request before generating the form. ### Method redirect ### Return `Illuminate\Http\Response` containing the auto-submitting HTML form. ### Request Example ```php public function pay() { $request = Order::find(1)->createRedsysRequest('Product description', PayMethod::Card); return $request->redirect(); // return this from a controller } ``` ``` -------------------------------- ### usingCardToken() Source: https://github.com/creagia/laravel-redsys Low-level variant of usingCard() that takes the token identifiers directly without forcing the payment method. ```APIDOC ## usingCardToken() ### Description Low-level variant of usingCard() that takes the token identifiers directly without forcing the payment method. ### Method usingCardToken ### Signature ```php public function usingCardToken(CofType $cofType, string $merchantIdentifier, string $cofTransactionId): RequestBuilder ``` ### Parameters - **cofType** (`\Creagia\Redsys\Enums\CofType`) - Required - Credential-On-File type. - **merchantIdentifier** (`string`) - Required - Merchant identifier (COF token). - **cofTransactionId** (`string`) - Required - COF transaction identifier. ### Return The same builder. Note that unlike `usingCard()`, this does **not** force `payMethods` to `Card`. ``` -------------------------------- ### RedsysLocalGatewayController index method Source: https://github.com/creagia/laravel-redsys Local fake gateway index. Throws \Exception('Local Gateway is only available on local environment. Update your .env file.') when app is not in local environment. Otherwise decodes Ds_MerchantParameters (base64 + url-decode + JSON) and returns redsys::localGateway view with originalPost and params. ```php public function index(Request $request): View ``` -------------------------------- ### Required .env variables Source: https://github.com/creagia/laravel-redsys/blob/main/README.md Define at least these environment variables in your .env file for the package to work. ```plaintext REDSYS_ENVIRONMENT REDSYS_MERCHANT_CODE REDSYS_KEY ``` -------------------------------- ### Create payment request and redirect Source: https://github.com/creagia/laravel-redsys/blob/main/README.md Use this snippet to create a Redsys payment request from an Eloquent model and redirect the user to the payment gateway. The method `createRedsysRequest` is called on the model, with a product description and payment method (e.g., Bizum). The `redirect()` method returns the redirect response. ```php public function createPaymentAndRedirect() { $redsysRequest = $yourModel->createRedsysRequest( productDescription: 'Product description', payMethod: PayMethod::Bizum, ); return $redsysRequest->redirect(); } ``` -------------------------------- ### Creating a notification log entry Source: https://github.com/creagia/laravel-redsys Shows how to create a RedsysNotificationLog row from a processed response. Handles both PostRequestError and RedsysResponse by selecting the appropriate parameters array. ```php $redsysNotificationLog = RedsysNotificationLog::create([ 'merchant_parameters' => $response instanceof PostRequestError ? $response->responseParameters : $response->merchantParametersArray, ]); ``` -------------------------------- ### model() method signature Source: https://github.com/creagia/laravel-redsys Returns a polymorphic relation to the owning model. The migration uses `nullableMorphs('model')`. ```php public function model(): MorphTo ``` -------------------------------- ### POST /redsys/localGateway/realizarPago Source: https://github.com/creagia/laravel-redsys Local gateway payment initiation endpoint. Handles payment requests via the local gateway controller. ```APIDOC ## [POST] /redsys/localGateway/realizarPago ### Description Local gateway payment initiation endpoint. Handles payment requests via the local gateway controller. ### Method POST ### Endpoint /redsys/localGateway/realizarPago ### Parameters No parameters documented. ### Response No response documented. ### Notes - No middleware configured. - No route name assigned. - Auth: none configured. ``` -------------------------------- ### post() method signature Source: https://github.com/creagia/laravel-redsys Public method that returns a RedsysResponse on success or a PostRequestError when the bank returns an HTTP error. It persists the request, sends the POST request via sendPostRequest(), and runs the HandleRedsysResponse action to update status and fire events. ```php public function post(): RedsysResponse|PostRequestError ``` -------------------------------- ### Send Redsys request via redirection (PayMethod::Card) Source: https://github.com/creagia/laravel-redsys/blob/main/README.md Creates a Redsys request from your model and redirects the user to the payment gateway. Use this for the Redirection integration method. The method `createRedsysRequest` is expected on your model and `redirect()` sends the user to Redsys. ```php use Creagia\Redsys\Enums\PayMethod; public function redirection() { $redsysRequest = $yourModel->createRedsysRequest( productDescription: 'Product description', payMethod: PayMethod::Card, ); return $redsysRequest->redirect(); } ``` -------------------------------- ### Override redirect routes in config file Source: https://github.com/creagia/laravel-redsys/blob/main/README.md Configuration keys to override the default successful and unsuccessful payment routes. Set these in the package config file to customize where Redsys redirects users after payment. The values default to null, meaning the package's built-in simple views are used. ```php 'successful_payment_route_name' => env('REDSYS_SUCCESSFUL_ROUTE_NAME', null), 'unsuccessful_payment_route_name' => env('REDSYS_UNSUCCESSFUL_ROUTE_NAME', null), ``` -------------------------------- ### RedsysNotificationController __invoke method Source: https://github.com/creagia/laravel-redsys Handles incoming bank notification POST. Dispatches RedsysNotificationEvent, builds RedsysClient, constructs RedsysResponse, sets parameters from response, finds Request by order_number, and runs HandleRedsysResponse. Throws DeniedRedsysPaymentResponseException, RedsysRequestNotFound, InvalidRedsysResponseException, ErrorRedsysResponseException, RedsysConfigError. ```php public function __invoke(HttpRequest $httpRequest, CreateRedsysClient $createRedsysClient): void ``` -------------------------------- ### Catching RedsysConfigError in consumer code Source: https://github.com/creagia/laravel-redsys Shows how to catch RedsysConfigError when calling RequestBuilder::newRequest($params)->post(). The exception is thrown when config('redsys.environment'), config('redsys.tpv.merchantCode'), or config('redsys.tpv.key') is falsy. Mitigation involves setting REDSYS_ENVIRONMENT, REDSYS_MERCHANT_CODE, and REDSYS_KEY environment variables. ```php use Creagia\LaravelRedsys\Exceptions\RedsysConfigError; try { $response = RequestBuilder::newRequest($params)->post(); } catch (RedsysConfigError $e) { // "Missing Environment option from Redsys config" etc. report($e->getMessage()); } ``` -------------------------------- ### RedsysRequest Facade class Source: https://github.com/creagia/laravel-redsys Facade that forwards to the 'redsys-request' container binding and proxies methods of the upstream RedsysRequest via @mixin. Note: the provider does not register this binding in the shown source, so the facade requires manual binding. ```php /** * @mixin \Creagia\Redsys\RedsysRequest */ class RedsysRequest extends Facade { protected static function getFacadeAccessor() { return 'redsys-request'; } } ``` -------------------------------- ### CreateRedsysClient __invoke() signature Source: https://github.com/creagia/laravel-redsys Invokable method that returns a configured RedsysClient. Throws RedsysConfigError::missingOption if environment, merchantCode, or key config options are missing. Uses Environment::Custom with the localGateway URL when environment is 'local'. ```php public function __invoke(): RedsysClient ``` -------------------------------- ### post() Source: https://github.com/creagia/laravel-redsys Sends the payment request to the bank and returns the response or an error object. Persists the request, sends the POST request, and processes the response. ```APIDOC ## post() ### Description Sends the payment request to the bank and returns the response or an error object. Persists the request, sends the POST request, and processes the response. ### Method post ### Return `\Creagia\Redsys\RedsysResponse` on success, or `\Creagia\Redsys\Support\PostRequestError` when the bank returns an HTTP error. ### Request Example ```php try { $response = $builder->post(); if ($response instanceof \Creagia\Redsys\Support\PostRequestError) { // transport error response: $response->message, $response->code } } catch (\Exception $e) { // handled by HandleRedsysResponse / upstream exceptions } ``` ``` -------------------------------- ### Prepare Eloquent model with InteractsWithRedsysCards Source: https://github.com/creagia/laravel-redsys/blob/main/README.md Use the InteractsWithRedsysCards concern on the model you want to associate with Redsys card tokens, typically User, Team, or Subscription. ```php use Creagia\LaravelRedsys\Concerns\InteractsWithRedsysCards; class Team extends Model { use InteractsWithRedsysCards; ... } ``` -------------------------------- ### RequestBuilder::post() Source: https://github.com/creagia/laravel-redsys Executes the request by calling create() and persisting the Request model. This method finalizes and sends the payment request. ```APIDOC ## RequestBuilder::post() ### Description Executes the request by calling create() and persisting the Request model. ### Method Instance method ### Example ```php use Creagia\LaravelRedsys\RequestBuilder; use Creagia\Redsys\Enums\Currency; use Creagia\Redsys\Enums\TransactionType; use Creagia\Redsys\Support\RequestParameters; $response = RequestBuilder::newRequest(new RequestParameters( amountInCents: $order->getTotalAmount(), currency: Currency::EUR, order: '1446068581', transactionType: TransactionType::Anulacion, ))->associateWithModel($order)->post(); ``` ``` -------------------------------- ### Credential-On-File initial request with card token Source: https://github.com/creagia/laravel-redsys Creates a request that requests a card token for recurring payments (COF) and stores the token on a user model. The request is then redirected. ```php // Credential-On-File initial request $redsysRequest = $this->productModel->createRedsysRequest( productDescription: 'Product description', payMethod: PayMethod::Card, )->requestingCardToken(CofType::Recurring)->storeCardOnModel($userModel); return $redsysRequest->redirect(); ``` -------------------------------- ### getNextOrderNumber() method declaration and usage Source: https://github.com/creagia/laravel-redsys Static helper that computes the next unique 12-digit order number. Uses config redsys.order_num_auto_prefix to enable year-month prefix and redsys.order_num_prefix as integer prefix. Returns lastNumber->order_number + 1 or $minNumber + 1. ```php public static function getNextOrderNumber(): int ``` ```php $next = Request::getNextOrderNumber(); ``` -------------------------------- ### Published config file content Source: https://github.com/creagia/laravel-redsys/blob/main/README.md This is the default configuration file published by the package. It defines the environment, TPV settings, route prefix, and order number options. The 'environment' can be 'test', 'production', or 'local'. Default test merchant code is 999008881 and default test key is sq7HjrUOBfKmC576ILgskD5srU870gJ7. ```php return [ /** * Used to define the service URL. Possible values 'test', 'production' or 'local'. * * It's recommended to use 'local' during your development to enable a local gateway to test your * application without need to expose it. */ 'environment' => env('REDSYS_ENVIRONMENT'), /** * Values sent to Redsys. */ 'tpv' => [ 'terminal' => env('REDSYS_TERMINAL', 1), 'currency' => \Creagia\Redsys\Enums\Currency::EUR, 'merchantCode' => env('REDSYS_MERCHANT_CODE'), // Default test code: 999008881 'key' => env('REDSYS_KEY'), // Default test key: sq7HjrUOBfKmC576ILgskD5srU870gJ7 ], /** * Prefix used by the package routes. 'redsys' by default. */ 'routes_prefix' => env('REDSYS_ROUTE_PREFIX', 'redsys'), /** * Route names for successful and unsuccessful confirm pages. Redsys redirects to these routes * after the payment is finished. By default, this package provides two neutral views. */ 'successful_payment_route_name' => env('REDSYS_SUCCESSFUL_ROUTE_NAME', null), 'unsuccessful_payment_route_name' => env('REDSYS_UNSUCCESSFUL_ROUTE_NAME', null), /** * Use an automatic prefix for the order number with the current year and month. */ 'order_num_auto_prefix' => true, /** * Redsys order number should be unique. Here you can set an order number prefix if you need it. * This prefix must be an integer number. */ 'order_num_prefix' => env('REDSYS_ORDER_NUM_PREFIX', 0), ]; ``` -------------------------------- ### RequestBuilder::redirect() Source: https://github.com/creagia/laravel-redsys Executes the request by calling create() and persisting the Request model, then redirects the user. This method finalizes the request and initiates a redirect. ```APIDOC ## RequestBuilder::redirect() ### Description Executes the request by calling create() and persisting the Request model, then redirects the user. ### Method Instance method ### Note This method is mentioned in the source as an alternative to post() for executing the request. ``` -------------------------------- ### Listening to Events Source: https://github.com/creagia/laravel-redsys Register listeners in App\Providers\EventServiceProvider or handle events in a listener class. ```APIDOC ## Listening to Events ### Description Register listeners in `App\Providers\EventServiceProvider` or handle events in a listener class. ### Example: Registering Listeners ```php protected $listen = [ \Creagia\LaravelRedsys\Events\RedsysNotificationEvent::class => [ LogRedsysNotification::class, ], \Creagia\LaravelRedsys\Events\RedsysSuccessfulEvent::class => [ NotifyCustomerOfSuccess::class, ], \Creagia\LaravelRedsys\Events\RedsysUnsuccessfulEvent::class => [ NotifyCustomerOfFailure::class, ], ]; ``` ### Example: Handling in a Listener ```php namespace App\Listeners; use Creagia\LaravelRedsys\Events\RedsysSuccessfulEvent; class NotifyCustomerOfSuccess { public function handle(RedsysSuccessfulEvent $event): void { $order = $event->redsysPayment->model; $order->notify(new OrderPaid($event->redsysPayment->amount, $event->notificationData)); } } ``` ``` -------------------------------- ### RedsysLocalGatewayController post method Source: https://github.com/creagia/laravel-redsys Local fake gateway POST handler. Decodes parameters, computes $authorised = RedsysResponse::isAuthorisedCode((int) $request->responseCode), builds RedsysFakeGateway with all inputs and config('redsys.tpv.key'). If DS_MERCHANT_MERCHANTURL present, synthesises internal POST to it and runs through app()->handle($request). Redirects to DS_MERCHANT_URLOK when authorised, else DS_MERCHANT_URLKO. ```php public function post(Request $request): RedirectResponse|Redirector ``` -------------------------------- ### RequestBuilder constructor signature Source: https://github.com/creagia/laravel-redsys Constructor for the RequestBuilder class. Requires a RequestParameters object holding all Redsys input parameters. Required fields for a valid transaction include amountInCents, currency, transactionType, and unless explicitly set, order, merchantUrl, urlOk, and urlKo. ```php public function __construct( RequestParameters $requestParameters, ) ``` -------------------------------- ### storeCardOnModel() Source: https://github.com/creagia/laravel-redsys Associates the resulting card token to the given Eloquent model via the `redsys_cards.model` morph. ```APIDOC ## storeCardOnModel() ### Description Associates the resulting card token to the given Eloquent model via the `redsys_cards.model` morph. ### Method storeCardOnModel ### Signature ```php public function storeCardOnModel(Model $cardModel): static ``` ### Parameters - **cardModel** (`Illuminate\Database\Eloquent\Model`) - Required - Model (e.g. `User`, `Team`) the resulting card token will be associated to via the `redsys_cards.model` morph. ### Return The same instance for chaining. Only meaningful together with `requestingCardToken()`. ``` -------------------------------- ### redirect() method signature Source: https://github.com/creagia/laravel-redsys Public method that returns an Illuminate\Http\Response containing the auto-submitting HTML form. It persists the request by calling the private create() method, which instantiates and saves the Request model first. ```php public function redirect(): Response ``` -------------------------------- ### POST {prefix}/localGateway/post Source: https://github.com/creagia/laravel-redsys Processes a local gateway post. Accepts responseCode and Ds_* fields and returns a redirect. ```APIDOC ## POST {prefix}/localGateway/post ### Description Processes a local gateway post. Accepts responseCode and Ds_* fields and returns a redirect. ### Method POST ### Endpoint {prefix}/localGateway/post ### Parameters #### Request Body - **responseCode** (string) - Required - The response code. - **Ds_* fields** (form data) - Required - The Ds_* form fields. ### Response #### Success Response (200) - **Redirect** (redirect) - Returns a redirect. ``` -------------------------------- ### RedsysSuccessfulPaymentViewController __invoke method Source: https://github.com/creagia/laravel-redsys Invokable controller returning Illuminate\View\View rendering redsys::successful. Default page shown after successful payment when custom successful_payment_route_name not configured. ```php public function __invoke(): View ``` -------------------------------- ### RequestBuilder::__construct Source: https://github.com/creagia/laravel-redsys Constructor for the RequestBuilder class. Instantiating directly requires dependent services to be resolved from the container, so the static factory newRequest() is the intended public construction path. It initializes the request parameters and fills in default values for order, merchantUrl, urlOk, and urlKo if not set. ```APIDOC ## RequestBuilder::__construct ### Description Constructor for the RequestBuilder class. Instantiating directly requires dependent services to be resolved from the container, so the static factory newRequest() is the intended public construction path. It initializes the request parameters and fills in default values for order, merchantUrl, urlOk, and urlKo if not set. ### Method Constructor ### Signature ```php public function __construct( RequestParameters $requestParameters, ) ``` ### Parameters - **requestParameters** (\Creagia\Redsys\Support\RequestParameters) - Required - Object holding all Redsys input parameters. Required fields for a valid transaction at least include `amountInCents`, `currency`, `transactionType` and (unless explicitly set) `order`, `merchantUrl`, `urlOk`, `urlKo`. ### Behavior During Construction - If `requestParameters->order` is not set (empty), it is filled with `(string) Request::getNextOrderNumber()`. - If `requestParameters->merchantUrl` is not set, it is filled with `action(\Creagia\LaravelRedsys\Controllers\RedsysNotificationController::class)` (the package notification route). - If `requestParameters->urlOk` is not set, it is filled with `route(config('redsys.successful_payment_route_name'), $this->uuid)` when that config route name is set, otherwise `action(RedsysSuccessfulPaymentViewController::class, $this->uuid)`. - If `requestParameters->urlKo` is not set, it is filled analogously using `config('redsys.unsuccessful_payment_route_name')` or `action(RedsysUnsuccessfulPaymentViewController::class, $this->uuid)`. - A new `uuid` (string) is generated via `Str::uuid()`. - `RedsysRequest::create($createClient(), $requestParameters)` builds the underlying upstream request using a `CreateRedsysClient`. ```