Skip to content

Commit

Permalink
Merge pull request #29 from TransbankDevelopers/feat/custom-eun
Browse files Browse the repository at this point in the history
Allow commerce to provide its own EUN
  • Loading branch information
Alfredo Fiebig authored Aug 29, 2018
2 parents 65f1c69 + 56e1421 commit a764597
Show file tree
Hide file tree
Showing 7 changed files with 83 additions and 19 deletions.
5 changes: 2 additions & 3 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ SHELL := /bin/bash
all: build run

run: build
docker-compose run --service-ports web
docker-compose run --rm web

test: build
docker-compose run --service-ports web sh -c './sdktest'
docker-compose run --rm web

build: .built .bundled

Expand All @@ -16,7 +16,6 @@ build: .built .bundled

.bundled: composer.json composer.lock
docker-compose run --rm web composer install
docker-compose run --service-ports web composer update
touch .bundled

logs:
Expand Down
26 changes: 20 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ automaticamente, pero si usas el SDK de manera directa requerirás también:
Para usar el SDK en tu proyecto puedes usar Composer, añadiendo el SDK como dependencia a tu proyecto:
```json
"require": {
"transbank/transbank-sdk": "1.1.1"
"transbank/transbank-sdk": "1.2.0"
}
```

Expand All @@ -48,10 +48,10 @@ Existen varias formas de configurar esta información, la cual identifica a cada

##### 1. Por variable de entorno
```bash
export ONEPAY_SHARED_SECRET = "valor de tu shared secret"
export ONEPAY_API_KEY = "valor de tu api key"
export ONEPAY_CALLBACK_URL = "valor de tu callback url"
export ONEPAY_APP_SCHEME = "valor de tu app scheme"
export ONEPAY_SHARED_SECRET="valor de tu shared secret"
export ONEPAY_API_KEY="valor de tu api key"
export ONEPAY_CALLBACK_URL="valor de tu callback url"
export ONEPAY_APP_SCHEME="valor de tu app scheme"
```

##### 2. Configurando tu API_KEY y SHARED_SECRET al inicializar tu proyecto
Expand Down Expand Up @@ -181,6 +181,19 @@ En caso que `$channel` sea `ChannelEnum::APP()` es obligatorio que esté previam
OnepayBase::setAppScheme('mi-app://mi-app/onepay-result');
```

Como comercio, también puedes querer especificar un identificador propio de transacción. Este parámetro se conoce como
`ExternalUniqueNumber` y puede ser especificado al momento de crear la transacción. La única condición es que
**debes asegurar que este identificador sea único para toda tu organización**, de lo contrario la
transacción será **rechazada**.

```php

$externalUniqueNumber = "My Unique Number - 123";
$response = Transaction::create($shoppingCart, $channel, $externalUniqueNumber;
```
Si el `ExternalUniqueNumber` no es especificado, entonces el SDK se encarga de generar un UUID, que puedes rescatar
desde la respuesta de `Transaction::create($shoppingCart, ChannelEnum::APP());` por ejemplo.

Posteriormente, se debe presentar al usuario el código QR y el número OTT para que pueda proceder al pago mediante la aplicación móvil.
##### Confirmar una transacción
Una vez que el usuario realizó el pago mediante la aplicación, dispones de 30 segundos para realizar la confirmación de la transacción, de lo contrario, se realizará automáticamente la reversa de la transacción.
Expand Down Expand Up @@ -308,4 +321,5 @@ Para ejecutar los test localmente debes usar el siguiente comando en una termina
make test
```

### Deploy de una nueva version.
### Deploy de una nueva versión.
Para generar una nueva versión en Packagist, basta con crear un nuevo release en github.
2 changes: 1 addition & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ services:
build:
context: .
dockerfile: Dockerfile
command: sh -c './sdktest'
command: sh -c './sdktest.sh'
volumes:
- .:/sdk
ports:
Expand Down
12 changes: 9 additions & 3 deletions lib/Transaction.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,20 +32,26 @@ private static function getHttpClient()

/**
* @param $shoppingCart
* @param null $options
* @param ChannelEnum|null $channel
* @param null $externalUniqueNumber
* @param null $options
* @return TransactionCreateResponse
* @throws SignException
* @throws TransactionCreateException
* @throws \Exception
*/
public static function create($shoppingCart, $channel = null, $options = null)
public static function create($shoppingCart, $channel = null, $externalUniqueNumber = null, $options = null)
{
if ($channel instanceof Options) {
$options = $channel;
$channel = null;
}

if ($externalUniqueNumber instanceof Options){
$options = $externalUniqueNumber;
$externalUniqueNumber = null;
}

if (null != $channel && $channel == ChannelEnum::APP() && null == OnepayBase::getAppScheme())
throw new TransactionCreateException('You need to set an appScheme if you want to use the APP channel');

Expand All @@ -57,7 +63,7 @@ public static function create($shoppingCart, $channel = null, $options = null)
}
$http = self::getHttpClient();
$options = OnepayRequestBuilder::getInstance()->buildOptions($options);
$request = json_encode(OnepayRequestBuilder::getInstance()->buildCreateRequest($shoppingCart, $channel, $options), JSON_UNESCAPED_SLASHES);
$request = json_encode(OnepayRequestBuilder::getInstance()->buildCreateRequest($shoppingCart, $channel, $externalUniqueNumber, $options), JSON_UNESCAPED_SLASHES);
echo $request;
$path = self::TRANSACTION_BASE_PATH . self::SEND_TRANSACTION;
$httpResponse = json_decode($http->post(OnepayBase::getCurrentIntegrationTypeUrl(), $path ,$request), true);
Expand Down
8 changes: 6 additions & 2 deletions lib/utils/OnepayRequestBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public static function getInstance()
return static::$instance;
}

