Completed
Push — master ( 8c9a49...c1ae1c )
by angel
04:08 queued 01:56
created

InstapagoPayment::cancelPayment()   B

Complexity

Conditions 2
Paths 4

Size

Total Lines 24
Code Lines 15

Duplication

Lines 24
Ratio 100 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 24
loc 24
rs 8.9713
cc 2
eloc 15
nc 4
nop 1
1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 40 and the first side effect is on line 32.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
3
/**
4
 * The MIT License (MIT)
5
 * Copyright (c) 2016 Angel Cruz <[email protected]>.
6
 *
7
 * Permission is hereby granted, free of charge, to any person obtaining a copy
8
 * of this software and associated documentation files (the “Software”), to deal
9
 * in the Software without restriction, including without limitation the rights
10
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
 * copies of the Software, and to permit persons to whom the Software is
12
 * furnished to do so, subject to the following conditions:
13
 *
14
 * The above copyright notice and this permission notice shall be included in
15
 * all copies or substantial portions of the Software.
16
 *
17
 * THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23
 * THE SOFTWARE.
24
 *
25
 * @author Angel Cruz <[email protected]>
26
 * @license MIT License
27
 * @copyright 2016 Angel Cruz
28
 */
29
30
namespace Instapago\InstapagoGateway;
31
32
require __DIR__ . '/../../vendor/autoload.php';
33
34
use Instapago\InstapagoGateway\Exceptions\InstapagoException;
35
use GuzzleHttp\Client as Client;
36
37
/**
38
 * Clase para la pasarela de pagos Instapago.
39
 */
