Completed
Pull Request — master (#19)
by
unknown
02:55
created

Api::continuePayment()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 13
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 13
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 10
nc 1
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
 * @license MIT License
27
 * @copyright 2016 Angel Cruz
28
 */
29
30
namespace Instapago;
31
32
use GuzzleHttp\Client as Client;
33
34
/**
35
* Clase para la pasarela de pagos Instapago.
36
*/
37
class Api
38
{
39
  protected $keyId;
40
  protected $publicKeyId;
41
42
  /**
43
   * Crear un nuevo objeto de Instapago.
44
   *
45
   * @param string $keyId       llave privada
46
   * @param string $publicKeyId llave publica
47
   *                            Requeridas.
48
   */
49
  public function __construct($keyId, $publicKeyId) {
50
    if ( empty($keyId) || empty($publicKeyId) ) {
51
      throw new Exceptions\InstapagoException('Los parámetros "keyId" y "publicKeyId" son requeridos para procesar la petición.');
52
    }
53
    $this->publicKeyId = $publicKeyId;
54
    $this->keyId = $keyId;
55
  }
56
57
  /**
58
   * Crear un pago directo.
59
   *
60
   * @param \ArrayObject<string, string> $fields Los campos necesarios 
61
   * para procesar el pago.
62
   * @return \ArrayObject<string, string> Respuesta de Instapago
0 ignored issues
show
Documentation introduced by
The doc-type \ArrayObject<string, could not be parsed: Expected "|" or "end of type", but got "<" at position 12. (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...
63
   * @throws Exceptions\InstapagoException
64
   */
65
  public function directPayment($fields)
66
  {
67
    return $this->payment('direct', $fields);
68
  }
69
70
  /**
71
   * Crear un pago diferido o reservado.
72
   *
73
   * @param \ArrayObject<string, string> $fields Los campos necesarios 
74
   * para procesar el pago.
75
   * @return \ArrayObject<string, string> Respuesta de Instapago
0 ignored issues
show
Documentation introduced by
The doc-type \ArrayObject<string, could not be parsed: Expected "|" or "end of type", but got "<" at position 12. (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...
76
   * @throws Exceptions\InstapagoException
77
   */
78
  public function reservePayment($fields)
79
  {
80
    return $this->payment('reserve', $fields);
81
  }
82
83
  /**
84
   * Crear un pago.
85
   *
86
   * @param string $paymentType tipo de pago ('reserve' o 'direct')
87
   * @param \ArrayObject<string, string> $fields Los campos necesarios 
88
   * para procesar el pago.
89
   * @return \ArrayObject<string, string> Respuesta de Instapago
90
   * @throws Exceptions\InstapagoException
0 ignored issues
show
Documentation introduced by
The doc-type \ArrayObject<string, could not be parsed: Expected "|" or "end of type", but got "<" at position 12. (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...
91
   */
92
93
  public function payment($paymentType, $fields) {
94
    $type = null;
0 ignored issues
show
Unused Code introduced by
$type is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
95
    if ($paymentType == 'direct') {
96
      $type = '2';
97
    }else if ($paymentType == 'reserve') {
98
      $type = '1';
99
    }else{
100
      throw new Exceptions\InstapagoException("Invalid Payment type");
101
    }
102
103
    (new Validator())->payment()->validate($fields);
104
105
    $fields = [
106
      'KeyID'          => $this->keyId, 
107
      'PublicKeyId'    => $this->publicKeyId, 
108
      'amount'         => $fields['amount'], 
109
      'description'    => $fields['description'], 
110
      'cardHolder'     => $fields['card_holder'], 
111
      'cardHolderId'   => $fields['card_holder_id'], 
112
      'cardNumber'     => $fields['card_number'], 
113
      'cvc'            => $fields['cvc'], 
114
      'expirationDate' => $fields['expiration'], 
115
      'statusId'       => $type, 
116
      'IP'             => $fields['ip'], 
117
    ];
118
119
    $obj = $this->curlTransaccion('payment', $fields, 'POST');
120
    $result = $this->checkResponseCode($obj);
121
122
    return $result;
123
  }
124
125
  /**
126
   * Completar Pago
127
   * Este método funciona para procesar un bloqueo o pre-autorización
128
   * para así procesarla y hacer el cobro respectivo.
129
   *
130
   * @param \ArrayObject<string, string> $fields Los campos necesarios 
131
   * para procesar el pago.
132
   * @return \ArrayObject<string, string> Respuesta de Instapago
0 ignored issues
show
Documentation introduced by
The doc-type \ArrayObject<string, could not be parsed: Expected "|" or "end of type", but got "<" at position 12. (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...
133
   * @throws Exceptions\InstapagoException
134
   */
135
  public function continuePayment($fields){
136
    (new Validator())->release()->validate($fields);
137
    $fields = [
138
      'KeyID'        => $this->keyId, //required
139
      'PublicKeyId'  => $this->publicKeyId, //required
140
      'id'           => $fields['id'], //required
141
      'amount'       => $fields['amount'], //required
142
    ];
143
144
    $obj = $this->curlTransaccion('complete', $fields, 'POST');
145
    $result = $this->checkResponseCode($obj);
146
    return $result;
147
  }
148
149
  /**
150
   * Información/Consulta de Pago
151
   * Este método funciona para procesar un bloqueo o pre-autorización
152
   * para así procesarla y hacer el cobro respectivo.
153
   *
154
   * @param string $id_pago ID del pago a consultar 
155
   * @return \ArrayObject<string, string> Respuesta de Instapago
0 ignored issues
show
Documentation introduced by
The doc-type \ArrayObject<string, could not be parsed: Expected "|" or "end of type", but got "<" at position 12. (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...
156
   * @throws Exceptions\InstapagoException
157
   */
158 View Code Duplication
  public function query($id_pago) {
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...
159
    (new Validator())->query()->validate([
160
      'id' => $id_pago
161
    ]);
162
163
    $fields = [
164
      'KeyID'        => $this->keyId, //required
165
      'PublicKeyId'  => $this->publicKeyId, //required
166
      'id'           => $id_pago, //required
167
    ];
168
169
    $obj = $this->curlTransaccion('payment', $fields, 'GET');
170
    $result = $this->checkResponseCode($obj);
171
    return $result;
172
  }
173
174
  /**
175
   * Cancelar Pago
176
   * Este método funciona para cancelar un pago previamente procesado.
177
   *
178
   * @param string $id_pago ID del pago a cancelar
179
   * @return \ArrayObject<string, string> Respuesta de Instapago
0 ignored issues
show
Documentation introduced by
The doc-type \ArrayObject<string, could not be parsed: Expected "|" or "end of type", but got "<" at position 12. (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...
180
   * @throws Exceptions\InstapagoException
181
   */
182 View Code Duplication
  public function cancel($id_pago) {
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...
183
    (new Validator())->query()->validate([
184
      'id' => $id_pago
185
    ]);
186
187
    $fields = [
188
      'KeyID'        => $this->keyId, //required
189
      'PublicKeyId'  => $this->publicKeyId, //required
190
      'id'           => $id_pago, //required
191
    ];
192
193
    $obj = $this->curlTransaccion('payment', $fields, 'DELETE');
194
    $result = $this->checkResponseCode($obj);
195
    return $result;
196
  }
197
198
  /**
199
   * Realiza Transaccion
200
   * Efectúa y retornar una respuesta a un metodo de pago.
201
   *
202
   * @param $url endpoint a consultar
203
   * @param $fields datos para la consulta
204
   * @param $method verbo http de la consulta
205
   *
206
   * @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...
207
   */
208
  public function curlTransaccion($url, $fields, $method)
209
  {
210
    $client = new Client([
211
       'base_uri' => 'https://api.instapago.com/',
212
    ]);
213
214
    $args = [];
0 ignored issues
show
Unused Code introduced by
$args is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
215
    
216
    if ($method == 'GET') {
217
      $args = [
218
        'query' => $fields
219
      ];
220
    }else if ($method == 'POST' || $method == 'DELETE') {
221
      $args = [
222
          'form_params' => $fields
223
      ];
224
    }else{
225
      throw new Exception("Not implemented yet", 1);
226
    }
227
    
228
    try {
229
      $request = $client->request($method, $url, $args);
230
      $body = $request->getBody()->getContents();
231
      $obj = json_decode($body);
232
      return $obj;
233
    } catch (\GuzzleHttp\Exception\ConnectException $e) {
234
      throw new Exceptions\TimeoutException("Cannot connect to api.instapago.com");
235
    }
236
  }
237
238
  /**
239
   * Verifica y retornar el resultado de la transaccion.
240
   *
241
   * @param $obj datos de la consulta
242
   *
243
   * @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...
244
   */
245
  public function checkResponseCode($obj)
246
  {
247
    $code = $obj->code;
248
249
    if ($code == 400) {
250
      throw new Exceptions\InvalidInputException(
251
        'Error al validar los datos enviados.'
252
      );
253
    }else if ($code == 401) {
254
      throw new Exceptions\AuthException(
255
        'Error de autenticación, ha ocurrido un error'
256
        . ' con las llaves utilizadas.');
257
    }else if ($code == 403) {
258
      throw new Exceptions\BankRejectException(
259
        'Pago Rechazado por el banco.'
260
      );
261
    }else if ($code == 500) {
262
      throw new Exceptions\InstapagoException(
263
        'Ha Ocurrido un error interno dentro del servidor.'
264
      );
265
    }else if ($code == 503) {
266
      throw new Exceptions\InstapagoException(
267
        'Ha Ocurrido un error al procesar los parámetros de entrada.'
268
        . ' Revise los datos enviados y vuelva a intentarlo.'
269
      );
270
    }else if ($code == 201) {
271
      return [
272
        'code'         => $code,
273
        'msg_banco'    => $obj->message,
274
        'voucher'      => html_entity_decode($obj->voucher),
275
        'id_pago'      => $obj->id,
276
        'reference'    => $obj->reference,
277
      ];
278
    }else {
279
      throw new \Exception('Not implemented yet');
280
    }
281
  }
282
283
}
284