laragear/transbank

Easy-to-use Transbank SDK for PHP.

v2.0.0 2024-03-06 20:04 UTC

This package is auto-updated.

Last update: 2024-06-13 07:11:57 UTC


README

Latest Version on Packagist Latest stable test run Codecov coverage Maintainability Sonarcloud Status Laravel Octane Compatibility

Easy-to-use Transbank SDK for PHP for Webpay, Webpay Mall and Oneclick Mall.

use Laragear\Transbank\Facades\Webpay;
use Laragear\Transbank\Http\Requests\WebpayRequest;

public function pay(Request $request)
{
    return Webpay::create('pink teddy bear', 1990, url('confirm'));
}

public function confirm(WebpayRequest $payment)
{
    if ($payment->isSuccessful()) {
        return 'Your pink teddy bear is on the way!';
    };
}

Note

Only supports Webpay at the moment. Webpay Mall and Oneclick Mall are planned based on support.

Become a sponsor

Your support allows me to keep this package free, up-to-date and maintainable. Alternatively, you can spread the word!

Requisites:

  • Laravel 10, or later

Installation

You can install the package via Composer:

composer require laragear/transbank

Usage

This SDK mimics all the Webpay methods from the official Transbank SDK for PHP.

You can check the documentation of these services in Transbank Developer's site.

Quickstart

Use the service facade you want to make a payment for.

For example, to make a payment request, use Webpay::create(), along with the URL to return to your application once the payment is done.

use Laragear\Transbank\Facades\Webpay;

public function pay(Request $request)
{
    return Webpay::create('pink teddy bear', 1990, route('confirm'));
}

Once done, you can confirm the payment using the convenient WebpayRequest in your controller.

use Laragear\Transbank\Http\Requests\WebpayRequest;

public function confirm(WebpayRequest $request)
{
    $transaction = $request->transaction();
    
    if ($transaction->isSuccessful()) {
        return 'Your pink teddy bear is on the way!';
    };
}

Environments and credentials

By default, this SDK starts up in integration environment, where all transactions made are fake by using Transbank's own integration server, and it comes with integration credentials.

Transbank will give you production credentials for each service you have contracted. You can them set them conveniently using the .env file.

WEBPAY_KEY=597055555532
WEBPAY_SECRET=579B532A7440BB0C9079DED94D31EA1615BACEB56610332264630D42D0A36B1C

To operate in production mode, where all transaction will be real, you will need set the environment to production explicitly in using your .env environment file.

TRANSBANK_ENV=production

Note

Production keys don't work on integration and vice versa.

Middleware endpoint protection

You may want to use the included transbank.protect middleware to validate the transaction response from Transbank (the route which Transbank returns the user to). It will void any request without the proper tokens.

use Illuminate\Support\Facades\Route;

Route::get('confirm', function (WebpayRequest $request) {
    // ...
})->middleware('transbank.handle')

Additionally, you can enable endpoint protection to only let Transbank requests to be allowed into the application.

Transaction Failure Middleware

Transbank failure responses for transactions are sent using a POST request. This disrupts the session because these come back without cookies, hence a new empty session is generated. This renders authentication useless and loses refers or intended URLs.

To avoid that, use the convenient RouteRedirect facade to create a ready-made route that handles the POST failure request back to your application. When this redirection is processed, your browser sends its cookies to the application, recovering the session.

use Illuminate\Support\Facades\Route;
use Laragear\Transbank\Http\Requests\WebpayRequest;
use Laragear\Transbank\Facades\RouteRedirect;

Route::get('confirm', function (WebpayRequest $request) {
    // ...
})->middleware('transbank.protect');

RouteRedirect::as('confirm');

By default, the redirection uses the same path, but you can change it using a second parameter.

use Illuminate\Support\Facades\Route;
use Laragear\Transbank\Http\Requests\WebpayRequest;
use Laragear\Transbank\Facades\RouteRedirect;

Route::get('confirm', function (WebpayRequest $request) {
    // ... Handle the successful transaction.
})->middleware('transbank.protect');

Route::get('failed-transaction', function () {
    // ... Handle the failed transaction.
})->middleware('transbank.protect');

RouteRedirect::as('confirm', 'failed-transaction');

Important

If you're using you own middleware to verify CSRF/XSRF tokens, set the class in RouteRedirect::$csrfMiddleware.

Events

You will be able to hear all transactions started and completed. This package sends the following events:

  • TransactionCreating before a transaction is created in Transbank.
  • TransactionCreated after a transaction is created in Transbank, but pending payment.
  • TransactionCompleted after a transaction or refund is completed in Transbank, regardless of the success.

Exceptions

All exceptions implement TransbankException, so you can easily catch and check what happened.

Important

Transactions properly rejected by banks or credit card issuers do not throw exceptions.

There are 4 types of exceptions:

  • ClientException: Any error byproduct of bad transactions, misconfiguration, aborts, abandonment, timeout or invalid values.
  • ServerException: Any internal Transbank servers errors.
  • NetworkException: Any communication error from Transbank Server, like network timeouts or wrong endpoints.
  • UnknownException: Any other error.

Advanced configuration

There is a handy configuration file you can use if you need nitpicking. Publish it with Artisan:

php artisan vendor:publish --provider="Laragear\Transbank\TransbankServiceProvider" --tag="config"

You will receive the config/transbank.php file with the following contents:

<?php

return [
    'environment' => env('TRANSBANK_ENV'),
    'http' => [
        'timeout' => 10,
        'retries' => 3,
        'options' => [
            'synchronous' => true
        ]
    ],
    'credentials' => [
        // ...
    ],
    'protect' => [
        'enabled' => false,
        'store' => env('TRANSBANK_PROTECT_CACHE'),
        'prefix' => 'transbank|token',
    ],
]

Environment

return [
    'environment' => env('TRANSBANK_ENV'),
]

To use this package on production environment, you will have to explicitly enable it using production. To do that, use your .env file.

TRANSBANK_ENV=production

This will instruct the package to use the production server for Transbank services. You should use this in combination with your production credentials.

HTTP Client

return [
    'http' => [
        'timeout' => 10,
        'retries' => 3,
        'options' => [
            'synchronous' => true
        ]
    ],
]

This array handles how much time to wait per request made to Transbank, how many retries, and any other raw option to pass to the underlying Guzzle HTTP Client.

Credentials

return [
    'credentials' => [
        // ...
    ],
]

This array holds each pair of credentials (key & secret) for each service. This package comes with integration credentials already set, so you can get right away on development and testing.

Endpoint protection

return [
    'protect' => [
        'enabled' => false,
        'store' => env('TRANSBANK_PROTECT_CACHE'),
        'prefix' => 'transbank|token',
    ],
]

Disabled by default, you can further protect your endpoints using the transbank.protect middleware. Once enabled, it will save the token of every transaction created by 5 minutes, and once Transbank returns the user with the token, abort the request if it was not generated or was expired.

This also handles which cache store to use, and which prefix to use when storing the tokens into the cache.

Licence

This specific package version is licensed under the terms of the MIT License, at time of publishing.

Laravel is a Trademark of Taylor Otwell. Copyright © 2011-2022 Laravel LLC.

Redcompra, Webpay, Oneclick, Onepay, Patpass and Transbank are trademarks of Transbank S.A.. This package and its author are not associated with Transbank S.A.