Completed
Push — master ( 091a38...424b72 )
by angel
8s
created

InstapagoPayment::checkRequiredParams()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 9
rs 9.6666
cc 3
eloc 4
nc 3
nop 1
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
            $params = array($amount,$description,$cardHolder,$cardHolderId,$cardNumber,$cvc,$expirationDate,$statusId,$ipAddres);
99
            $this->checkRequiredParams($params);
100
101
            $this->amount           = $amount;
102
            $this->description      = $description;
103
            $this->cardHolder       = $cardHolder;
104
            $this->cardHolderId     = $cardHolderId;
105
            $this->cardNumber       = $cardNumber;
106
            $this->cvc 			    = $cvc;
107
            $this->expirationDate   = $expirationDate;
108
            $this->statusId		    = $statusId;
109
            $this->ipAddres        = $ipAddres;
110
111
            $url = $this->root . 'payment'; // endpoint
112
113
            $fields = [
114
                "KeyID"             => $this->keyId, //required
115
                "PublicKeyId"       => $this->publicKeyId, //required
116
                "amount"            => $this->amount, //required
117
                "description"       => $this->description, //required
118
                "cardHolder"        => $this->cardHolder, //required
119
                "cardHolderId"      => $this->cardHolderId, //required
120
                "cardNumber"        => $this->cardNumber, //required
121
                "cvc"               => $this->cvc, //required
122
                "expirationDate"    => $this->expirationDate, //required
123
                "statusId"          => $this->statusId, //required
124
                "IP"                => $this->ipAddres //required
125
            ];
126
127
            $obj = $this->curlTransaccion($url, $fields);
128
            $result = $this->checkResponseCode($obj);
129
130
            return $result;
131
132
        } catch (InstapagoException $e) {
133
134
            echo $e->getMessage();
135
136
        } // end try/catch
137
138
        return;
139
140
    } // end payment
141
142
    /**
143
     * Completar Pago
144
     * Este método funciona para procesar un bloqueo o pre-autorización
145
     * para así procesarla y hacer el cobro respectivo.
146
     * Para usar este método es necesario configurar en `payment()` el parametro statusId a 1
147
     * https://github.com/abr4xas/php-instapago/blob/master/help/DOCUMENTACION.md#completar-pago
148
     */
149
150
    public function continuePayment($amount,$idPago)
151
    {
152
        try {
153
            $params = array($amount,$idPago);
154
            $this->checkRequiredParams($params);
155
156
            $this->amount = $amount;
157
            $this->idPago = $idPago;
158
159
            $url = $this->root . 'complete'; // endpoint
160
161
            $fields = [
162
                "KeyID"             => $this->keyId, //required
163
                "PublicKeyId"       => $this->publicKeyId, //required
164
                "amount"            => $this->amount, //required
165
                "id"                => $this->idPago, //required
166
            ];
167
168
            $obj = $this->curlTransaccion($url, $fields);
169
            $result = $this->checkResponseCode($obj);
170
171
            return $result;
172
173
        } catch (InstapagoException $e) {
174
175
            echo $e->getMessage();
176
177
        } // end try/catch
178
179
        return;
180
    } // continuePayment
181
182
    /**
183
     * Anular Pago
184
     * Este método funciona para procesar una anulación de un pago o un bloqueo.
185
     * https://github.com/abr4xas/php-instapago/blob/master/help/DOCUMENTACION.md#anular-pago
186
     */
187
188
    public function cancelPayment($idPago)
189
    {
190
        try {
191
192
            $params = array($idPago);
193
            $this->checkRequiredParams($params);
194
195
            $this->idPago = $idPago;
196
197
            $url = $this->root . 'payment'; // endpoint
198
199
            $fields = [
200
                "KeyID"             => $this->keyId, //required
201
                "PublicKeyId"       => $this->publicKeyId, //required
202
                "id"                => $this->idPago, //required
203
            ];
204
205
            $obj = $this->curlTransaccion($url, $fields);
206
            $result = $this->checkResponseCode($obj);
207
208
            return $result;
209
210
        } catch (InstapagoException $e) {
211
212
            echo $e->getMessage();
213
214
        } // end try/catch
215
216
        return;
217
    } // cancelPayment
