Completed
Pull Request — master (#15)
by angel
01:58
created

InstapagoPayment   A

Complexity

Total Complexity 25

Size/Duplication

Total Lines 256
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 4
Bugs 0 Features 0
Metric Value
wmc 25
c 4
b 0
f 0
lcom 1
cbo 1
dl 0
loc 256
rs 10

8 Methods

Rating   Name   Duplication   Size   Complexity  
B __construct() 0 21 6
B payment() 0 40 2
B continuePayment() 0 26 2
A cancelPayment() 0 8 2
A paymentInfo() 0 23 2
A curlTransaccion() 0 13 1
C checkResponseCode() 0 24 7
A checkRequiredParams() 0 8 3
1
<?php
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
namespace Instapago\InstapagoGateway;
30
31
use Instapago\InstapagoGateway\Exceptions\InstapagoException;
32
33
/**
34
 * Clase para la pasarela de pagos Instapago.
35
 */
36
class InstapagoPayment
37
{
38
    protected $keyId;
39
    protected $publicKeyId;
40
    public $cardHolder;
41
    public $cardHolderId;
42
    public $cardNumber;
43
    public $cvc;
44
    public $expirationDate;
45
    public $amount;
46
    public $description;
47
    public $statusId;
48
    public $ipAddres;
49
    public $idPago;
50
    public $root = 'https://api.instapago.com/';
51
52
    /**
53
     * Crear un nuevo objeto de Instapago.
54
     *
55
     * @param string $keyId       llave privada
56
     * @param string $publicKeyId llave publica
57
     *                            Requeridas.
58
     */
59
    public function __construct($keyId, $publicKeyId)
60
    {
61
        try {
62
            if (empty($keyId) && empty($publicKeyId)) {
63
                throw new InstapagoException('Los parámetros "keyId" y "publicKeyId" son requeridos para procesar la petición.');
64
            }
65
66
            if (empty($keyId)) {
67
                throw new InstapagoException('El parámetro "keyId" es requerido para procesar la petición. ');
68
            }
69
70
            if (empty($publicKeyId)) {
71
                throw new InstapagoException('El parámetro "publicKeyId" es requerido para procesar la petición.');
72
            }
73
74
            $this->publicKeyId = $publicKeyId;
75
            $this->keyId = $keyId;
76
        } catch (InstapagoException $e) {
77
            echo $e->getMessage();
78
        } // end try/catch
79
    }
80
81
 // end construct
82
83
    /**
84
     * Crear un pago
85
     * Efectúa un pago con tarjeta de crédito, una vez procesado retornar una respuesta.
86
     * https://github.com/abr4xas/php-instapago/blob/master/help/DOCUMENTACION.md#crear-un-pago.
87
     */
88
    public function payment($amount, $description, $cardHolder, $cardHolderId, $cardNumber, $cvc, $expirationDate, $statusId, $ipAddres)
89
    {
90
        try {
91
            $params = [$amount, $description, $cardHolder, $cardHolderId, $cardNumber, $cvc, $expirationDate, $statusId, $ipAddres];
92
            $this->checkRequiredParams($params);
93
94
            $this->amount = $amount;
95
            $this->description = $description;
96
            $this->cardHolder = $cardHolder;
97
            $this->cardHolderId = $cardHolderId;
98
            $this->cardNumber = $cardNumber;
99
            $this->cvc = $cvc;
100
            $this->expirationDate = $expirationDate;
101
            $this->statusId = $statusId;
102
            $this->ipAddres = $ipAddres;
103
104
            $url = $this->root.'payment'; // endpoint
105
106
            $fields = [
107
                'KeyID'             => $this->keyId, //required
108
                'PublicKeyId'       => $this->publicKeyId, //required
109
                'amount'            => $this->amount, //required
110
                'description'       => $this->description, //required
111
                'cardHolder'        => $this->cardHolder, //required
112
                'cardHolderId'      => $this->cardHolderId, //required
113
                'cardNumber'        => $this->cardNumber, //required
114
                'cvc'               => $this->cvc, //required
115
                'expirationDate'    => $this->expirationDate, //required
116
                'statusId'          => $this->statusId, //required
117
                'IP'                => $this->ipAddres, //required
118
            ];
119
120
            $obj = $this->curlTransaccion($url, $fields);
121
            $result = $this->checkResponseCode($obj);
122
123
            return $result;
124
        } catch (InstapagoException $e) {
125
            echo $e->getMessage();
126
        } // end try/catch
127
    }
128
129
 // end payment
130
131
    /**
132
     * Completar Pago
133
     * Este método funciona para procesar un bloqueo o pre-autorización
134
     * para así procesarla y hacer el cobro respectivo.
135
     * Para usar este método es necesario configurar en `payment()` el parametro statusId a 1
136
     * https://github.com/abr4xas/php-instapago/blob/master/help/DOCUMENTACION.md#completar-pago.
137
     */
138
139
    public function continuePayment($idPago, $amount)
140
    {
141
        try {
142
            $params = [$idPago, $amount];
143
            $this->checkRequiredParams($params);
144
145
            $this->idPago = $idPago;
146
            $this->amount = $amount;
147
148
            $url = $this->root.'complete'; // endpoint
149
150
            $fields = [
151
                'KeyID'             => $this->keyId, //required
152
                'PublicKeyId'       => $this->publicKeyId, //required
153
                'id'                => $this->idPago, //required
154
                'amount'            => $this->amount, //required
155
            ];
156
157
            $obj = $this->curlTransaccion($url, $fields);
158
            $result = $this->checkResponseCode($obj);
159
160
            return $result;
161
        } catch (InstapagoException $e) {
162
            echo $e->getMessage();
163
        } // end try/catch
164
    }
165
166
 // continuePayment
167
168
    /**
169
     * Anular Pago
170
     * Este método funciona para procesar una anulación de un pago o un bloqueo.
171
     * https://github.com/abr4xas/php-instapago/blob/master/help/DOCUMENTACION.md#anular-pago.
172
     */
173
    public function cancelPayment($idPago)
0 ignored issues
show
Unused Code introduced by
The parameter $idPago is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
174
    {
175
        try {
0 ignored issues
show
Unused Code introduced by
This try statement is empty and can be removed.

This check looks for try blocks that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

If there is nothing in the try then the catch block can never be executed either. Thus, these try statements can be removed completely.

Loading history...
176
            // TODO
177
        } catch (InstapagoException $e) {
0 ignored issues
show
Unused Code introduced by
catch (\Instapago\Instap...cho $e->getMessage(); } does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
178
            echo $e->getMessage();
179
        } // end try/catch
180
    }
181
182
 // cancelPayment
183
184
    /**
185
     * Información del Pago
186
     * Consulta información sobre un pago generado anteriormente.
187
     * Requiere como parámetro el `id` que es el código de referencia de la transacción
188
     * https://github.com/abr4xas/php-instapago/blob/master/help/DOCUMENTACION.md#información-del-pago.
189
     */
190
    public function paymentInfo($idPago)
191
    {
192
        try {
193
            $params = [$idPago];
194
            $this->checkRequiredParams($params);
195
196
            $this->idPago = $idPago;
197
198
            $url = $this->root.'payment'; // endpoint
199
200
            $myCurl = curl_init();
201
            curl_setopt($myCurl, CURLOPT_URL, $url.'?'.'KeyID='.$this->keyId.'&PublicKeyId='.$this->publicKeyId.'&id='.$this->idPago);
202
            curl_setopt($myCurl, CURLOPT_RETURNTRANSFER, 1);
203
            $server_output = curl_exec($myCurl);
204
            curl_close($myCurl);
205
            $obj = json_decode($server_output);
206
            $result = $this->checkResponseCode($obj);
207
208
            return $result;
209
        } catch (InstapagoException $e) {
210
            echo $e->getMessage();
211
        } // end try/catch
212
    }
213
214
 // paymentInfo
215
216
    /**
217
     * Realiza Transaccion
218
     * Efectúa y retornar una respuesta a un metodo de pago.
219
     *
220
     *@param $url endpoint a consultar
221
     *@param $fields datos para la consulta
222
     *
223
     *@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...
224
     * https://github.com/abr4xas/php-instapago/blob/master/help/DOCUMENTACION.md#PENDIENTE
225
     */
226
    public function curlTransaccion($url, $fields)
227
    {
228
        $myCurl = curl_init();
229
        curl_setopt($myCurl, CURLOPT_URL, $url);
230
        curl_setopt($myCurl, CURLOPT_POST, 1);
231
        curl_setopt($myCurl, CURLOPT_POSTFIELDS, http_build_query($fields));
232
        curl_setopt($myCurl, CURLOPT_RETURNTRANSFER, true);
233
        $server_output = curl_exec($myCurl);
234
        curl_close($myCurl);
235
        $obj = json_decode($server_output);
236
237
        return $obj;
238
    }
239
240
    /**
241
     * Verifica Codigo de Estado de transaccion
242
     * Verifica y retornar el resultado de la transaccion.
243
     *
244
     *@param $obj datos de la consulta
245
     *
246
     *@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...
247
     * https://github.com/abr4xas/php-instapago/blob/master/help/DOCUMENTACION.md#PENDIENTE
248
     */
249
    public function checkResponseCode($obj)
250
    {
251
        $code = $obj->code;
252
253
        if ($code == 400) {
254
            throw new InstapagoException('Error al validar los datos enviados.');
255
        } elseif ($code == 401) {
256
            throw new InstapagoException('Error de autenticación, ha ocurrido un error con las llaves utilizadas.');
257
        } elseif ($code == 403) {
258
            throw new InstapagoException('Pago Rechazado por el banco.');
259
        } elseif ($code == 500) {
260
            throw new InstapagoException('Ha Ocurrido un error interno dentro del servidor.');
261
        } elseif ($code == 503) {
262
            throw new InstapagoException('Ha Ocurrido un error al procesar los parámetros de entrada. Revise los datos enviados y vuelva a intentarlo.');
263
        } elseif ($code == 201) {
264
            return [
265
            'code'         => $code,
266
            'msg_banco'    => $obj->message,
267
            'voucher'      => html_entity_decode($obj->voucher),
268
            'id_pago'      => $obj->id,
269
            'reference'    => $obj->reference,
270
        ];
271
        }
272
    }
273
274
    /**
275
     * Verifica parametros para realizar operación
276
     * Verifica y retorna exception si algun parametro esta vacio.
277
     *
278
     *@param $params Array con parametros a verificar
279
     *
280
     *@return new InstapagoException
281
     * https://github.com/abr4xas/php-instapago/blob/master/help/DOCUMENTACION.md#PENDIENTE
282
     */
283
    private function checkRequiredParams(array $params)
284
    {
285
        foreach ($params as $param) {
286
            if (empty($param)) {
287
                throw new InstapagoException('Parámetros faltantes para procesar el pago. Verifique la documentación.');
288
            }
289
        }
290
    }
291
} // end class
292