Completed
Push — master ( c1ae1c...dc77cb )
by angel
14s
created

InstapagoPayment::paymentCancelOrInfo()   B

Complexity

Conditions 2
Paths 4

Size

Total Lines 26
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 26
rs 8.8571
cc 2
eloc 15
nc 4
nop 2
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
     * Información o Cancelación del pago
167
     * Consulta información sobre un pago generado anteriormente o puede cancelarlo.
168
     * Requiere como parámetro el `id` que es el código de referencia de la transacción
169
     * @param `$idPago` que es el código de referencia de la transacción
170
     * @param `$method` que puede ser GET o DELETE según lo que desea hacer
171
     *
172
     * @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...
173
     * https://github.com/abr4xas/php-instapago/blob/master/help/DOCUMENTACION.md#PENDIENTE
174
     */
175
    public function paymentCancelOrInfo($idPago, $method)
176
    {
177
        try {
178
            $params = [$idPago];
179
            $this->checkRequiredParams($params);
180
181
            $this->idPago = $idPago;
182
183
            $url = 'payment'; // endpoint
184
185
            $fields = [
186
                'KeyID'             => $this->keyId, //required
187
                'PublicKeyId'       => $this->publicKeyId, //required
188
                'id'                => $this->idPago, //required
189
            ];
190
191
            $obj = $this->curlTransaccion($url, $fields, $method);
192
193
            $result = $this->checkResponseCode($obj);
194
195
            return $result;
196
197
        } catch (InstapagoException $e) {
198
            echo $e->getMessage();
199
        } // end try/catch
200
    }
201
202
 // paymentInfo
203
204
    /**
205
     * Realiza Transaccion
206
     * Efectúa y retornar una respuesta a un metodo de pago.
207
     *
208
     *@param $url endpoint a consultar
209
     *@param $fields datos para la consulta
210
     *
211
     *@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...
212
     * https://github.com/abr4xas/php-instapago/blob/master/help/DOCUMENTACION.md#PENDIENTE
213
     */
214
    public function curlTransaccion($url, $fields, $method)
215
    {
216
        
217
218
        $client = new Client([
219
             'base_uri' => 'https://api.instapago.com/',
220
             //'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...
221
        ]);
222
223
        if ($method == 'GET') {
224
            $request = $client->request('GET', $url, [
225
                'query' => $fields
226
            ]);
227
        }
228
        if ($method == 'POST' || $method == 'DELETE') {
229
            $request = $client->request($method, $url, [
230
                'form_params' => $fields
231
            ]);
232
        }
233
234
        $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...
235
236
        $obj = json_decode($body);
237
238
        return $obj;
239
    }
240
241
    /**
242
     * Verifica Codigo de Estado de transaccion
243
     * Verifica y retornar el resultado de la transaccion.
244
     *
245
     *@param $obj datos de la consulta
246
     *
247
     *@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...
248
     * https://github.com/abr4xas/php-instapago/blob/master/help/DOCUMENTACION.md#PENDIENTE
249
     */
250
    public function checkResponseCode($obj)
251
    {
252
        $code = $obj->code;
253
254
        if ($code == 400) {
255
            throw new InstapagoException('Error al validar los datos enviados.');
256
        }
257
        if ($code == 401) {
258
            throw new InstapagoException('Error de autenticación, ha ocurrido un error con las llaves utilizadas.');
259
        }
260
        if ($code == 403) {
261
            throw new InstapagoException('Pago Rechazado por el banco.');
262
        }
263
        if ($code == 500) {
264
            throw new InstapagoException('Ha Ocurrido un error interno dentro del servidor.');
265
        }
266
        if ($code == 503) {
267
            throw new InstapagoException('Ha Ocurrido un error al procesar los parámetros de entrada. Revise los datos enviados y vuelva a intentarlo.');
268
        }
269
        if ($code == 201) {
270
            return [
271
                'code'         => $code,
272
                'msg_banco'    => $obj->message,
273
                'voucher'      => html_entity_decode($obj->voucher),
274
                'id_pago'      => $obj->id,
275
                'reference'    => $obj->reference,
276
            ];
277
        }
278
    }
279
280
    /**
281
     * Verifica parametros para realizar operación
282
     * Verifica y retorna exception si algun parametro esta vacio.
283
     *
284
     *@param $params Array con parametros a verificar
285
     *
286
     *@return new InstapagoException
287
     * https://github.com/abr4xas/php-instapago/blob/master/help/DOCUMENTACION.md#PENDIENTE
288
     */
289
    private function checkRequiredParams(array $params)
290
    {
291
        foreach ($params as $param) {
292
            if (empty($param)) {
293
                throw new InstapagoException('Parámetros faltantes para procesar el pago. Verifique la documentación.');
294
            }
295
        }
296
    }
297
} // end class
298