GithubHelp home page GithubHelp logo

bbva-php's Introduction

Bbva PHP

PHP client for Bbva API services (version 1.0.0)

This is a client implementing the payment services for Bbva at bbva.mx

What's new?

Compatibility

PHP 5.2 or later

Requirements

PHP 5.2 or later cURL extension for PHP JSON extension for PHP Multibyte String extension for PHP

Installation

Composer

The preferred method is via composer. Follow the installation instructions if you do not already have composer installed.

Once composer is installed, execute the following command in your project root to install this library:

composer require bbva/sdk dev-master

Finally, be sure to include the autoloader:

require_once '/path/to/your-project/vendor/autoload.php';

Manual installation

To install, just:

  • Clone the repository or download the library and copy/create a folder named 'Bbva' inside your project folder structure. If you downloaded the client library as a compressed file, uncompress it and create the proper folder structure.
  • At the top of the PHP script in which the client library will be used (or in the section you include other libraries), add the client's library main script:
require(dirname(__FILE__) . '/Bbva/Bbva.php');

NOTE: In the example above, the library is located in the directory named Bbva, located inside the same directory that the PHP file which is including the cliente. Make sure to adjust the paths inside your project, otherwise the library will not work.

Implementation

Configuration

Before use the library will be necessary to set up your Merchant ID and Private key. There are three options:

  • Use the methods Bbva::setId() and Bbva::setApiKey(). Just pass the proper parameters to each function:
Bbva::setId('moiep6umtcnanql3jrxp');
Bbva::setApiKey('sk_3433941e467c4875b178ce26348b0fac');
  • Pass Merchant ID and Private Key as parameters to the method Bbva::getInstance(), which is the instance generator:
$bbva = Bbva::getInstance('moiep6umtcnanql3jrxp', 'sk_3433941e467c4875b178ce26348b0fac');
  • Configure the Marchant ID and the Private Key as well, as environment variables. This method has its own advantages as this sensitive data is not exposed directly in any script.

NOTE: please, refer to PHP documentation for further information about this method.

Sandbox/Production Mode

By convenience and security, the sandbox mode is activated by default in the client library. This allows you to test your own code when implementing Bbva, before charging any credit card in production environment. Once you have finished your integration, use the method Bbva::setProductionMode(FLAG) which will allow you to active/inactivate the sandbox mode.

Bbva::setProductionMode(true);

Also you can use environment variables for this purpose:

SetEnv BBVA_PRODUCTION_MODE true

If its necessary, you can use the method Bbva::getProductionMode() to determine anytime, which is the sandbox mode status:

// will return TRUE/FALSE, depending on if sandbox mode is activated or not.
Bbva::getProductionMode(); 

PHP client library intro

Once configured the library, you can use it to interact with Bbva API services. The first step is get an instance with the generator:

$bbva = Bbva::getInstance('mptdggroasfcmqs8plpy', 'sk_326c6d0443f6457aae29ffbd48f7d1be');

In this example $bbva will be an instance of a merchant (root), wich will be used to call any derived child resource. According to the current version of the Bbva API, these resources are:

  • charges
  • tokens

You can access all of these resources as public variables of the root instance, so, if you want to add a new customer you will be able to do it as follows:

$bbva->tokens->add(PARAMETERS);

Every call to any resource will return an instance of that resource. In the example above, calling the method add() in the resource tokens will return an instance of Token, calling the method add() in the resource tokens will return an instance of Card, and so on. The only exception occurs when you retrieve a list of resources using the method getList(), in which case an array of instances will be returned:

// a SINGLE instance of Customer will be returned
$charge = $bbva->charges->add(PARAMETERS);


// an ARRAY of instances of Customers will be returned
chargersList = $bbva->charges->getList(PARAMETERS);

On the other hand, the resources derived from Charge, according to Bbva API documentation, are:

  • charges
  • tokens

Parameters

Those methods which receive more than one parameter (for example, when trying to add a new customer or a new customer's card), must be passed as associatives arrays:

array('PARAMETER_INTEGER' => VALUE,
      'PARAMETER_STRING'  => 'VALUE');
      'PARAMETER_DERIVED' => array('PARAMETER_INTEGER' => VALUE), 
                                   'PARAMETER_STRING'  => 'VALUE'));

NOTE: Please refer to Bbva API docuemntation to determine wich parameters are accepted, wich required and which of those are optional, in every case.

Error handling

