Completed
Pull Request — master (#19)
by
unknown
01:47
created

Api::payment()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 23
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 23
rs 9.0856
cc 1
eloc 17
nc 1
nop 2
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('2', $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('1', $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 
0 ignored issues
show
Bug introduced by
There is no parameter named $paymentType. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
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
  private function payment($type, $fields) {
94
95
    (new Validator())->payment()->validate($fields);
96
97
    $fields = [
98
      'KeyID'          => $this->keyId, 
99
      'PublicKeyId'    => $this->publicKeyId, 
100
      'amount'         => $fields['amount'], 
101
      'description'    => $fields['description'], 
102
      'cardHolder'     => $fields['card_holder'], 
103
      'cardHolderId'   => $fields['card_holder_id'], 
104
      'cardNumber'     => $fields['card_number'], 
105
      'cvc'            => $fields['cvc'], 
106
      'expirationDate' => $fields['expiration'], 
107
      'statusId'       => $type, 
108
      'IP'             => $fields['ip'], 
109
    ];
110
111
    $obj = $this->curlTransaccion('payment', $fields, 'POST');
112
    $result = $this->checkResponseCode($obj);
113
114
    return $result;
115
  }
116
117
  /**
118
   * Completar Pago
119
   * Este método funciona para procesar un bloqueo o pre-autorización
120
   * para así procesarla y hacer el cobro respectivo.
121
   *
122
   * @param \ArrayObject<string, string> $fields Los campos necesarios 
123
   * para procesar el pago.
124
   * @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...
125
   * @throws Exceptions\InstapagoException
126
   */
127
  public function continuePayment($fields){
128
    (new Validator())->release()->validate($fields);
129
    $fields = [
130
      'KeyID'        => $this->keyId, //required
131
      'PublicKeyId'  => $this->publicKeyId, //required
132
      'id'           => $fields['id'], //required
133
      'amount'       => $fields['amount'], //required
134
    ];
135
136
    $obj = $this->curlTransaccion('complete', $fields, 'POST');
137
    $result = $this->checkResponseCode($obj);
138
    return $result;
139
  }
140
141
  /**
142
   * Información/Consulta de Pago
143
   * Este método funciona para procesar un bloqueo o pre-autorización
144
   * para así procesarla y hacer el cobro respectivo.
145
   *
146
   * @param string $id_pago ID del pago a consultar 
147
   * @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...
148
   * @throws Exceptions\InstapagoException
149
   */
150 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...
151
    (new Validator())->query()->validate([
152
      'id' => $id_pago
153
    ]);
154
155
    $fields = [
156
      'KeyID'        => $this->keyId, //required
157
      'PublicKeyId'  => $this->publicKeyId, //required
158
      'id'           => $id_pago, //required
159
    ];
160
161
    $obj = $this->curlTransaccion('payment', $fields, 'GET');
162
    $result = $this->checkResponseCode($obj);
163
    return $result;
164
  }
165
166
  /**
167
   * Cancelar Pago
168
   * Este método funciona para cancelar un pago previamente procesado.
169
   *
170
   * @param string $id_pago ID del pago a cancelar
171
   * @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...
172
   * @throws Exceptions\InstapagoException
173
   */
174 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...
175
    (new Validator())->query()->validate([
176
      'id' => $id_pago
177
    ]);
178
179
    $fields = [
180
      'KeyID'        => $this->keyId, //required
181
      'PublicKeyId'  => $this->publicKeyId, //required
182
      'id'           => $id_pago, //required
183
    ];
184
185
    $obj = $this->curlTransaccion('payment', $fields, 'DELETE');
186
    $result = $this->checkResponseCode($obj);
187
    return $result;
188
  }
189
190
  /**
191
   * Realiza Transaccion
192
   * Efectúa y retornar una respuesta a un metodo de pago.
193
   *
194
   * @param $url endpoint a consultar
195
   * @param $fields datos para la consulta
196
   * @param $method verbo http de la consulta
197
   *
198
   * @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...
199
   */
200
  public function curlTransaccion($url, $fields, $method)
201
  {
202
    $client = new Client([
203
       'base_uri' => 'https://api.instapago.com/',
204
    ]);
205
206
    $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...
207
    
208
    if ($method == 'GET') {
209
      $args = [
210
        'query' => $fields
211
      ];
212
    }else if ($method == 'POST' || $method == 'DELETE') {
213
      $args = [
214
          'form_params' => $fields
215
      ];
216
    }else{
217
      throw new Exception("Not implemented yet", 1);
218
    }
219
    
220
    try {
221
      $request = $client->request($method, $url, $args);
222
      $body = $request->getBody()->getContents();
223
      $obj = json_decode($body);
224
      return $obj;
225
    } catch (\GuzzleHttp\Exception\ConnectException $e) {
226
      throw new Exceptions\TimeoutException("Cannot connect to api.instapago.com");
227
    }
228
  }
229
230
  /**
231
   * Verifica y retornar el resultado de la transaccion.
232
   *
233
   * @param $obj datos de la consulta
234
   *
235
   * @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...
236
   */
237
  public function checkResponseCode($obj)
238
  {
239
    $code = $obj->code;
240
241
    if ($code == 400) {
242
      throw new Exceptions\InvalidInputException(
243
        'Error al validar los datos enviados.'
244
      );
245
    }else if ($code == 401) {
246
      throw new Exceptions\AuthException(
247
        'Error de autenticación, ha ocurrido un error'
248
        . ' con las llaves utilizadas.');
249
    }else if ($code == 403) {
250
      throw new Exceptions\BankRejectException(
251
        'Pago Rechazado por el banco.'
252
      );
253
    }else if ($code == 500) {
254
      throw new Exceptions\InstapagoException(
255
        'Ha Ocurrido un error interno dentro del servidor.'
256
      );
257
    }else if ($code == 503) {
258
      throw new Exceptions\InstapagoException(
259
        'Ha Ocurrido un error al procesar los parámetros de entrada.'
260
        . ' Revise los datos enviados y vuelva a intentarlo.'
261
      );
262
    }else if ($code == 201) {
263
      return [
264
        'code'         => $code,
265
        'msg_banco'    => $obj->message,
266
        'voucher'      => html_entity_decode($obj->voucher),
267
        'id_pago'      => $obj->id,
268
        'reference'    => $obj->reference,
269
      ];
270
    }else {
271
      throw new \Exception('Not implemented yet');
272
    }
273
  }
274
275
}
276