Run the following command
composer require gjae/laravel-mercadopago
In your config/app.php
file add the following lines (ONLY FOR LARAVEL VERSIONS <= 5.4):
in your service providers array ( providers ):
Gjae MercadoPago MPServiceProvider::class,
add the following facade to your list of aliases (ONLY FOR LARAVEL VERSIONS <= 5.4):
' MercadoPago ' => Gjae MercadoPago Facade::class,
finally run the following command:
php artisan vendor:publish -- provider ="Gjae MercadoPago MPServiceProvider "
And finally run the migrations:
php artisan migrate
Now go to the config/mercadopago.php
file and add your configuration, your file will look similar to this:
<?php
return [
/**
* Si es verdadero entonces no se validan las credenciales
* en mercadopago
*/
' local_debug ' => true ,
/**
* Especifica el modo en el que se estara usando
* el mercado pago, : sandbox, production
*/
' mode ' => ' sandbox ' ,
/**
* Credenciales para el caso en que la aplicacion este en modo
* produccion (especificado en la clave mode)
*/
' production ' => [
' access_token ' => env ( ' MP_ACCESS_TOKEN ' , '' ),
' public_key ' => env ( ' MP_PUBLIC_KEY ' , '' ),
],
/**
* Credenciales para el modo sandbox
* especificado el uso en la clave "mode"
*/
' sandbox ' => [
' access_token ' => env ( ' MP_SANDBOX_ACCESS_TOKEN ' , '' ),
' public_key ' => env ( ' MP_SANDBOX_PUBLIC_KEY ' , '' )
],
/**
* Tipo de identificacion usada para los pagos
*/
' identification_type ' => ' DNI ' ,
/**
* Codigo de area telefonico
*/
' area_code ' => '' ,
/**
* Especifica las URL de retorno para el smartcheckout
*/
' back_urls ' => [
' success ' => '' ,
' failure ' => '' ,
' pending ' => '' ,
],
// Indica en que caso de respuesta del pago se ejecutara una autorecarga
// Por defecto: approved (el usuario pagador volvera automaticamente en caso de que el pago haya sido completado y aprobado)
' auto_return ' => ' approved ' ,
];
To start using the library you only need to call the MercadoPago facade (or whatever you have named it in the aliases arrangement of your config.php
file), calling the begin method which has as a parameter a callback function that will receive the transaction itself as a parameter, example:
MercadoPago:: begin ( function ( $ mp ){
// agrega un item al procesamiento
$ mp -> addItem ([
' title ' => ' Prueba ' , // Titulo del item
' qtty ' => 1 , // Cantidad del item
' price ' => 150.0 , // Precio unitario
' currency ' => ' USD ' , // MONEDA USADA PARA PAGAR
' id ' => " MYAWESOMEPRODUCTID " // ID DEL PRODUCTO (PARA CONTROL INTERNO DE SU APLICACIÓN)
]);
// OPCIONAL: el metodo backUrlAddQS agregara parametros adicionales a la URL de pago, dichos parametros seran devueltos al completar la transaccipon
// usado para control interno de su propia aplicación, si desea agregar un token o ID de seguridad a su proceso
$ mp -> backUrlAddQS ([ ' foo ' => " bar " ]);
});
The addItem method can be called as many times as you consider necessary to add the items you need to charge to the payment. Finally, in your response view
The initPoint method of the MercadoPago facade will be available (example of view code):
<!DOCTYPE html >
< html lang =" en " >
< head >
< meta charset =" UTF-8 " >
< meta name =" viewport " content =" width=device-width, initial-scale=1.0 " >
< meta http-equiv =" X-UA-Compatible " content =" ie=edge " >
< title > Redirigiendo a MercadoPago para procesar su compra </ title >
</ head >
< body >
< input type =" hidden " name =" redirect-mp " id =" mp " value =" {{ MercadoPago::initPoint() }} " >
< script >
window . location = document . getElementById ( 'mp' ) . value
</ script >
</ body >
</ html >
The responses returned by the payment gateway must be controlled from their routes and added to the configuration file ( config/mercadopago.php
).
In the routes associated with the response (configured in the configuration file), call the MPResponse class and use dependency injection to process the response, example:
<?php
. . .
use Gjae MercadoPago Contracts MPResponse ;
class MercadoPagoController extends Controller
{
public function successResponse ( MPResponse $ request )
{
. . .
}
}
The injected MPResponse object will automatically save the response data for you.
Additionally you can associate models with your transaction, for this you must go to your Eloquent model class and implement the HasTransaction interface and the HasTransactions trait included in the package:
namespace App ;
. . .
use Illuminate Database Eloquent Model ;
use Gjae MercadoPago Contracts HasTransaction ;
use Gjae MercadoPago Traits HasTransactions ;
class MyAwesomeModel extends Model implements HasTransaction{
use HasTransactions;
. . .
}
Having done this, you can pass as the second parameter to the begin function, an object (or array of objects) of any class that implements the HasTransaction interface:
MercadoPago:: begin ( function ( $ mp ){
. . .
}, [ $ HasTransactionObjects ]);
Objects that implement the HasTransaction
interface and the HasTransactions
trait have the transactions extension that returns a collection of transactions related to said object:
$ user = App User:: first ();
$ user -> transactions ;
The MPResponse object that is injected into the controller has the getTransaction method that returns the data of the received transaction
public function successResponse ( MPResponse $ request )
{
$ transaction = $ request -> getTransaction ();
}
When the configuration file has the "local_debug" option set to true; An init_point will not be issued with the Mercadopago URL, this is so that the user does not create transactions that will not be carried out within the gateway and can calmly test the operation without waiting for responses from the Mercadopago server without need, when he is ready to test. full operation whether in production or in sandbox mode, change this option to false