The Bbva API generates several types of errors depending on the situation, to handle this, the PHP client has implemented five type of exceptions:

  • BbvaApiTransactionError. This category includes those errors ocurred when the transaction does not complete successfully: declined card, insufficient funds, inactive destination account, etc.
  • BbvaApiRequestError. It refers to errors generated when a request to the API fail. Examples: invalid format in data request, incorrect parameters in the request, Bbva internal servers errors, etc.
  • BbvaApiConnectionError. These exceptions are generated when the library try to connect to the API but fails in the attempt. For example: timeouts, domain name servers, etc.
  • BbvaApiAuthError. Errors which are generated when the authentication data are specified in an invalid format or, if are not fully validated on the Bbva server (Merchant ID or Private Key).
  • BbvaApiError. This category includes all generic errors when processing with the client library.

All these error exceptions make available all the information returned by the Bbva API, with the following methods:

  • getDescription(): Error description generated by Bbva server.
  • getErrorCode(): Error code generated by Bbva server. When the error is generated before the request, this value is equal to zero.
  • getCategory(): Error category generated and determined by Bbva server. When the error is generated before or during the request, this value is an empty string.
  • getHttpCode(): HTTP error code generated when request the Bbva server. When the error is generated before or during the request, this value is equal to zero.
  • getRequestId(): ID generated by the Bbva server when process a request. When the error is generated before the request, this value is an empty string.

The following is an more complete example of error catching:

try {
	Bbva::setProductionMode(true);
	
	// the following line will generate an error because the
	// private key is empty. The exception generated will be
	// a BbvaApiAuthError
	$bbva = Bbva::getInstance('mptdggroasfcmqs8plpy', '');

	$customer = $bbva->customers->get('a9ualumwnrcxkl42l6mh');
 	$customer->name = 'Juan';
 	$customer->last_name = 'Godinez';
 	$customer->save();

} catch (BbvaApiTransactionError $e) {
	error_log('ERROR on the transaction: ' . $e->getMessage() . 
	      ' [error code: ' . $e->getErrorCode() . 
	      ', error category: ' . $e->getCategory() . 
	      ', HTTP code: '. $e->getHttpCode() . 
	      ', request ID: ' . $e->getRequestId() . ']', 0);

} catch (BbvaApiRequestError $e) {
	error_log('ERROR on the request: ' . $e->getMessage(), 0);

} catch (BbvaApiConnectionError $e) {
	error_log('ERROR while connecting to the API: ' . $e->getMessage(), 0);

} catch (BbvaApiAuthError $e) {
	error_log('ERROR on the authentication: ' . $e->getMessage(), 0);
	
} catch (BbvaApiError $e) {
	error_log('ERROR on the API: ' . $e->getMessage(), 0);
	
} catch (Exception $e) {
	error_log('Error on the script: ' . $e->getMessage(), 0);
}

Examples

Customers

Add a new customer to a merchant:

$bbva = Bbva::getInstance('mptdggroasfcmqs8plpy', 'sk_326c6d0443f6457aae29ffbd48f7d1be');

$customerData = array(
	'name' => 'Teofilo',
	'last_name' => 'Velazco',
	'email' => '[email protected]',
	'phone_number' => '4421112233',
	'address' => array(
			'line1' => 'Privada Rio No. 12',
			'line2' => 'Co. El Tintero',
			'line3' => '',
			'postal_code' => '76920',
			'state' => 'Querétaro',
			'city' => 'Querétaro.',
			'country_code' => 'MX'));

Tokens

On a merchant:

Add a token:

$bbva = Bbva::getInstance('mptdggroasfcmqs8plpy', 'sk_326c6d0443f6457aae29ffbd48f7d1be');

$tokenData = array(
	'holder_name' => 'Luis Pérez',
	'card_number' => '4111111111111111',
	'cvv2' => '123',
	'expiration_month' => '12',
	'expiration_year' => '15',
	'address' => array(
		'line1' => 'Av. 5 de Febrero No. 1',
		'line2' => 'Col. Felipe Carrillo Puerto',
		'line3' => 'Zona industrial Carrillo Puerto',
		'postal_code' => '76920',
		'state' => 'Querétaro',
		'city' => 'Querétaro',
		'country_code' => 'MX'));

$token = $bbva->tokens->add($tokenData);

Get a token:

$bbva = Bbva::getInstance('mptdggroasfcmqs8plpy', 'sk_326c6d0443f6457aae29ffbd48f7d1be');

$token = $bbva->tokens->get('k9pn8qtsvr7k7gxoq1r5');

Charges

On a Merchant:

Make a charge on a merchant:

$bbva = Bbva::getInstance('mptdggroasfcmqs8plpy', 'sk_326c6d0443f6457aae29ffbd48f7d1be');