public function buildCreateRequest($shoppingCart, $channel, $options = null)
public function buildCreateRequest($shoppingCart, $channel, $externalUniqueNumber = null, $options = null)
{
if (null == OnepayBase::getCallBackUrl()) {
OnepayBase::setCallbackUrl(OnepayBase::DEFAULT_CALLBACK);
Expand All @@ -31,9 +31,13 @@ public function buildCreateRequest($shoppingCart, $channel, $options = null)
$channel = OnepayBase::DEFAULT_CHANNEL();
}

if (null == $externalUniqueNumber){
$externalUniqueNumber = (int)(microtime(true) * 1000);
}

$options = self::buildOptions($options);
$issuedAt = time();
$externalUniqueNumber = (int)(microtime(true) * 1000);

$request = new TransactionCreateRequest(
$externalUniqueNumber,
$shoppingCart->getTotal(),
Expand Down
File renamed without changes.
49 changes: 45 additions & 4 deletions tests/TransactionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,6 @@ public function testTransactionRaisesWhenSignatureIsInvalid()
}
}


public function testTransactionCreationWorksTakingKeysFromGetenv()
{

Expand Down Expand Up @@ -182,8 +181,6 @@ public function testTransactionCreationWorksWithOptions()
$this->assertNotNull($response->getQrCodeAsBase64());
}



public function testTransactionCommitWorks()
{
// Setting commerce data
Expand Down Expand Up @@ -251,7 +248,6 @@ public function testTransactionCommitRaisesWhenResponseIsNull()

}


public function testTransactionCommitRaisesWhenResponseIsNotOk()
{
$mockResponse = json_encode(array('responseCode' => 'INVALID_PARAMS',
Expand Down Expand Up @@ -444,4 +440,49 @@ public function testTransactionWhenChannelAPPAndAppSchemeNotNull() {
$this->assertEquals($response->getDescription(), "OK");
$this->assertNotNull($response->getQrCodeAsBase64());
}

public function testTransactionWhenExternalUniqueNumberNull() {
OnepayBase::setAppScheme('somescheme');
$shoppingCart = new ShoppingCart();
$options = new Options("mUc0GxYGor6X8u-_oB3e-HWJulRG01WoC96-_tUA3Bg",
"P4DCPS55QB2QLT56SQH6#W#LV76IAPYX");
$firstItem = new Item("Zapatos", 1, 15000, null, -1);
$secondItem = new Item("Pantalon", 1, 12500, null, -1);

$shoppingCart->add($firstItem);
$shoppingCart->add($secondItem);

$this->assertEquals('Zapatos', $firstItem->getDescription());
$this->assertEquals('Pantalon', $secondItem->getDescription());

$response = Transaction::create($shoppingCart, ChannelEnum::APP(), null);

$this->assertEquals($response instanceof TransactionCreateResponse, true);
$this->assertEquals($response->getResponseCode(), "OK");
$this->assertEquals($response->getDescription(), "OK");
$this->assertNotNull($response->getQrCodeAsBase64());
}

public function testTransactionWhenExternalUniqueNumberPresent() {
OnepayBase::setAppScheme('somescheme');
$shoppingCart = new ShoppingCart();
$options = new Options("mUc0GxYGor6X8u-_oB3e-HWJulRG01WoC96-_tUA3Bg",
"P4DCPS55QB2QLT56SQH6#W#LV76IAPYX");
$firstItem = new Item("Zapatos", 1, 15000, null, -1);
$secondItem = new Item("Pantalon", 1, 12500, null, -1);

$shoppingCart->add($firstItem);
$shoppingCart->add($secondItem);

$this->assertEquals('Zapatos', $firstItem->getDescription());
$this->assertEquals('Pantalon', $secondItem->getDescription());

$response = Transaction::create($shoppingCart, ChannelEnum::APP(), "ABC123");

$this->assertEquals(true, $response instanceof TransactionCreateResponse);
$this->assertEquals("OK", $response->getResponseCode());
$this->assertEquals("OK", $response->getDescription());
$this->assertNotNull($response->getQrCodeAsBase64());
$this->assertEquals("f506a955-800c-4185-8818-4ef9fca97aae", $response->getExternalUniqueNumber());
}
}

0 comments on commit a764597

Please sign in to comment.