flashpi 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +7 -0
- data/CHANGELOG.md +25 -0
- data/LICENSE +21 -0
- data/README.en.md +379 -0
- data/README.md +383 -0
- data/lib/flashpi/api_response.rb +33 -0
- data/lib/flashpi/client.rb +112 -0
- data/lib/flashpi/errors.rb +116 -0
- data/lib/flashpi/internal/engine.rb +355 -0
- data/lib/flashpi/internal/json_text.rb +108 -0
- data/lib/flashpi/internal/multipart.rb +141 -0
- data/lib/flashpi/internal/problems.rb +111 -0
- data/lib/flashpi/internal/request.rb +231 -0
- data/lib/flashpi/internal/resource.rb +125 -0
- data/lib/flashpi/internal/secret.rb +41 -0
- data/lib/flashpi/internal/settings.rb +88 -0
- data/lib/flashpi/internal/transport.rb +432 -0
- data/lib/flashpi/internal/validate.rb +122 -0
- data/lib/flashpi/page.rb +82 -0
- data/lib/flashpi/resources/documents.rb +136 -0
- data/lib/flashpi/resources/events.rb +36 -0
- data/lib/flashpi/resources/issuer_onboardings.rb +47 -0
- data/lib/flashpi/resources/issuers.rb +179 -0
- data/lib/flashpi/resources/webhook_endpoints.rb +110 -0
- data/lib/flashpi/version.rb +6 -0
- data/lib/flashpi/webhooks.rb +223 -0
- data/lib/flashpi.rb +42 -0
- data/sig/flashpi/internal.rbs +376 -0
- data/sig/flashpi/resources.rbs +712 -0
- data/sig/flashpi/sdk_types.rbs +114 -0
- data/sig/flashpi/types.rbs +2495 -0
- data/sig/flashpi.rbs +187 -0
- data/sig/manifest.yaml +8 -0
- metadata +80 -0
data/README.md
ADDED
|
@@ -0,0 +1,383 @@
|
|
|
1
|
+
# Flashpi para Ruby
|
|
2
|
+
|
|
3
|
+
SDK oficial de [Flashpi](https://flashpi.com.ec), la API de facturación electrónica del SRI de
|
|
4
|
+
Ecuador, para Ruby.
|
|
5
|
+
|
|
6
|
+
[English](https://github.com/flashpi1/flashpi-ruby/blob/main/README.en.md)
|
|
7
|
+
|
|
8
|
+
- Las 45 operaciones de la API: los seis comprobantes, documentos (XML, RIDE en PDF, correo),
|
|
9
|
+
emisores con establecimientos, puntos de emisión y certificados .p12, webhooks y eventos.
|
|
10
|
+
- Un cliente (`Flashpi::Client`) que puedes compartir entre hilos y que reutiliza sus conexiones.
|
|
11
|
+
- Firmas RBS generadas del documento OpenAPI de la API: Steep y los editores que leen RBS conocen
|
|
12
|
+
cada campo.
|
|
13
|
+
- Reintentos seguros: cada emisión lleva un `Idempotency-Key`, así un reintento nunca emite dos
|
|
14
|
+
veces.
|
|
15
|
+
- Errores tipados (RFC 9457) con su `code`, los errores por campo y el `request_id`.
|
|
16
|
+
- Paginación automática: cada lista es `Enumerable` y pide las páginas a medida que avanzas.
|
|
17
|
+
- Verificación de firmas de webhooks (Standard Webhooks) para Rails, Sinatra o cualquier app Rack.
|
|
18
|
+
- Ruby 3.3 o superior. Sin dependencias: solo la biblioteca estándar (net/http).
|
|
19
|
+
|
|
20
|
+
## Instalación
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
bundle add flashpi
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
O sin Bundler: `gem install flashpi`.
|
|
27
|
+
|
|
28
|
+
## Primeros pasos
|
|
29
|
+
|
|
30
|
+
Crea una clave de API en la [consola](https://flashpi.com.ec/app/) y guárdala en la variable de
|
|
31
|
+
entorno `FLASHPI_API_KEY`. Una clave `fp_test_` emite en el ambiente de pruebas del SRI; una
|
|
32
|
+
`fp_live_` emite comprobantes reales en producción.
|
|
33
|
+
|
|
34
|
+
```ruby
|
|
35
|
+
require "flashpi"
|
|
36
|
+
|
|
37
|
+
# Lee FLASHPI_API_KEY; también puedes pasarla: Flashpi::Client.new(api_key: "fp_test_...")
|
|
38
|
+
flashpi = Flashpi::Client.new
|
|
39
|
+
|
|
40
|
+
invoice = flashpi.invoices.create(
|
|
41
|
+
{
|
|
42
|
+
issuerId: "<id del emisor demo o del tuyo>",
|
|
43
|
+
establishment: "001",
|
|
44
|
+
emissionPoint: "001",
|
|
45
|
+
customer: {
|
|
46
|
+
idType: "ruc",
|
|
47
|
+
id: "1760013210001",
|
|
48
|
+
name: "PRUEBAS SERVICIO DE RENTAS INTERNAS",
|
|
49
|
+
address: "Av. Amazonas y Villalengua, Quito"
|
|
50
|
+
},
|
|
51
|
+
items: [
|
|
52
|
+
{
|
|
53
|
+
code: "P-001",
|
|
54
|
+
description: "Servicio de prueba",
|
|
55
|
+
quantity: "1",
|
|
56
|
+
unitPrice: "1.00",
|
|
57
|
+
taxes: [{ type: "vat", rate: "15" }]
|
|
58
|
+
}
|
|
59
|
+
],
|
|
60
|
+
payments: [{ method: "cash", amount: "1.15" }],
|
|
61
|
+
options: { waitForAuthorization: true }
|
|
62
|
+
}
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
puts invoice[:status], invoice[:accessKey]
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
Las peticiones y las respuestas son hashes con las claves de la API en camelCase, como símbolos
|
|
69
|
+
(`invoice[:accessKey]`), con sus tipos en `Flashpi::Types` (`Flashpi::Types::create_invoice`,
|
|
70
|
+
`Flashpi::Types::document`). Los montos y cantidades son **textos** (`"1.15"`), nunca números,
|
|
71
|
+
para no perder decimales. Escribe el cuerpo entre llaves, `create({ ... })`: sin ellas, Ruby lo
|
|
72
|
+
tomaría como opciones de la llamada.
|
|
73
|
+
|
|
74
|
+
Con el **emisor demo** puedes emitir en pruebas sin subir un certificado: su id está en el
|
|
75
|
+
Resumen de la consola (hasta 50 comprobantes al día). Más en
|
|
76
|
+
[Sandbox y emisor demo](https://flashpi.com.ec/docs/sandbox/).
|
|
77
|
+
|
|
78
|
+
Un cliente mantiene abiertas sus conexiones para las siguientes peticiones y se puede compartir
|
|
79
|
+
entre hilos: crea uno y reutilízalo (en Rails, por ejemplo, en un initializer). `flashpi.close`
|
|
80
|
+
cierra esas conexiones.
|
|
81
|
+
|
|
82
|
+
## Emitir comprobantes
|
|
83
|
+
|
|
84
|
+
| Comprobante | Método |
|
|
85
|
+
| --------------------- | ------------------------------------------- |
|
|
86
|
+
| Factura | `flashpi.invoices.create(body)` |
|
|
87
|
+
| Nota de crédito | `flashpi.credit_notes.create(body)` |
|
|
88
|
+
| Nota de débito | `flashpi.debit_notes.create(body)` |
|
|
89
|
+
| Liquidación de compra | `flashpi.purchase_settlements.create(body)` |
|
|
90
|
+
| Guía de remisión | `flashpi.waybills.create(body)` |
|
|
91
|
+
| Retención | `flashpi.withholdings.create(body)` |
|
|
92
|
+
|
|
93
|
+
Todos devuelven el documento. Por defecto la respuesta llega enseguida con el estado
|
|
94
|
+
`processing` y el resultado del SRI llega por webhook. Con
|
|
95
|
+
`options: { waitForAuthorization: true }` la API espera la respuesta del SRI (15 s por defecto,
|
|
96
|
+
hasta 30 s con `waitTimeoutSeconds`) y devuelve `authorized`, `rejected` o `failed`; si el SRI
|
|
97
|
+
tarda más, devuelve `processing` o `pending_sri` y el documento sigue su curso.
|
|
98
|
+
|
|
99
|
+
## Documentos
|
|
100
|
+
|
|
101
|
+
```ruby
|
|
102
|
+
document = flashpi.documents.get(invoice[:id])
|
|
103
|
+
puts document[:status]
|
|
104
|
+
|
|
105
|
+
xml = flashpi.documents.xml(invoice[:id]) # xml[:kind]: "authorized" cuando ya lo autorizó el SRI
|
|
106
|
+
pdf = flashpi.documents.pdf(invoice[:id]) # el RIDE, en bytes
|
|
107
|
+
File.binwrite("#{invoice[:accessKey]}.pdf", pdf)
|
|
108
|
+
puts xml[:xml] if xml[:kind] == "authorized"
|
|
109
|
+
|
|
110
|
+
flashpi.documents.send_email(invoice[:id]) # reenvía RIDE y XML al correo del comprador
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
## Listas y paginación
|
|
114
|
+
|
|
115
|
+
Una lista devuelve una página que es `Enumerable`: `each` recorre todas las páginas, que se
|
|
116
|
+
piden a medida que avanzas, y `first(10)` solo pide las que necesita.
|
|
117
|
+
|
|
118
|
+
```ruby
|
|
119
|
+
flashpi.documents.list({ status: "authorized", issueDateFrom: "2026-11-01" }).each do |document|
|
|
120
|
+
puts document[:accessKey]
|
|
121
|
+
end
|
|
122
|
+
|
|
123
|
+
page = flashpi.documents.list({ limit: 50 })
|
|
124
|
+
puts page.data.size # los documentos de esta página
|
|
125
|
+
page = page.next_page if page.has_next_page?
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
Los filtros usan los nombres de la API (`issueDateFrom`, `issuerId`) y van en un hash entre
|
|
129
|
+
llaves, antes de las opciones de la llamada.
|
|
130
|
+
|
|
131
|
+
## Errores
|
|
132
|
+
|
|
133
|
+
Cada error de la API es una subclase de `Flashpi::APIError` según su estado HTTP. Decide según
|
|
134
|
+
`code`, que es estable y en inglés; `message` sigue el idioma pedido.
|
|
135
|
+
|
|
136
|
+
```ruby
|
|
137
|
+
begin
|
|
138
|
+
flashpi.invoices.create(body)
|
|
139
|
+
rescue Flashpi::UnprocessableEntityError => e
|
|
140
|
+
puts e.code # "validation_failed", "total_mismatch", ...
|
|
141
|
+
e.errors.each { |field| puts "#{field[:field]}: #{field[:message]}" }
|
|
142
|
+
raise
|
|
143
|
+
rescue Flashpi::APIError => e
|
|
144
|
+
puts e.status, e.code, e.request_id # comparte request_id con soporte
|
|
145
|
+
raise
|
|
146
|
+
end
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
| Clase | Estado | Ejemplos de `code` |
|
|
150
|
+
| ----------------------------------- | ------ | ----------------------------------------------------------- |
|
|
151
|
+
| `Flashpi::BadRequestError` | 400 | `malformed_json`, `invalid_idempotency_key` |
|
|
152
|
+
| `Flashpi::AuthenticationError` | 401 | `authentication_required`, `invalid_api_key` |
|
|
153
|
+
| `Flashpi::PermissionDeniedError` | 403 | `key_read_only`, `key_scope_mismatch`, `ip_not_allowed` |
|
|
154
|
+
| `Flashpi::NotFoundError` | 404 | `not_found` |
|
|
155
|
+
| `Flashpi::ConflictError` | 409 | `sequential_already_used`, `ride_not_available` |
|
|
156
|
+
| `Flashpi::UnprocessableEntityError` | 422 | `validation_failed`, `total_mismatch` |
|
|
157
|
+
| `Flashpi::RateLimitError` | 429 | `demo_issuer_quota_exceeded`, `account_email_limit_reached` |
|
|
158
|
+
| `Flashpi::InternalServerError` | 5xx | `internal_error` |
|
|
159
|
+
| `Flashpi::APIConnectionError` | — | sin respuesta (red); `APITimeoutError` si se agotó el plazo |
|
|
160
|
+
|
|
161
|
+
Todas derivan de `Flashpi::Error`. Algunos errores traen datos extra en `error.problem`, por
|
|
162
|
+
ejemplo `documentId`, `limit`, `resetsAt` o `rideStatus`. Para recibir los mensajes en español:
|
|
163
|
+
`Flashpi::Client.new(language: "es")`.
|
|
164
|
+
|
|
165
|
+
## Reintentos e idempotencia
|
|
166
|
+
|
|
167
|
+
El SDK reintenta hasta 2 veces, con espera creciente, los errores de red, los tiempos agotados y
|
|
168
|
+
las respuestas 408, 429 y 5xx (si piden esperar 60 s o menos; no 501 ni
|
|
169
|
+
`demo_issuer_unavailable`). Cada POST lleva un `Idempotency-Key` que se repite en sus reintentos,
|
|
170
|
+
así que la API nunca emite dos veces:
|
|
171
|
+
|
|
172
|
+
- Si un reintento descubre que el primer intento sí creó el documento, el SDK devuelve ese
|
|
173
|
+
documento.
|
|
174
|
+
- Si el primer intento sigue en curso en la API (por ejemplo, se cortó la conexión mientras
|
|
175
|
+
esperaba al SRI), el SDK espera a que termine con la misma clave, hasta el tiempo límite de la
|
|
176
|
+
llamada, sin gastar reintentos.
|
|
177
|
+
|
|
178
|
+
Para usar tu propia clave (por ejemplo el id de tu pedido), pásala a la llamada:
|
|
179
|
+
|
|
180
|
+
```ruby
|
|
181
|
+
flashpi.invoices.create(body, idempotency_key: "pedido-#{order.id}")
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
Si una emisión falla igual, el error (un `Flashpi::Error`) trae la clave que usó en
|
|
185
|
+
`error.idempotency_key`. Reintentar con `idempotency_key: error.idempotency_key` nunca emite un
|
|
186
|
+
segundo documento: dentro de 24 horas la API devuelve la primera respuesta; después (o si la API
|
|
187
|
+
perdió el primer intento), la llamada falla con un 422 `idempotency_key_reused` cuyo
|
|
188
|
+
`error.problem[:documentId]` es el documento que ya existe (léelo con `flashpi.documents.get`).
|
|
189
|
+
|
|
190
|
+
```ruby
|
|
191
|
+
begin
|
|
192
|
+
flashpi.invoices.create(body)
|
|
193
|
+
rescue Flashpi::Error => e
|
|
194
|
+
save_for_retry(body, e.idempotency_key) if e.idempotency_key # tu cola de reintentos
|
|
195
|
+
raise
|
|
196
|
+
end
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
Una llamada que interrumpes desde fuera (con `Timeout.timeout`, o al detener el proceso o el
|
|
200
|
+
hilo) no lanza un `Flashpi::Error` ni trae la clave: si lo haces con emisiones, pasa tu propio
|
|
201
|
+
`idempotency_key`.
|
|
202
|
+
|
|
203
|
+
Los límites diarios (como la cuota del emisor demo) no se reintentan: se lanzan como
|
|
204
|
+
`Flashpi::RateLimitError` con `retry_after` en segundos.
|
|
205
|
+
|
|
206
|
+
## Webhooks
|
|
207
|
+
|
|
208
|
+
Verifica cada webhook con el cuerpo **tal cual llegó** (sin parsear) y el secreto `whsec_` del
|
|
209
|
+
endpoint. `Flashpi::Webhooks.unwrap` no necesita clave de API (también está en
|
|
210
|
+
`flashpi.webhooks`). Acepta las cabeceras como un hash, el `env` de Rack o `request.headers` de
|
|
211
|
+
Rails.
|
|
212
|
+
|
|
213
|
+
Con Rails:
|
|
214
|
+
|
|
215
|
+
```ruby
|
|
216
|
+
class FlashpiWebhooksController < ApplicationController
|
|
217
|
+
skip_forgery_protection
|
|
218
|
+
|
|
219
|
+
def create
|
|
220
|
+
event = Flashpi::Webhooks.unwrap(request.raw_post, request.headers, ENV.fetch("FLASHPI_WEBHOOK_SECRET"))
|
|
221
|
+
|
|
222
|
+
case event[:type]
|
|
223
|
+
when "webhook_endpoint.verification"
|
|
224
|
+
# La activación del endpoint: responde el desafío.
|
|
225
|
+
return render(json: { challenge: event[:data][:challenge] })
|
|
226
|
+
when "invoice.authorized"
|
|
227
|
+
Rails.logger.info("Autorizada #{event[:data][:accessKey]}") # event[:data] es el documento
|
|
228
|
+
when "invoice.rejected"
|
|
229
|
+
Rails.logger.info("Rechazada #{event[:data][:sriMessages]}")
|
|
230
|
+
end
|
|
231
|
+
head :no_content
|
|
232
|
+
rescue Flashpi::WebhookVerificationError
|
|
233
|
+
head :bad_request
|
|
234
|
+
end
|
|
235
|
+
end
|
|
236
|
+
```
|
|
237
|
+
|
|
238
|
+
Con Sinatra (o cualquier app Rack, con su `env`):
|
|
239
|
+
|
|
240
|
+
```ruby
|
|
241
|
+
require "sinatra"
|
|
242
|
+
require "flashpi"
|
|
243
|
+
|
|
244
|
+
post "/webhooks/flashpi" do
|
|
245
|
+
event = Flashpi::Webhooks.unwrap(request.body.read, request.env, ENV.fetch("FLASHPI_WEBHOOK_SECRET"))
|
|
246
|
+
if event[:type] == "webhook_endpoint.verification"
|
|
247
|
+
content_type :json
|
|
248
|
+
JSON.generate({ challenge: event[:data][:challenge] })
|
|
249
|
+
else
|
|
250
|
+
handle_event(event) # tu código, como las ramas del ejemplo de Rails
|
|
251
|
+
204
|
|
252
|
+
end
|
|
253
|
+
rescue Flashpi::WebhookVerificationError
|
|
254
|
+
400
|
|
255
|
+
end
|
|
256
|
+
```
|
|
257
|
+
|
|
258
|
+
Guarda el `event[:id]` y descarta los repetidos: un evento puede llegar más de una vez. Durante
|
|
259
|
+
una rotación del secreto, Flashpi firma con el nuevo y el anterior, así que cualquiera de los dos
|
|
260
|
+
sirve. Si el endpoint usa el modo `thin` (sin `data`), pide el evento con
|
|
261
|
+
`flashpi.events.get(event[:id])`.
|
|
262
|
+
|
|
263
|
+
## Emisores y certificados
|
|
264
|
+
|
|
265
|
+
Estas operaciones necesitan una clave de toda la cuenta con acceso de lectura y escritura.
|
|
266
|
+
|
|
267
|
+
Un emisor nace de su firma electrónica (.p12): Flashpi la verifica, lee el RUC y consulta al SRI,
|
|
268
|
+
y te devuelve un `prefill` con lo que encontró para que armes el emisor.
|
|
269
|
+
|
|
270
|
+
```ruby
|
|
271
|
+
onboarding = flashpi.issuer_onboardings.create(
|
|
272
|
+
{ file: File.binread("firma.p12"), password: ENV.fetch("P12_PASSWORD") }
|
|
273
|
+
)
|
|
274
|
+
while onboarding[:status] == "verifying"
|
|
275
|
+
sleep 2
|
|
276
|
+
onboarding = flashpi.issuer_onboardings.get(onboarding[:id])
|
|
277
|
+
end
|
|
278
|
+
unless onboarding[:status] == "ready"
|
|
279
|
+
rejection = onboarding[:rejection]
|
|
280
|
+
raise(rejection ? rejection[:message] : onboarding[:status])
|
|
281
|
+
end
|
|
282
|
+
|
|
283
|
+
prefill = onboarding[:prefill]
|
|
284
|
+
completed =
|
|
285
|
+
if onboarding[:existingIssuer]
|
|
286
|
+
# Ya tienes ese RUC: el certificado se agrega a ese emisor (una renovación).
|
|
287
|
+
flashpi.issuer_onboardings.complete(onboarding[:id])
|
|
288
|
+
else
|
|
289
|
+
# Un RUC nuevo: tú confirmas los datos del emisor, partiendo del prefill.
|
|
290
|
+
tax_profile = prefill && prefill[:taxProfile]
|
|
291
|
+
rimpe_regime = tax_profile && tax_profile[:rimpeRegime]
|
|
292
|
+
flashpi.issuer_onboardings.complete(
|
|
293
|
+
onboarding[:id],
|
|
294
|
+
{
|
|
295
|
+
legalName: (prefill && prefill[:legalName]) || "MI EMPRESA S.A.",
|
|
296
|
+
headOfficeAddress: (prefill && prefill[:headOfficeAddress]) || "Av. Amazonas N24-100, Quito",
|
|
297
|
+
taxProfile: {
|
|
298
|
+
keepsAccounting: tax_profile ? tax_profile[:keepsAccounting] == true : false,
|
|
299
|
+
# El régimen RIMPE, si lo tiene ("general" no es uno).
|
|
300
|
+
rimpeRegime: case rimpe_regime when "entrepreneur", "popular_business" then rimpe_regime end
|
|
301
|
+
# Si es contribuyente especial o agente de retención, agrega sus resoluciones.
|
|
302
|
+
}
|
|
303
|
+
# Si onboarding[:rucNeedsConfirmation] es true, envía también ruc:.
|
|
304
|
+
}
|
|
305
|
+
)
|
|
306
|
+
end
|
|
307
|
+
|
|
308
|
+
flashpi.issuers.establishments.list(completed[:issuer][:id]).each do |establishment|
|
|
309
|
+
puts establishment[:code]
|
|
310
|
+
end
|
|
311
|
+
```
|
|
312
|
+
|
|
313
|
+
El `file` puede ser el contenido del .p12 (`File.binread("firma.p12")`) o un archivo abierto en
|
|
314
|
+
modo binario (`File.open("firma.p12", "rb")`), de hasta 1 MiB.
|
|
315
|
+
|
|
316
|
+
Para **renovar la firma** de un emisor, para pruebas y producción a la vez, repite el mismo
|
|
317
|
+
flujo con el .p12 nuevo: Flashpi reconoce el RUC (`existingIssuer`) y `complete` sin datos
|
|
318
|
+
agrega el certificado. En cambio,
|
|
319
|
+
`flashpi.issuers.certificates.upload(issuer_id, { file: ..., password: ... })` sube un
|
|
320
|
+
certificado solo para el modo de la clave que usas (pruebas o producción).
|
|
321
|
+
|
|
322
|
+
## Opciones
|
|
323
|
+
|
|
324
|
+
```ruby
|
|
325
|
+
flashpi = Flashpi::Client.new(
|
|
326
|
+
api_key: ENV.fetch("FLASHPI_API_KEY"), # por defecto, la variable FLASHPI_API_KEY
|
|
327
|
+
language: "es", # idioma de los mensajes: "en" (por defecto) o "es"
|
|
328
|
+
timeout: 60, # segundos por intento (con waitForAuthorization, al menos la espera + 15 s)
|
|
329
|
+
max_retries: 2 # 0 desactiva los reintentos
|
|
330
|
+
)
|
|
331
|
+
```
|
|
332
|
+
|
|
333
|
+
Cada método acepta además, como argumentos con nombre, opciones de esa petición:
|
|
334
|
+
`idempotency_key`, `timeout`, `max_retries`, `language`, `correlation_id` (tu propio id, que
|
|
335
|
+
Flashpi registra) y `extra_headers`.
|
|
336
|
+
|
|
337
|
+
```ruby
|
|
338
|
+
document = flashpi.documents.get(document_id, timeout: 10, language: "es", correlation_id: "pedido-42")
|
|
339
|
+
```
|
|
340
|
+
|
|
341
|
+
Para ver la respuesta HTTP y el id de la petición, llama al método a través de `with_response`:
|
|
342
|
+
|
|
343
|
+
```ruby
|
|
344
|
+
result = flashpi.documents.with_response.get(document_id)
|
|
345
|
+
puts result.data[:status], result.status, result.request_id
|
|
346
|
+
```
|
|
347
|
+
|
|
348
|
+
El tiempo límite es uno solo por intento, desde que se envía hasta que se lee toda la respuesta:
|
|
349
|
+
conectar, el saludo TLS y cada lectura y escritura cuentan contra él (solo la consulta DNS puede
|
|
350
|
+
pasarse). Las peticiones salen por net/http con el proxy de las variables de entorno
|
|
351
|
+
(`https_proxy` o `HTTPS_PROXY`, una URL `http://`, y `no_proxy`), que se leen al crear el cliente,
|
|
352
|
+
y el SDK nunca sigue redirecciones. En tus pruebas, WebMock o VCR pueden responder en lugar de la
|
|
353
|
+
API.
|
|
354
|
+
|
|
355
|
+
## Tipos
|
|
356
|
+
|
|
357
|
+
El gem trae sus firmas RBS en `sig/`. Con [Steep](https://github.com/soutaro/steep),
|
|
358
|
+
`rbs collection install` las encuentra en tu `Gemfile.lock`, y Steep revisa los nombres de los
|
|
359
|
+
campos, sus valores posibles y las opciones de cada llamada. Las firmas necesitan rbs 3.5 o
|
|
360
|
+
superior (Steep 1.7 o superior); Ruby 3.3 trae rbs 3.4.
|
|
361
|
+
|
|
362
|
+
```ruby
|
|
363
|
+
# @type var body: Flashpi::Types::create_invoice
|
|
364
|
+
body = {
|
|
365
|
+
issuerId: "<id del emisor>",
|
|
366
|
+
establishment: "001",
|
|
367
|
+
emissionPoint: "001",
|
|
368
|
+
customer: { idType: "final_consumer" },
|
|
369
|
+
items: [{ description: "Pan", quantity: "2", unitPrice: "0.50", taxes: [{ type: "vat", rate: "15" }] }],
|
|
370
|
+
payments: [{ method: "cash", amount: "1.15" }]
|
|
371
|
+
}
|
|
372
|
+
document = flashpi.invoices.create(body) # Flashpi::Types::document
|
|
373
|
+
puts document[:accessKey]
|
|
374
|
+
```
|
|
375
|
+
|
|
376
|
+
## Solo en el servidor
|
|
377
|
+
|
|
378
|
+
Tu clave de API es secreta: usa el SDK en tus servidores, nunca en código que corre en los
|
|
379
|
+
dispositivos de tus usuarios. `flashpi.inspect` muestra el ambiente y la URL, nunca la clave.
|
|
380
|
+
|
|
381
|
+
## Licencia
|
|
382
|
+
|
|
383
|
+
[MIT](https://github.com/flashpi1/flashpi-ruby/blob/main/LICENSE) © 2026 SIGNIADIGITAL S.A.
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Flashpi
|
|
4
|
+
# The data of a call together with the HTTP answer it came from, returned by the methods of a
|
|
5
|
+
# resource's `with_response` view:
|
|
6
|
+
#
|
|
7
|
+
# result = flashpi.documents.with_response.get(document_id)
|
|
8
|
+
# result.data[:status]
|
|
9
|
+
# result.status # 200
|
|
10
|
+
# result.request_id # share it with support
|
|
11
|
+
class APIResponse
|
|
12
|
+
# @return [Object] what the method returns
|
|
13
|
+
attr_reader :data
|
|
14
|
+
# @return [Integer] the HTTP status
|
|
15
|
+
attr_reader :status
|
|
16
|
+
# @return [Hash{String => String}] the response headers, by lowercase name
|
|
17
|
+
attr_reader :headers
|
|
18
|
+
# @return [String, nil] Flashpi's id of the request (`x-request-id`)
|
|
19
|
+
attr_reader :request_id
|
|
20
|
+
|
|
21
|
+
def initialize(data:, status:, headers:, request_id:)
|
|
22
|
+
@data = data
|
|
23
|
+
@status = status
|
|
24
|
+
@headers = headers
|
|
25
|
+
@request_id = request_id
|
|
26
|
+
freeze
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
def inspect
|
|
30
|
+
"#<#{self.class.name} status=#{status} request_id=#{request_id.inspect} data=#{(_ = data).inspect}>"
|
|
31
|
+
end
|
|
32
|
+
end
|
|
33
|
+
end
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Flashpi
|
|
4
|
+
# The address of the Flashpi API.
|
|
5
|
+
DEFAULT_BASE_URL = "https://api.flashpi.com.ec"
|
|
6
|
+
# Seconds each attempt of a request may take, from sending it to reading the whole answer (the
|
|
7
|
+
# Node SDK's 60 000 ms).
|
|
8
|
+
DEFAULT_TIMEOUT = 60.0
|
|
9
|
+
# Retries after network errors, timeouts, 429 and 5xx.
|
|
10
|
+
DEFAULT_MAX_RETRIES = 2
|
|
11
|
+
|
|
12
|
+
# The Flashpi API client.
|
|
13
|
+
#
|
|
14
|
+
# flashpi = Flashpi::Client.new # reads FLASHPI_API_KEY
|
|
15
|
+
# invoice = flashpi.invoices.create({ ... })
|
|
16
|
+
#
|
|
17
|
+
# An `fp_test_` key issues in the SRI test environment (pruebas); an `fp_live_` key issues real
|
|
18
|
+
# documents in production. Use it on servers only: the key must stay secret. A client is safe
|
|
19
|
+
# to share between threads and keeps its connections open for the next requests: create one
|
|
20
|
+
# and reuse it.
|
|
21
|
+
class Client
|
|
22
|
+
# @return [String] `"test"` for fp_test_ keys (SRI pruebas), `"live"` for fp_live_ keys (SRI
|
|
23
|
+
# production)
|
|
24
|
+
attr_reader :environment
|
|
25
|
+
# @return [Resources::Invoices] invoices (facturas)
|
|
26
|
+
attr_reader :invoices
|
|
27
|
+
# @return [Resources::CreditNotes] credit notes (notas de crédito)
|
|
28
|
+
attr_reader :credit_notes
|
|
29
|
+
# @return [Resources::DebitNotes] debit notes (notas de débito)
|
|
30
|
+
attr_reader :debit_notes
|
|
31
|
+
# @return [Resources::PurchaseSettlements] purchase settlements (liquidaciones de compra)
|
|
32
|
+
attr_reader :purchase_settlements
|
|
33
|
+
# @return [Resources::Waybills] waybills (guías de remisión)
|
|
34
|
+
attr_reader :waybills
|
|
35
|
+
# @return [Resources::Withholdings] withholding receipts (comprobantes de retención)
|
|
36
|
+
attr_reader :withholdings
|
|
37
|
+
# @return [Resources::Documents] every issued document: search, XML, RIDE (PDF) and email
|
|
38
|
+
attr_reader :documents
|
|
39
|
+
# @return [Resources::Issuers] issuers (RUCs) with their establishments, emission points and
|
|
40
|
+
# certificates
|
|
41
|
+
attr_reader :issuers
|
|
42
|
+
# @return [Resources::IssuerOnboardings] create an issuer from its .p12 certificate
|
|
43
|
+
attr_reader :issuer_onboardings
|
|
44
|
+
# @return [Resources::WebhookEndpoints] the URLs Flashpi sends events to
|
|
45
|
+
attr_reader :webhook_endpoints
|
|
46
|
+
# @return [Resources::Events] events of documents, certificates and email sending
|
|
47
|
+
attr_reader :events
|
|
48
|
+
# @return [Resources::Status] the API's status
|
|
49
|
+
attr_reader :status
|
|
50
|
+
|
|
51
|
+
# Creates a client.
|
|
52
|
+
#
|
|
53
|
+
# @param api_key [String, nil] the API key (`fp_test_...` or `fp_live_...`); defaults to the
|
|
54
|
+
# FLASHPI_API_KEY environment variable
|
|
55
|
+
# @param base_url [String, nil] the API's address (default https://api.flashpi.com.ec)
|
|
56
|
+
# @param timeout [Integer, Float, nil] seconds each attempt of a request may take, from
|
|
57
|
+
# sending it to reading the whole answer (default 60). Issuing with
|
|
58
|
+
# `options: { waitForAuthorization: true }` raises it to the wait plus 15 seconds. Only a
|
|
59
|
+
# DNS lookup can run past it.
|
|
60
|
+
# @param max_retries [Integer, nil] retries after network errors, timeouts, 429 and 5xx
|
|
61
|
+
# (default 2; 0 turns them off)
|
|
62
|
+
# @param language [String, Symbol, nil] language of the API's messages: `"en"` (default) or
|
|
63
|
+
# `"es"`. Error codes do not change.
|
|
64
|
+
# @param default_headers [Hash{String => String}, nil] headers sent with every request (not
|
|
65
|
+
# `Idempotency-Key`: that one is per request)
|
|
66
|
+
# @raise [Flashpi::Error] for a missing or bad API key, base URL, timeout or max_retries
|
|
67
|
+
def initialize(api_key: nil, base_url: nil, timeout: nil, max_retries: nil, language: nil, default_headers: nil)
|
|
68
|
+
config = Internal::Settings.configure(api_key, base_url:, timeout:, max_retries:, language:, default_headers:)
|
|
69
|
+
@environment = config.api_key.start_with?("fp_test_") ? "test" : "live"
|
|
70
|
+
@transport = Internal::Transport.new(config.base_url)
|
|
71
|
+
@engine = Internal::Engine.new(config, @transport)
|
|
72
|
+
@invoices = Resources::Invoices.new(@engine)
|
|
73
|
+
@credit_notes = Resources::CreditNotes.new(@engine)
|
|
74
|
+
@debit_notes = Resources::DebitNotes.new(@engine)
|
|
75
|
+
@purchase_settlements = Resources::PurchaseSettlements.new(@engine)
|
|
76
|
+
@waybills = Resources::Waybills.new(@engine)
|
|
77
|
+
@withholdings = Resources::Withholdings.new(@engine)
|
|
78
|
+
@documents = Resources::Documents.new(@engine)
|
|
79
|
+
@issuers = Resources::Issuers.new(@engine)
|
|
80
|
+
@issuer_onboardings = Resources::IssuerOnboardings.new(@engine)
|
|
81
|
+
@webhook_endpoints = Resources::WebhookEndpoints.new(@engine)
|
|
82
|
+
@events = Resources::Events.new(@engine)
|
|
83
|
+
@status = Resources::Status.new(@engine)
|
|
84
|
+
end
|
|
85
|
+
|
|
86
|
+
# Verify the signature of the webhooks you receive (no API key needed).
|
|
87
|
+
#
|
|
88
|
+
# @return [Module] {Flashpi::Webhooks}
|
|
89
|
+
def webhooks
|
|
90
|
+
Webhooks
|
|
91
|
+
end
|
|
92
|
+
|
|
93
|
+
# @return [String] the API's address
|
|
94
|
+
def base_url
|
|
95
|
+
@engine.config.base_url
|
|
96
|
+
end
|
|
97
|
+
|
|
98
|
+
# Closes the connections kept open for the next requests. The client can still be used: it
|
|
99
|
+
# opens new ones.
|
|
100
|
+
#
|
|
101
|
+
# @return [nil]
|
|
102
|
+
def close
|
|
103
|
+
@transport.close
|
|
104
|
+
end
|
|
105
|
+
|
|
106
|
+
# Never the API key.
|
|
107
|
+
def inspect
|
|
108
|
+
"#<#{self.class.name} environment=#{environment.inspect} base_url=#{base_url.inspect}>"
|
|
109
|
+
end
|
|
110
|
+
alias to_s inspect
|
|
111
|
+
end
|
|
112
|
+
end
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Flashpi
|
|
4
|
+
# Every error this gem raises extends this class, except for invalid arguments (`ArgumentError`
|
|
5
|
+
# and `TypeError`, as for any Ruby method).
|
|
6
|
+
class Error < StandardError
|
|
7
|
+
# The Idempotency-Key a failed POST used (the caller's or the one the SDK made), or nil. To try
|
|
8
|
+
# the same operation again later without issuing twice, pass it back:
|
|
9
|
+
# `create(body, idempotency_key: error.idempotency_key)`.
|
|
10
|
+
attr_accessor :idempotency_key
|
|
11
|
+
end
|
|
12
|
+
|
|
13
|
+
# The API answered with an error status.
|
|
14
|
+
#
|
|
15
|
+
# Branch on {#code} (stable English slugs such as `validation_failed`), never on {#message},
|
|
16
|
+
# which follows the requested language.
|
|
17
|
+
class APIError < Error
|
|
18
|
+
# @return [Integer] HTTP status of the answer.
|
|
19
|
+
attr_reader :status
|
|
20
|
+
|
|
21
|
+
# @return [String, nil] Error code, or nil when the answer had no Problem Details (a 502).
|
|
22
|
+
attr_reader :code
|
|
23
|
+
|
|
24
|
+
# @return [String, nil] Short summary of the problem type.
|
|
25
|
+
attr_reader :title
|
|
26
|
+
|
|
27
|
+
# @return [String, nil] What went wrong in this request.
|
|
28
|
+
attr_reader :detail
|
|
29
|
+
|
|
30
|
+
# @return [Array<Hash{Symbol => Object}>] Field-level problems of a request body or query.
|
|
31
|
+
attr_reader :errors
|
|
32
|
+
|
|
33
|
+
# @return [String, nil] Flashpi's id of the request (`x-request-id`): share it with support.
|
|
34
|
+
attr_reader :request_id
|
|
35
|
+
|
|
36
|
+
# @return [Hash{Symbol => Object}, nil] The full Problem Details body, with its extension
|
|
37
|
+
# members (`documentId`, `limit`, `resetsAt`, ...), when there was one.
|
|
38
|
+
attr_reader :problem
|
|
39
|
+
|
|
40
|
+
# @return [Hash{String => String}] Response headers, by lowercase name.
|
|
41
|
+
attr_reader :headers
|
|
42
|
+
|
|
43
|
+
# @param status [Integer]
|
|
44
|
+
# @param headers [Hash{String => String}] by lowercase name
|
|
45
|
+
# @param problem [Hash{Symbol => Object}, nil]
|
|
46
|
+
# @param body_text [String]
|
|
47
|
+
def initialize(status, headers, problem, body_text = "")
|
|
48
|
+
super(Internal::Problems.message(status, problem, body_text))
|
|
49
|
+
@status = status
|
|
50
|
+
@headers = headers
|
|
51
|
+
@problem = problem
|
|
52
|
+
members = problem || {}
|
|
53
|
+
@code = Internal::Problems.text(members[:code])
|
|
54
|
+
@title = Internal::Problems.text(members[:title])
|
|
55
|
+
@detail = Internal::Problems.text(members[:detail])
|
|
56
|
+
errors = members[:errors]
|
|
57
|
+
@errors = errors.is_a?(Array) ? errors : []
|
|
58
|
+
@request_id = Internal::Problems.text(members[:requestId]) || headers["x-request-id"]
|
|
59
|
+
end
|
|
60
|
+
|
|
61
|
+
# Seconds the API asked to wait before trying again (`Retry-After`), or nil.
|
|
62
|
+
#
|
|
63
|
+
# Daily quota errors point at the next midnight in Ecuador, so this can be hours.
|
|
64
|
+
#
|
|
65
|
+
# @return [Integer, nil]
|
|
66
|
+
def retry_after
|
|
67
|
+
Internal::Problems.retry_after(headers["retry-after"])
|
|
68
|
+
end
|
|
69
|
+
end
|
|
70
|
+
|
|
71
|
+
# 400: the request could not be read (malformed JSON, invalid Idempotency-Key, ...).
|
|
72
|
+
class BadRequestError < APIError; end
|
|
73
|
+
|
|
74
|
+
# 401: the API key is missing, malformed, unknown or revoked.
|
|
75
|
+
class AuthenticationError < APIError; end
|
|
76
|
+
|
|
77
|
+
# 403: the key may not do this (read-only, another issuer, IP allowlist, suspended account).
|
|
78
|
+
class PermissionDeniedError < APIError; end
|
|
79
|
+
|
|
80
|
+
# 404: the resource does not exist in this mode (test or live) for this account.
|
|
81
|
+
class NotFoundError < APIError; end
|
|
82
|
+
|
|
83
|
+
# 409: the request conflicts with the current state (sequential used, RIDE not ready, ...).
|
|
84
|
+
class ConflictError < APIError; end
|
|
85
|
+
|
|
86
|
+
# 422: the request is well formed but invalid (`validation_failed`, `total_mismatch`, ...).
|
|
87
|
+
class UnprocessableEntityError < APIError; end
|
|
88
|
+
|
|
89
|
+
# 429: a limit was reached; see {#retry_after} and the `limit` and `resetsAt` members.
|
|
90
|
+
class RateLimitError < APIError; end
|
|
91
|
+
|
|
92
|
+
# 5xx: Flashpi failed to answer. Requests are retried automatically before this is raised.
|
|
93
|
+
class InternalServerError < APIError; end
|
|
94
|
+
|
|
95
|
+
# The request never got an answer (DNS, TLS, connection reset, ...).
|
|
96
|
+
class APIConnectionError < Error; end
|
|
97
|
+
|
|
98
|
+
# The request took longer than the `timeout` option.
|
|
99
|
+
class APITimeoutError < APIConnectionError; end
|
|
100
|
+
|
|
101
|
+
# A webhook did not come from Flashpi, was altered, or is too old: answer 400 and ignore it.
|
|
102
|
+
class WebhookVerificationError < Error
|
|
103
|
+
# Why it was rejected: `:missing_headers`, `:invalid_timestamp`, `:timestamp_out_of_range`,
|
|
104
|
+
# `:no_matching_signature`, `:invalid_secret` or `:invalid_payload`.
|
|
105
|
+
#
|
|
106
|
+
# @return [Symbol]
|
|
107
|
+
attr_reader :reason
|
|
108
|
+
|
|
109
|
+
# @param reason [Symbol]
|
|
110
|
+
# @param message [String]
|
|
111
|
+
def initialize(reason, message)
|
|
112
|
+
super(message)
|
|
113
|
+
@reason = reason
|
|
114
|
+
end
|
|
115
|
+
end
|
|
116
|
+
end
|