-
Notifications
You must be signed in to change notification settings - Fork 56
API REST
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class VerifactuApiPostExample {
public static void main(String[] args) {
// URL del endpoint
String endpoint = "https://facturae.irenesolutions.com:8050/Kivu/Taxes/Verifactu/Invoices/GetQrCode";
// Cuerpo de la solicitud (JSON)
String requestBody = """
{
"ServiceKey": "your service key",
"InvoiceID": "FRTEST1734699642488",
"InvoiceDate": "2024-12-20T13:00:42.488Z",
"SellerID": "B12959755",
"CompanyName": "IRENE SOLUTIONS SL",
"TaxItems": [
{
"TaxBase": 11.99,
"TaxAmount": 2.52
}
]
}
""";
try {
// Crear cliente HTTP
HttpClient client = HttpClient.newHttpClient();
// Construir la solicitud
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(endpoint))
.header("Content-Type", "application/json") // Tipo de contenido
.POST(HttpRequest.BodyPublishers.ofString(requestBody)) // Método POST con el cuerpo
.build();
// Enviar la solicitud y obtener la respuesta
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
// Manejar la respuesta
if (response.statusCode() == 200) {
System.out.println("Respuesta exitosa:");
System.out.println(response.body());
} else {
System.out.println("Error en la llamada: " + response.statusCode());
System.out.println("Detalle: " + response.body());
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("Error al realizar la solicitud.");
}
}
}
Para deserializar el JSON en un objeto dinámico en Java, puedes usar bibliotecas como Jackson o Gson, que son populares y sencillas de usar.
A continuación, se muestra cómo hacerlo con Jackson, ya que permite trabajar fácilmente con objetos dinámicos.
Primero, asegúrate de incluir la dependencia de Jackson en tu archivo Maven (pom.xml) o Gradle:
Maven:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.15.2</version>
</dependency>
Gradle:
implementation 'com.fasterxml.jackson.core:jackson-databind:2.15.2'
Código para Deserializar JSON en un Objeto Dinámico
Aquí tienes un ejemplo de cómo deserializar el JSON recibido en un objeto dinámico utilizando ObjectMapper de Jackson:
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonDeserializationExample {
public static void main(String[] args) {
// JSON como cadena (puedes obtenerlo desde una respuesta HTTP)
String json = """
{
"ServiceKey": "your service key",
"InvoiceID": "FRTEST1734699642488",
"InvoiceDate": "2024-12-20T13:00:42.488Z",
"SellerID": "B12959755",
"CompanyName": "IRENE SOLUTIONS SL",
"TaxItems": [
{
"TaxBase": 11.99,
"TaxAmount": 2.52
}
]
}
""";
try {
// Crear instancia de ObjectMapper
ObjectMapper objectMapper = new ObjectMapper();
// Deserializar JSON en un objeto dinámico (JsonNode)
JsonNode rootNode = objectMapper.readTree(json);
// Acceder a los campos del JSON
String serviceKey = rootNode.get("ServiceKey").asText();
String invoiceId = rootNode.get("InvoiceID").asText();
String invoiceDate = rootNode.get("InvoiceDate").asText();
String sellerId = rootNode.get("SellerID").asText();
String companyName = rootNode.get("CompanyName").asText();
System.out.println("ServiceKey: " + serviceKey);
System.out.println("InvoiceID: " + invoiceId);
System.out.println("InvoiceDate: " + invoiceDate);
System.out.println("SellerID: " + sellerId);
System.out.println("CompanyName: " + companyName);
// Acceder a los elementos de la lista TaxItems
JsonNode taxItemsNode = rootNode.get("TaxItems");
for (JsonNode item : taxItemsNode) {
double taxBase = item.get("TaxBase").asDouble();
double taxAmount = item.get("TaxAmount").asDouble();
System.out.println("TaxBase: " + taxBase);
System.out.println("TaxAmount: " + taxAmount);
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("Error al deserializar el JSON.");
}
}
}Para realizar una llamada POST a la API https://facturae.irenesolutions.com:8050/Kivu/Taxes/Verifactu/Invoices/Create utilizando Python, puedes usar la librería requests.
Primero, asegúrate de tener instalada la librería requests. Si no la tienes, puedes instalarla desde tu terminal con pip:
pip install requestsimport requests
import json
from datetime import datetime, timezone
# El endpoint de la API
url = "[https://facturae.irenesolutions.com:8050/Kivu/Taxes/Verifactu/Invoices/Create](https://facturae.irenesolutions.com:8050/Kivu/Taxes/Verifactu/Invoices/Create)"
# El cuerpo de la solicitud en formato de diccionario de Python
# La fecha de la factura se ha actualizado a la fecha actual para que sea válida
payload = {
"ServiceKey": "zfzxgzxgcxzgdsaaaaa",
"Status": "POST",
"InvoiceType": "F1",
"InvoiceID": "FRTEST1752504601220",
"InvoiceDate": datetime.now(timezone.utc).isoformat(),
"SellerID": "B12959755",
"CompanyName": "IRENE SOLUTIONS SL",
"RelatedPartyID": "B44531218",
"RelatedPartyName": "WEFINZ SOLUTIONS SL",
"Text": "SERVICIOS INFORMATICOS",
"TaxItems": [
{
"TaxScheme": "01",
"TaxType": "S1",
"TaxRate": 21,
"TaxBase": 11.99,
"TaxAmount": 2.52
}
]
}
try:
# Realizar la solicitud POST
# La librería requests convierte automáticamente el diccionario a JSON
response = requests.post(url, json=payload)
# Forzar una excepción si la respuesta es un error HTTP (ej. 4xx o 5xx)
response.raise_for_status()
# Imprimir el código de estado de la respuesta
print(f"✅ Status Code: {response.status_code}")
# Imprimir la respuesta de la API en formato JSON
print("📝 Response JSON:")
print(json.dumps(response.json(), indent=4))
except requests.exceptions.HTTPError as http_err:
print(f"❌ HTTP error occurred: {http_err}")
print(f" Response body: {response.text}")
except requests.exceptions.RequestException as err:
print(f"❌ Other error occurred: {err}")
except json.JSONDecodeError:
print("❌ La respuesta no es un JSON válido.")-
import requests: Importa la libreríarequests. -
url: Define la URL del endpoint. -
payload: Es un diccionario de Python que contiene los datos a enviar.requestslo convertirá automáticamente a formato JSON y añadirá la cabeceraContent-Type: application/json. -
requests.post(url, json=payload): Ejecuta la solicitudPOST. -
response.raise_for_status(): Es una buena práctica para comprobar si la solicitud fue exitosa. Si el código de estado es un error (como404o500), lanzará una excepción. -
response.json(): Convierte la respuesta JSON del servidor en un diccionario de Python. -
json.dumps(response.json(), indent=4): Muestra el JSON de la respuesta de forma legible y con sangría. -
try...except: El bloquetry...exceptgestiona posibles errores, como problemas de red (requests.exceptions.RequestException), errores HTTP (requests.exceptions.HTTPError) o respuestas que no son JSON válido.
<?php
$url = 'https://facturae.irenesolutions.com:8050/Kivu/Taxes/Verifactu/Invoices/GetQrCode';
$data = [
"ServiceKey" => "your service key", // Sustituye por tu clave real
"InvoiceID" => "FRTEST1734699642488",
"InvoiceDate" => "2024-12-20T13:00:42.488Z",
"SellerID" => "B12959755",
"CompanyName" => "IRENE SOLUTIONS SL",
"TaxItems" => [
[
"TaxBase" => 11.99,
"TaxAmount" => 2.52
]
]
];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json'
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (curl_errno($ch)) {
echo 'Error de cURL: ' . curl_error($ch);
} else {
if ($httpCode === 200) {
echo "QR generado correctamente:\n";
echo $response; // Puedes decodificarlo con json_decode si quieres acceder a los campos
} else {
echo "Error HTTP: $httpCode\n";
echo "Respuesta: $response";
}
}
curl_close($ch);✅ Notas:
-
Este código es completamente funcional en entornos con PHP >= 7.0 y soporte para cURL.
-
Puedes utilizar json_decode($response, true) si necesitas acceder a los datos como array asociativo.
-
Recuerda sustituir "your service key" por la clave válida que te haya sido asignada.
A continuación mostramos cómo realizar llamadas al API REST de Veri*Factu desde aplicaciones .NET.
Recuerda sustituir el campo ServiceKey por tu clave real de acceso.
using System;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
class Program
{
private static readonly HttpClient http = new HttpClient();
static async Task Main()
{
var url = "https://facturae.irenesolutions.com:8050/Kivu/Taxes/Verifactu/Invoices/GetQrCode";
var payload = new
{
ServiceKey = "your service key",
InvoiceID = "FRTEST1734699642488",
InvoiceDate = "2024-12-20T13:00:42.488Z",
SellerID = "B12959755",
CompanyName = "IRENE SOLUTIONS SL",
TaxItems = new[]
{
new { TaxBase = 11.99, TaxAmount = 2.52 }
}
};
var json = JsonSerializer.Serialize(payload);
using var content = new StringContent(json, Encoding.UTF8, "application/json");
using var resp = await http.PostAsync(url, content);
var body = await resp.Content.ReadAsStringAsync();
Console.WriteLine($"Status: {(int)resp.StatusCode}");
Console.WriteLine(body);
}
}using System;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
class Program
{
private static readonly HttpClient http = new HttpClient();
static async Task Main()
{
var url = "https://facturae.irenesolutions.com:8050/Kivu/Taxes/Verifactu/Invoices/Create";
var payload = new
{
ServiceKey = "zfzxgzxgcxzgdsaaaaa",
Status = "POST",
InvoiceType = "F1",
InvoiceID = "FRTEST1752504601220",
InvoiceDate = DateTime.UtcNow.ToString("o"),
SellerID = "B12959755",
CompanyName = "IRENE SOLUTIONS SL",
RelatedPartyID = "B44531218",
RelatedPartyName = "WEFINZ SOLUTIONS SL",
Text = "SERVICIOS INFORMATICOS",
TaxItems = new[]
{
new { TaxScheme = "01", TaxType = "S1", TaxRate = 21, TaxBase = 11.99, TaxAmount = 2.52 }
}
};
var json = JsonSerializer.Serialize(payload);
using var content = new StringContent(json, Encoding.UTF8, "application/json");
using var resp = await http.PostAsync(url, content);
var body = await resp.Content.ReadAsStringAsync();
Console.WriteLine($"Status: {(int)resp.StatusCode}");
Console.WriteLine(body);
}
}Imports System
Imports System.Net.Http
Imports System.Text
Imports System.Text.Json
Imports System.Threading.Tasks
Module Program
Private ReadOnly http As New HttpClient()
Async Function Main() As Task
Dim url = "https://facturae.irenesolutions.com:8050/Kivu/Taxes/Verifactu/Invoices/GetQrCode"
Dim payload = New With {
.ServiceKey = "your service key",
.InvoiceID = "FRTEST1734699642488",
.InvoiceDate = "2024-12-20T13:00:42.488Z",
.SellerID = "B12959755",
.CompanyName = "IRENE SOLUTIONS SL",
.TaxItems = {New With {.TaxBase = 11.99, .TaxAmount = 2.52}}
}
Dim json = JsonSerializer.Serialize(payload)
Dim content = New StringContent(json, Encoding.UTF8, "application/json")
Dim resp = Await http.PostAsync(url, content)
Dim body = Await resp.Content.ReadAsStringAsync()
Console.WriteLine($"Status: {CInt(resp.StatusCode)}")
Console.WriteLine(body)
End Function
End ModuleImports System
Imports System.Net.Http
Imports System.Text
Imports System.Text.Json
Imports System.Threading.Tasks
Module Program
Private ReadOnly http As New HttpClient()
Async Function Main() As Task
Dim url = "https://facturae.irenesolutions.com:8050/Kivu/Taxes/Verifactu/Invoices/Create"
Dim payload = New With {
.ServiceKey = "zfzxgzxgcxzgdsaaaaa",
.Status = "POST",
.InvoiceType = "F1",
.InvoiceID = "FRTEST1752504601220",
.InvoiceDate = DateTime.UtcNow.ToString("o"),
.SellerID = "B12959755",
.CompanyName = "IRENE SOLUTIONS SL",
.RelatedPartyID = "B44531218",
.RelatedPartyName = "WEFINZ SOLUTIONS SL",
.Text = "SERVICIOS INFORMATICOS",
.TaxItems = {New With {.TaxScheme = "01", .TaxType = "S1", .TaxRate = 21, .TaxBase = 11.99, .TaxAmount = 2.52}}
}
Dim json = JsonSerializer.Serialize(payload)
Dim content = New StringContent(json, Encoding.UTF8, "application/json")
Dim resp = Await http.PostAsync(url, content)
Dim body = Await resp.Content.ReadAsStringAsync()
Console.WriteLine($"Status: {CInt(resp.StatusCode)}")
Console.WriteLine(body)
End Function
End Module- Los endpoints de pruebas están disponibles en
https://facturae.irenesolutions.com:8050/Kivu/Taxes/Verifactu/. - Sustituir
ServiceKeypor la clave real que se obtiene al registrarse en el panel de la API. - Los ejemplos muestran únicamente llamadas básicas; el modelo de datos admite más campos según la casuística de la factura.
Private Sub ValidarNif()
Dim url As String
Dim body As String
Dim xmlhttp As Object
On Error GoTo ErrHandler
' URL del endpoint de VeriFactu (ejemplo)
url = "https://facturae.irenesolutions.com/verifactu/Taxes/Verifactu/Invoices/ValidateNIF"
' JSON de la petición (IMPORTANTE: sin secuencias "\n" dentro del JSON)
body = "{""ServiceKey"":""AQUI_TU_SERVICEKEY""," & _
"""RelatedPartyID"":""B44531218""," & _
"""RelatedPartyName"":""WEFINZ SOLUTIONS SL""}"
' Crear el objeto HTTP
Set xmlhttp = CreateObject("MSXML2.ServerXMLHTTP")
' Abrir la conexión (POST síncrono)
xmlhttp.Open "POST", url, False
' Cabeceras
xmlhttp.setRequestHeader "Content-Type", "application/json"
xmlhttp.setRequestHeader "Accept", "application/json"
' Enviar la petición
xmlhttp.send body
' Comprobar el resultado
If xmlhttp.Status = 200 Then
' Aquí puedes parsear el JSON de respuesta;
' para depuración mostramos directamente el texto
MsgBox xmlhttp.responseText
Else
MsgBox "Error al llamar al API. HTTP " & xmlhttp.Status & " - " & xmlhttp.statusText, _
vbExclamation, "Error VeriFactu"
End If
' Liberar recursos
Set xmlhttp = Nothing
Exit Sub
ErrHandler:
MsgBox "Error VB6: " & Err.Number & " - " & Err.Description, vbCritical, "Error"
End Sub
- No añadas "\n" dentro del string JSON. En VB6 esa secuencia se envía literalmente (barra + n), no como salto de línea.
- Si quieres partir el JSON en varias líneas por legibilidad, hazlo con concatenaciones de VB6 (& _) pero sin añadir caracteres extra dentro del JSON. Por ejemplo:
body = "{""ServiceKey"":""...""," & _
"""RelatedPartyID"":""...""," & _
"""RelatedPartyName"":""...""}"
- En un escenario más avanzado, convertir el cuerpo a UTF-8 usando ADODB.Stream antes de enviarlo.
En algunos entornos VB6/Windows antiguos, aunque el código funcione con caracteres simples, pueden aparecer problemas cuando el JSON contiene acentos, eñes u otros caracteres no ASCII.
Para asegurarnos de que el cuerpo se envía realmente en UTF-8, podemos usar ADODB.Stream para convertir el string a un array de bytes UTF-8 antes de llamar a xmlhttp.send.
Private Sub ValidarNifUtf8()
Dim url As String
Dim body As String
Dim xmlhttp As Object
Dim stm As Object ' ADODB.Stream
Dim bytes As Variant
On Error GoTo ErrHandler
url = "https://facturae.irenesolutions.com/verifactu/Taxes/Verifactu/Invoices/ValidateNIF"
' JSON con posibles caracteres especiales (ñ, tildes, etc.)
body = "{""ServiceKey"":""AQUI_TU_SERVICEKEY""," & _
"""RelatedPartyID"":""B44531218""," & _
"""RelatedPartyName"":""WEFINZ SOLUTIONS SL""}"
' Crear el objeto HTTP
Set xmlhttp = CreateObject("MSXML2.ServerXMLHTTP")
' Abrir la conexión (POST síncrono)
xmlhttp.Open "POST", url, False
' Indicamos explícitamente UTF-8
xmlhttp.setRequestHeader "Content-Type", "application/json; charset=utf-8"
xmlhttp.setRequestHeader "Accept", "application/json"
' Convertir el string a bytes UTF-8 con ADODB.Stream
Set stm = CreateObject("ADODB.Stream")
stm.Type = 2 ' adTypeText
stm.Charset = "utf-8"
stm.Open
stm.WriteText body
stm.Position = 0
stm.Type = 1 ' adTypeBinary
bytes = stm.Read ' bytes UTF-8 del JSON
' Enviar los bytes UTF-8 al servidor
xmlhttp.send bytes
If xmlhttp.Status = 200 Then
MsgBox xmlhttp.responseText, vbInformation, "Respuesta VeriFactu"
Else
MsgBox "Error HTTP " & xmlhttp.Status & " - " & xmlhttp.statusText, _
vbExclamation, "Error VeriFactu"
End If
stm.Close
Set stm = Nothing
Set xmlhttp = Nothing
Exit Sub
ErrHandler:
MsgBox "Error VB6: " & Err.Number & " - " & Err.Description, vbCritical, "Error"
End Sub