40
class InstapagoPayment
41
{
42
    protected $keyId;
43
    protected $publicKeyId;
44
    public $cardHolder;
45
    public $cardHolderId;
46
    public $cardNumber;
47
    public $cvc;
48
    public $expirationDate;
49
    public $amount;
50
    public $description;
51
    public $statusId;
52
    public $ipAddres;
53
    public $idPago;
54
55
    /**
56
     * Crear un nuevo objeto de Instapago.
57
     *
58
     * @param string $keyId       llave privada
59
     * @param string $publicKeyId llave publica
60
     *                            Requeridas.
61
     */
62
    public function __construct($keyId, $publicKeyId)
63
    {
64
        try {
65
            if (empty($keyId) && empty($publicKeyId)) {
66
                throw new InstapagoException('Los parámetros "keyId" y "publicKeyId" son requeridos para procesar la petición.');
67
            }
68
69
            if (empty($keyId)) {
70
                throw new InstapagoException('El parámetro "keyId" es requerido para procesar la petición. ');
71
            }
72
73
            if (empty($publicKeyId)) {
74
                throw new InstapagoException('El parámetro "publicKeyId" es requerido para procesar la petición.');
75
            }
76
77
            $this->publicKeyId = $publicKeyId;
78
            $this->keyId = $keyId;
79
        } catch (InstapagoException $e) {
80
            echo $e->getMessage();
81
        } // end try/catch
82
    }
83
84
    /**
85
     * Crear un pago
86
     * Efectúa un pago con tarjeta de crédito, una vez procesado retornar una respuesta.
87
     * https://github.com/abr4xas/php-instapago/blob/master/help/DOCUMENTACION.md#crear-un-pago.
88
     */
89
    public function payment($amount, $description, $cardHolder, $cardHolderId, $cardNumber, $cvc, $expirationDate, $statusId, $ipAddres)
90
    {
91
        try {
92
            $params = [$amount, $description, $cardHolder, $cardHolderId, $cardNumber, $cvc, $expirationDate, $statusId, $ipAddres];
93
            $this->checkRequiredParams($params);
94
95
            $this->amount = $amount;
96
            $this->description = $description;
97
            $this->cardHolder = $cardHolder;
98
            $this->cardHolderId = $cardHolderId;
99
            $this->cardNumber = $cardNumber;
100
            $this->cvc = $cvc;
101
            $this->expirationDate = $expirationDate;
102
            $this->statusId = $statusId;
103
            $this->ipAddres = $ipAddres;
104
105
            $url = 'payment'; // endpoint
106
107
            $fields = [
108
                'KeyID'             => $this->keyId, //required
109
                'PublicKeyId'       => $this->publicKeyId, //required
110
                'amount'            => $this->amount, //required
111
                'description'       => $this->description, //required
112
                'cardHolder'        => $this->cardHolder, //required
113
                'cardHolderId'      => $this->cardHolderId, //required
114
                'cardNumber'        => $this->cardNumber, //required
115
                'cvc'               => $this->cvc, //required
116
                'expirationDate'    => $this->expirationDate, //required
117
                'statusId'          => $this->statusId, //required
118
                'IP'                => $this->ipAddres, //required
119
            ];
120
121
            $obj = $this->curlTransaccion($url, $fields, 'POST');
122
            $result = $this->checkResponseCode($obj);
123
124
            return $result;
125
        } catch (InstapagoException $e) {
126
            echo $e->getMessage();
127
        } // end try/catch
128
    }
129
130
    /**
131
     * Completar Pago
132
     * Este método funciona para procesar un bloqueo o pre-autorización
133
     * para así procesarla y hacer el cobro respectivo.
134
     * Para usar este método es necesario configurar en `payment()` el parametro statusId a 1
135
     * https://github.com/abr4xas/php-instapago/blob/master/help/DOCUMENTACION.md#completar-pago.
136
     */
137
138
    public function continuePayment($idPago, $amount)
139
    {
140
        try {
141
            $params = [$idPago, $amount];
142
            $this->checkRequiredParams($params);
143
144
            $this->idPago = $idPago;
145
            $this->amount = $amount;
146
147
            $url = 'complete'; // endpoint
148
149
            $fields = [
150
                'KeyID'             => $this->keyId, //required
151
                'PublicKeyId'       => $this->publicKeyId, //required
152
                'id'                => $this->idPago, //required
153
                'amount'            => $this->amount, //required
154
            ];
155
156
            $obj = $this->curlTransaccion($url, $fields, 'POST');
157
            $result = $this->checkResponseCode($obj);
158
159
            return $result;
160
        } catch (InstapagoException $e) {
161
            echo $e->getMessage();
162
        } // end try/catch
163
    }
164
165
    /**
166
     * Anular Pago
167
     * Este método funciona para procesar una anulación de un pago o un bloqueo.
168
     * https://github.com/abr4xas/php-instapago/blob/master/help/DOCUMENTACION.md#anular-pago.
169
     */
170 View Code Duplication
    public function cancelPayment($idPago)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
171
    {
172
        try {
173
            $params = [$idPago];
174
            $this->checkRequiredParams($params);
175
176
            $this->idPago = $idPago;
177
178
            $url = 'payment'; // endpoint
179
180
            $fields = [
181
                'KeyID'             => $this->keyId, //required
182
                'PublicKeyId'       => $this->publicKeyId, //required
183
                'Id'                => $this->idPago, //required
184
            ];
185
            $obj = $this->curlTransaccion($url, $fields, 'DELETE');
186
187
            $result = $this->checkResponseCode($obj);
188
            return $result;
189
190
        } catch (InstapagoException $e) {
191
            echo $e->getMessage();
192
        } // end try/catch
193
    }
194
195
 // cancelPayment
196
197
    /**
198
     * Información del Pago
199
     * Consulta información sobre un pago generado anteriormente.
200
     * Requiere como parámetro el `id` que es el código de referencia de la transacción
201
     * https://github.com/abr4xas/php-instapago/blob/master/help/DOCUMENTACION.md#información-del-pago.
202
     */
203 View Code Duplication
    public function paymentInfo($idPago)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
204
    {
205
        try {
206
            $params = [$idPago];
207
            $this->checkRequiredParams($params);
208
209
            $this->idPago = $idPago;
210
211
            $url = 'payment'; // endpoint
212
213
            $fields = [
214
                'KeyID'             => $this->keyId, //required
215
                'PublicKeyId'       => $this->publicKeyId, //required
216
                'id'                => $this->idPago, //required
217
            ];
218
219
            $obj = $this->curlTransaccion($url, $fields, 'GET');
220
221
            $result = $this->checkResponseCode($obj);
222
223
            return $result;
224
225
        } catch (InstapagoException $e) {
226
            echo $e->getMessage();
227
        } // end try/catch
228
    }
229
230
 // paymentInfo
231
232
    /**
233
     * Realiza Transaccion
234
     * Efectúa y retornar una respuesta a un metodo de pago.
235
     *
236
     *@param $url endpoint a consultar
237
     *@param $fields datos para la consulta
238
     *
239
     *@return $obj array resultados de la transaccion
0 ignored issues
show
Documentation introduced by
The doc-type $obj could not be parsed: Unknown type name "$obj" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
240
     * https://github.com/abr4xas/php-instapago/blob/master/help/DOCUMENTACION.md#PENDIENTE
241
     */
242
    public function curlTransaccion($url, $fields, $method)
243
    {
244
        
245
246
        $client = new Client([
247
             'base_uri' => 'https://api.instapago.com/',
248
             //'debug' => true,
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
249
        ]);
250
251
        if ($method == 'GET') {
252
            $request = $client->request('GET', $url, [
253
                'query' => $fields
254
            ]);
255
        }
256
        if ($method == 'POST' || $method == 'DELETE') {
257
            $request = $client->request($method, $url, [
258
                'form_params' => $fields
259
            ]);
260
        }
261
262
        $body = $request->getBody()->getContents();
0 ignored issues
show
Bug introduced by
The variable $request does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
263
264
        $obj = json_decode($body);
265
266
        return $obj;
267
    }
268
269
    /**
270
     * Verifica Codigo de Estado de transaccion
271
     * Verifica y retornar el resultado de la transaccion.
272
     *
273
     *@param $obj datos de la consulta
274
     *
275
     *@return $result array datos de transaccion
0 ignored issues
show
Documentation introduced by
The doc-type $result could not be parsed: Unknown type name "$result" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
276
     * https://github.com/abr4xas/php-instapago/blob/master/help/DOCUMENTACION.md#PENDIENTE
277
     */
278
    public function checkResponseCode($obj)
279
    {
280
        $code = $obj->code;
281
282
        if ($code == 400) {
283
            throw new InstapagoException('Error al validar los datos enviados.');
284
        }
285
        if ($code == 401) {
286
            throw new InstapagoException('Error de autenticación, ha ocurrido un error con las llaves utilizadas.');
287
        }
288
        if ($code == 403) {
289
            throw new InstapagoException('Pago Rechazado por el banco.');
290
        }
291
        if ($code == 500) {
292
            throw new InstapagoException('Ha Ocurrido un error interno dentro del servidor.');
293
        }
294
        if ($code == 503) {
295
            throw new InstapagoException('Ha Ocurrido un error al procesar los parámetros de entrada. Revise los datos enviados y vuelva a intentarlo.');
296
        }
297
        if ($code == 201) {
298
            return [
299
                'code'         => $code,
300
                'msg_banco'    => $obj->message,
301
                'voucher'      => html_entity_decode($obj->voucher),
302
                'id_pago'      => $obj->id,
303
                'reference'    => $obj->reference,
304
            ];
305
        }
306
    }
307
308
    /**
309
     * Verifica parametros para realizar operación
310
     * Verifica y retorna exception si algun parametro esta vacio.
311
     *
312
     *@param $params Array con parametros a verificar
313
     *
314
     *@return new InstapagoException
315
     * https://github.com/abr4xas/php-instapago/blob/master/help/DOCUMENTACION.md#PENDIENTE
316
     */
317
    private function checkRequiredParams(array $params)
318
    {
319
        foreach ($params as $param) {
320
            if (empty($param)) {
321
                throw new InstapagoException('Parámetros faltantes para procesar el pago. Verifique la documentación.');
322
            }
323
        }
324
    }
325
} // end class
326