218
219
    /**
220
     * Información del Pago
221
     * Consulta información sobre un pago generado anteriormente.
222
     * Requiere como parámetro el `id` que es el código de referencia de la transacción
223
     * https://github.com/abr4xas/php-instapago/blob/master/help/DOCUMENTACION.md#información-del-pago
224
     */
225
226
    public function paymentInfo($idPago)
227
    {
228
        try {
229
            $params = array($idPago);
230
            $this->checkRequiredParams($params);
231
232
            $this->idPago = $idPago;
233
234
            $url = $this->root . 'payment'; // endpoint
235
236
            $myCurl = curl_init();
237
            curl_setopt($myCurl, CURLOPT_URL, $url.'?'.'KeyID='. $this->keyId .'&PublicKeyId='. $this->publicKeyId .'&id=' . $this->idPago);
238
            curl_setopt($myCurl, CURLOPT_RETURNTRANSFER, 1);
239
            $server_output = curl_exec($myCurl);
240
            curl_close ($myCurl);
241
            $obj = json_decode($server_output);
242
            $result = $this->checkResponseCode($obj);
243
244
            return $result;
245
246
        } catch (InstapagoException $e) {
247
248
            echo $e->getMessage();
249
250
        } // end try/catch
251
252
        return;
253
    } // paymentInfo
254
255
    /**
256
     * Realiza Transaccion
257
     * Efectúa y retornar una respuesta a un metodo de pago.
258
     *@param $url endpoint a consultar
259
     *@param $fields datos para la consulta
260
     *@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...
261
     * https://github.com/abr4xas/php-instapago/blob/master/help/DOCUMENTACION.md#PENDIENTE
262
     */
263
    public function curlTransaccion($url, $fields)
264
    {
265
      $myCurl = curl_init();
266
      curl_setopt($myCurl, CURLOPT_URL,$url );
267
      curl_setopt($myCurl, CURLOPT_POST, 1);
268
      curl_setopt($myCurl, CURLOPT_POSTFIELDS,http_build_query($fields));
269
      curl_setopt($myCurl, CURLOPT_RETURNTRANSFER, true);
270
      $server_output = curl_exec ($myCurl);
271
      curl_close ($myCurl);
272
      $obj = json_decode($server_output);
273
      return $obj;
274
    }
275
276
    /**
277
     * Verifica Codigo de Estado de transaccion
278
     * Verifica y retornar el resultado de la transaccion.
279
     *@param $obj datos de la consulta
280
     *@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...
281
     * https://github.com/abr4xas/php-instapago/blob/master/help/DOCUMENTACION.md#PENDIENTE
282
     */
283
    public function checkResponseCode($obj)
284
    {
285
      $code = $obj->code;
286
287
      if ($code == 400) {
288
          throw new InstapagoException('Error al validar los datos enviados.');
289
      }elseif ($code == 401) {
290
          throw new InstapagoException('Error de autenticación, ha ocurrido un error con las llaves utilizadas.');
291
      }elseif ($code == 403) {
292
          throw new InstapagoException('Pago Rechazado por el banco.');
293
      }elseif ($code == 500) {
294
          throw new InstapagoException('Ha Ocurrido un error interno dentro del servidor.');
295
      }elseif ($code == 503) {
296
          throw new InstapagoException('Ha Ocurrido un error al procesar los parámetros de entrada. Revise los datos enviados y vuelva a intentarlo.');
297
      }elseif ($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
     *@param $params Array con parametros a verificar
312
     *@return new InstapagoException
313
     * https://github.com/abr4xas/php-instapago/blob/master/help/DOCUMENTACION.md#PENDIENTE
314
     */
315
    private function checkRequiredParams(Array $params)
316
    {
317
      foreach ($params as $param) {
318
        if(empty($param))
319
        {
320
          throw new InstapagoException('Parámetros faltantes para procesar el pago. Verifique la documentación.');
321
        }
322
      }
323
    }
324
325
} // end class
326