$chargeData = array(
	'affiliation_bbva' => '781500',
	'amount' => 100,
	'currency' => 'MXN',
	'order_id' => 'ORDEN-00071',
	'customer' => array(
		'name' => 'Teofilo',
		'last_name' => 'Velazco',
		'email' => '[email protected]',
		'phone_number' => '4421112233',
		'address' => array(
			'line1' => 'Privada Rio No. 12',
			'line2' => 'Co. El Tintero',
			'line3' => '',
			'postal_code' => '76920',
			'state' => 'Querétaro',
			'city' => 'Querétaro.',
			'country_code' => 'MX')),
	'description' => 'Cargo inicial a mi merchant'
	'redirect_url' => 'https://sand-portal.ecommercebbva.com/'
	);

$charge = $bbva->charges->create($chargeData);

Get a charge:

$bbva = Bbva::getInstance('mptdggroasfcmqs8plpy', 'sk_326c6d0443f6457aae29ffbd48f7d1be');

$charge = $bbva->charges->get('tvyfwyfooqsmfnaprsuk');

Make a capture:

$bbva = Bbva::getInstance('mptdggroasfcmqs8plpy', 'sk_326c6d0443f6457aae29ffbd48f7d1be');

$captureData = array('amount' => 150.00 );

$charge = $bbva->charges->get('tvyfwyfooqsmfnaprsuk');
$charge->capture($captureData);

Make a refund:

$bbva = Bbva::getInstance('mptdggroasfcmqs8plpy', 'sk_326c6d0443f6457aae29ffbd48f7d1be');

$refundData = array('description' => 'Devolución' );

$charge = $bbva->charges->get('tvyfwyfooqsmfnaprsuk');
$charge->refund($refundData);

bbva-php's People

Contributors

mguevara-openpay avatar carloshe-perez avatar ecommercebbva avatar

Stargazers

Luis Gonzalez avatar  avatar Emilio Luna avatar Alberto avatar  avatar

Watchers

Renato Castañeda avatar Zart182 avatar Israel Grijalva avatar  avatar

bbva-php's Issues

Call to undefined method stdClass::get()

Hola, estoy tratando de obtener un cargo de un customer. pero al momento de querer usar la función me marca un error. Seguí todos los pasos para instalar la librería(estoy usando php). Pero me da muchos problemas con la instancia customer.
El error es el siguiente.
[Thu Mar 25 16:46:45.640632 2021] [php7:error] [pid 9108] [client ::1:36166] PHP Fatal error: Uncaught Error: Call to undefined method stdClass::get() in /var/www/html/bbvaApi/createCustomer/index.php:42\nStack trace:\n#0 /var/www/html/bbvaApi/createCustomer/index.php(101): ApiBbvaConfiguration->addCustomer()\n#1 {main}\n thrown in /var/www/html/bbvaApi/createCustomer/index.php on line 42

Redirección

Buenos días,

¿Existe alguna forma de hacer un pago mediante redirección como se hacía antiguamente en la pasarela de BBVA Bancomer? Que llegaba a un portal del banco y luego volvía al comercio electrónico.

Muchas gracias de antemano.

No se descarga la librería bbva/sdk

Estoy trabajando en Linux, tengo instalado PHP 7.2, ya instalé composer y al momento de querer descargar la librería con el comando: composer require bbva/sdk dev-master me sale el siguiente mensaje de error:
[InvalidArgumentException]
Could not find a matching version of package bbva/sdk. Check the package spelling, your version constraint and that the package is available in a stability which matches your minimum-stability (stable).

Problema con MSI

En la certificación hay dos casos, uno con Meses sin Intereses, y otro con Meses sin Intereses y meses diferidos
El último caso pasa sin ningún problema
el primero me da error 1001 400, que está mal formado el mensaje
Pero uso el mismo código para ambos casos

Código que no funciona:
$chargeData = array( 'affiliation_bbva' => $afiliation_bbva, 'amount' => '3500.33', 'currency' => 'MXN', 'order_id' => 'ORDEN-' . $num_serie, 'customer' => array( 'name' => 'Teófilo', 'last_name' => 'Velazco', 'email' => '[email protected]', 'phone_number' => '4421112233', ), 'description' => 'SKIP Payment MSI', 'redirect_url' => 'https://codigonube.com/bbva/poc-back.php', 'use_3d_secure' => true, 'payment_plan' => [ 'payments' => 6, 'payments_type'=> 'WITHOUT_INTEREST' ] );

