Completed
Push — master ( 5c776f...9702f2 )
by angel
02:43 queued 30s
created

InstapagoPayment   A

Complexity

Total Complexity 35

Size/Duplication

Total Lines 277
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 4
Bugs 0 Features 0
Metric Value
wmc 35
c 4
b 0
f 0
lcom 1
cbo 1
dl 0
loc 277
rs 9

7 Methods

Rating   Name   Duplication   Size   Complexity  
B __construct() 0 27 6
C payment() 0 48 11
B continuePayment() 0 33 4
B cancelPayment() 0 31 3
B paymentInfo() 0 30 3
A curlTransaccion() 0 12 1
C checkResponseCode() 0 24 7
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
 * @package php-instapago
27
 * @license MIT License
28
 * @copyright 2016 Angel Cruz
29
 */
30
31
namespace Instapago\InstapagoGateway;
32
33
use Instapago\InstapagoGateway\Exceptions\InstapagoException;
34
35
/**
36
 * Clase para la pasarela de pagos Instapago
37
 */
38
39
class InstapagoPayment
40
{
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
    public      $root = 'https://api.instapago.com/';
55
56
    /**
57
     * Crear un nuevo objeto de Instapago
58
     * @param string $keyId llave privada
59
     * @param string $publicKeyId llave publica
60
     * Requeridas.
61
     */
62
    public function __construct ($keyId,$publicKeyId)
63
    {
64
65
        try {
66
67
            if (empty($keyId) && empty($publicKeyId)) {
68
                throw new InstapagoException('Los parámetros "keyId" y "publicKeyId" son requeridos para procesar la petición.');
69
            }
70
71
            if (empty($keyId)) {
72
                throw new InstapagoException('El parámetro "keyId" es requerido para procesar la petición. ');
73
            }
74
            
75
            if (empty($publicKeyId)) {
76
                throw new InstapagoException('El parámetro "publicKeyId" es requerido para procesar la petición.');
77
            }
78
            
79
            $this->publicKeyId = $publicKeyId;
80
            $this->keyId = $keyId;
81
82
        } catch (InstapagoException $e) {
83
84
            echo $e->getMessage();
85
86
        } // end try/catch
87
88
    } // end construct
89
90
    /**
91
     * Crear un pago
92
     * Efectúa un pago con tarjeta de crédito, una vez procesado retornar una respuesta.
93
     * https://github.com/abr4xas/php-instapago/blob/master/help/DOCUMENTACION.md#crear-un-pago
94
     */
95
    public function payment($amount,$description,$cardHolder,$cardHolderId,$cardNumber,$cvc,$expirationDate,$statusId,$ipAddres)
96
    {
97
        try {
98
99
            if (empty($amount) || empty($description) || empty($cardHolder) || empty($cardHolderId) || empty($cardNumber) || empty($cvc) || empty($expirationDate) || empty($statusId) || empty($ipAddres)) {
100
                throw new InstapagoException('Parámetros faltantes para procesar el pago. Verifique la documentación.');
101
            }
102
103
            $this->amount           = $amount;
104
            $this->description      = $description;
105
            $this->cardHolder       = $cardHolder;
106
            $this->cardHolderId     = $cardHolderId;
107
            $this->cardNumber       = $cardNumber;
108
            $this->cvc 			    = $cvc;
109
            $this->expirationDate   = $expirationDate;
110
            $this->statusId		    = $statusId;
111
            $this->ipAddres        = $ipAddres;
112
113
            $url = $this->root . 'payment'; // endpoint
114
115
            $fields = [
116
                "KeyID"             => $this->keyId, //required
117
                "PublicKeyId"       => $this->publicKeyId, //required
118
                "amount"            => $this->amount, //required
119
                "description"       => $this->description, //required
120
                "cardHolder"        => $this->cardHolder, //required
121
                "cardHolderId"      => $this->cardHolderId, //required
122
                "cardNumber"        => $this->cardNumber, //required
123
                "cvc"               => $this->cvc, //required
124
                "expirationDate"    => $this->expirationDate, //required
125
                "statusId"          => $this->statusId, //required
126
                "IP"                => $this->ipAddres //required
127
            ];
128
129
            $obj = $this->curlTransaccion($url, $fields);
130
            $result = $this->checkResponseCode($obj);
131
132
            return $result;
133
134
        } catch (InstapagoException $e) {
135
136
            echo $e->getMessage();
137
138
        } // end try/catch
139
140
        return;
141
142
    } // end payment
143
144
    /**
145
     * Completar Pago
146
     * Este método funciona para procesar un bloqueo o pre-autorización
147
     * para así procesarla y hacer el cobro respectivo.
148
     * Para usar este método es necesario configurar en `payment()` el parametro statusId a 1
149
     * https://github.com/abr4xas/php-instapago/blob/master/help/DOCUMENTACION.md#completar-pago
150
     */
151
152
    public function continuePayment($amount,$idPago)
153
    {
154
        try {
155
156
            if (empty($amount) || empty($idPago)) {
157
                throw new InstapagoException('Parámetros faltantes para procesar el pago. Verifique la documentación.');
158
            }
159
160
            $this->amount = $amount;
161
            $this->idPago = $idPago;
162
163
            $url = $this->root . 'complete'; // endpoint
164
165
            $fields = [
166
                "KeyID"             => $this->keyId, //required
167
                "PublicKeyId"       => $this->publicKeyId, //required
168
                "amount"            => $this->amount, //required
169
                "id"                => $this->idPago, //required
170
            ];
171
172
            $obj = $this->curlTransaccion($url, $fields);
173
            $result = $this->checkResponseCode($obj);
174
175
            return $result;
176
177
        } catch (InstapagoException $e) {
178
179
            echo $e->getMessage();
180
181
        } // end try/catch
182
183
        return;
184
    } // continuePayment
185
186
    /**
187
     * Anular Pago
188
     * Este método funciona para procesar una anulación de un pago o un bloqueo.
189
     * https://github.com/abr4xas/php-instapago/blob/master/help/DOCUMENTACION.md#anular-pago
190
     */
191
192
    public function cancelPayment($idPago)
193
    {
194
        try {
195
196
            if (empty($idPago)) {
197
                throw new InstapagoException('Parámetros faltantes para procesar el pago. Verifique la documentación.');
198
            }
199
200
            $this->idPago = $idPago;
201
202
            $url = $this->root . 'payment'; // endpoint
203
204
            $fields = [
205
                "KeyID"             => $this->keyId, //required
206
                "PublicKeyId"       => $this->publicKeyId, //required
207
                "id"                => $this->idPago, //required
208
            ];
209
210
            $obj = $this->curlTransaccion($url, $fields);
211
            $result = $this->checkResponseCode($obj);
212
213
            return $result;
214
215
        } catch (InstapagoException $e) {
216
217
            echo $e->getMessage();
218
219
        } // end try/catch
220
221
        return;
222
    } // cancelPayment
223
224
    /**
225
     * Información del Pago
226
     * Consulta información sobre un pago generado anteriormente.
227
     * Requiere como parámetro el `id` que es el código de referencia de la transacción
228
     * https://github.com/abr4xas/php-instapago/blob/master/help/DOCUMENTACION.md#información-del-pago
229
     */
230
231
    public function paymentInfo($idPago)
232
    {
233
        try {
234
235
            if (empty($idPago)) {
236
                throw new InstapagoException('Parámetros faltantes para procesar el pago. Verifique la documentación.');
237
            }
238
239
            $this->idPago = $idPago;
240
241
            $url = $this->root . 'payment'; // endpoint
242
243
            $myCurl = curl_init();
244
            curl_setopt($myCurl, CURLOPT_URL, $url.'?'.'KeyID='. $this->keyId .'&PublicKeyId='. $this->publicKeyId .'&id=' . $this->idPago);
245
            curl_setopt($myCurl, CURLOPT_RETURNTRANSFER, 1);
246
            $server_output = curl_exec($myCurl);
247
            curl_close ($myCurl);
248
            $obj = json_decode($server_output);
249
            $result = $this->checkResponseCode($obj);
250
251
            return $result;
252
253
        } catch (InstapagoException $e) {
254
255
            echo $e->getMessage();
256
257
        } // end try/catch
258
259
        return;
260
    } // paymentInfo
261
262
    /**
263
     * Realiza Transaccion
264
     * Efectúa y retornar una respuesta a un metodo de pago.
265
     *@param $url endpoint a consultar
266
     *@param $fields datos para la consulta
267
     *@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...
268
     * https://github.com/abr4xas/php-instapago/blob/master/help/DOCUMENTACION.md#PENDIENTE
269
     */
270
    public function curlTransaccion($url, $fields)
271
    {
272
      $myCurl = curl_init();
273
      curl_setopt($myCurl, CURLOPT_URL,$url );
274
      curl_setopt($myCurl, CURLOPT_POST, 1);
275
      curl_setopt($myCurl, CURLOPT_POSTFIELDS,http_build_query($fields));
276
      curl_setopt($myCurl, CURLOPT_RETURNTRANSFER, true);
277
      $server_output = curl_exec ($myCurl);
278
      curl_close ($myCurl);
279
      $obj = json_decode($server_output);
280
      return $obj;
281
    }
282
283
    /**
284
     * Verifica Codigo de Estado de transaccion
285
     * Verifica y retornar el resultado de la transaccion.
286
     *@param $obj datos de la consulta
287
     *@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...
288
     * https://github.com/abr4xas/php-instapago/blob/master/help/DOCUMENTACION.md#PENDIENTE
289
     */
290
    public function checkResponseCode($obj)
291
    {
292
      $code = $obj->code;
293
294
      if ($code == 400) {
295
          throw new InstapagoException('Error al validar los datos enviados.');
296
      }elseif ($code == 401) {
297
          throw new InstapagoException('Error de autenticación, ha ocurrido un error con las llaves utilizadas.');
298
      }elseif ($code == 403) {
299
          throw new InstapagoException('Pago Rechazado por el banco.');
300
      }elseif ($code == 500) {
301
          throw new InstapagoException('Ha Ocurrido un error interno dentro del servidor.');
302
      }elseif ($code == 503) {
303
          throw new InstapagoException('Ha Ocurrido un error al procesar los parámetros de entrada. Revise los datos enviados y vuelva a intentarlo.');
304
      }elseif ($code == 201) {
305
        return [
306
            'code'      => $code ,
307
            'msg_banco' => $obj->message,
308
            'voucher' 	=> html_entity_decode($obj->voucher),
309
            'id_pago'	  => $obj->id,
310
            'reference' =>$obj->reference
311
        ];
312
      }
313
    }
314
315
} // end class
316