Y el que si funciona es:
$chargeData = array( 'affiliation_bbva' => '360315', 'amount' => '3500.33', 'currency' => 'MXN', 'order_id' => 'ORDEN-' . $num_serie, 'customer' => array( 'name' => 'Teófilo', 'last_name' => 'Velazco', 'email' => '[email protected]', 'phone_number' => '4421112233', ), 'description' => 'SKIP Payment MSI', 'redirect_url' => 'https://codigonube.com/bbva/poc-back.php', 'use_3d_secure' => true, 'payment_plan' => [ 'payments' => 6, 'payments_type'=> 'WITHOUT_INTEREST', 'deferred_months' => 3 ] );

Class 'Bbva' not found

Bbva::getInstance('', '');
al momento de instanciar la clase de Bbva me sale un erro de php que dice que la clase no se encuentra
Uncaught Error: Class 'Bbva' not found.

Uncaught Error: Class "Bbva\Data\BbvaApiResourceBase" not found

Hi im starting use this project, i download from composer, and when i call the class principal for test y got this error Uncaught Error: Class "Bbva\Data\BbvaApiResourceBase" not found

this is my file .php

<?php 
require(dirname(__FILE__) . '/bbva/Bbva/Bbva.php');

?>

Request method 'POST' not supported

Al realizar un cargo con tarjeta me devuelve el siguiente mensaje de error

{"http_code":405,"error_code":1000,"category":"request","description":"Request method 'POST' not supported","request_id":"X"}

La url donde realizo la petición es https://sand-api.ecommercebbva.com/v1

Y el error aparece cuando ejecuto la función

$bbva->charges->create($params);

¿Hay algo que no esté haciendo bien?

cómo estás accediendo a los datos de json?

cómo estás accediendo a los datos de json?

Originally posted by @Grimmgalohm in #4 (comment)

Implemente esto, por que mire que si regresa los datos pero no puedo acceder a ellos

$bbva = Bbva::getInstance($keyID, $idSDK);

        $chargeRequest = array(
            'affiliation_bbva' =>$BBVAaffiliation',
            'amount' => 100,
            'description' => 'Cargo inicial a mi merchant',
            'currency' => 'MXN',
            'order_id' => 'oid-' . $idCarrito,
            'redirect_url' => 'https://sand-portal.ecommercebbva.com',
            'customer' => array(
                'name' => 'Juan',
                'last_name' => 'Vazquez Juarez',
                'email' => '[email protected]',
                'phone_number' => '554-170-3567'
            )
        );

        $charge = $bbva->charges->create($chargeRequest);
        $array = (array)  $charge;
        foreach ($array as $key => $val) {
            $new_array[str_replace('*', '', $key)] = $val;
        }
        foreach ($new_array as $key => $val) {
            $new_array2[str_replace(' ', '', $key)] = $val;
        }

Undefined property: stdClass::$resourceName

Que tal compañeros, disculpen estoy haciendo una intergracion con VPOS y 3dSecure activado, pero al momento de hacer el

$charge = $bbva->charges->create($chargeRequest);

Me arroja un error en la biblioteca:
Undefined property: stdClass::$resourceName
file: "../Bbva/data/BbvaApiResourceBase.php"
line: 161
message: "Undefined property: stdClass::$resourceName"
name: "PHP Notice"

Saben que podría ser? Estoy siguiendo el código ejemplo del README, espero puedan ayudarme, gracias!

> > No, el error es claro, tu número de afiliación es erróneo, revisa bien tus instancias de la clase para que veas que la clave es correcta, e incluso revisa que estés en modo sandbox porque al parecer ese número es sandbox

¿Nos puedes compartir el segmento de tu código donde instancias el pago?

ya pude resolverlo a hora solo me falta saber si el pago paso o no y como puedo extraer los datos este es mi codigo

$bbva = Bbva::getInstance('mptdggroasfcmqs8plpy', 'sk_326c6d0443f6457aae29ffbd48f7d1be');
Bbva::setSandboxMode(TRUE);
$chargeRequest = array(
'affiliation_bbva' => '781500',
'amount' => 100,
'description' => 'Cargo Venta',
'currency' => 'MXN',
'order_id' => 'FH-00003',
'redirect_url' => 'https://sand-portal.ecommercebbva.com',
'card' => array(
'holder_name' => 'Juan Vazquez',
'card_number' => '4242424242424242',
'expiration_month' => '12',
'expiration_year' => '28',
'cvv2' => '842'),
'customer' => array(
'name' => 'Juan',
'last_name' => 'Vazquez Juarez',
'email' => '[email protected]',
'phone_number' => '554-170-3567')
);

$charge = $bbva->charges->create($chargeRequest);

BBVA Openpay

La base de BBVA es Openpay,
Si installo sdk de openpay y pongo link, marchant id, key etc, todo va funcionar bien de misma manera o no.
Cual es diferencia entre BBVA y OpenPay ?
Gracias

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.