0% encontró este documento útil (0 votos)
322 vistas21 páginas

API Online

Este documento describe una API REST para emitir documentos electrónicos como facturas y boletas a través de una nube. Explica los recursos necesarios como la URL y token de autenticación, y proporciona detalles sobre cómo construir y enviar documentos en formato JSON, incluyendo los campos requeridos y sus significados. También especifica los tipos de documentos que se deben probar antes de pasar el sistema a producción.

Cargado por

TaTianaCruz
Derechos de autor
© © All Rights Reserved
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como DOCX, PDF, TXT o lee en línea desde Scribd
0% encontró este documento útil (0 votos)
322 vistas21 páginas

API Online

Este documento describe una API REST para emitir documentos electrónicos como facturas y boletas a través de una nube. Explica los recursos necesarios como la URL y token de autenticación, y proporciona detalles sobre cómo construir y enviar documentos en formato JSON, incluyendo los campos requeridos y sus significados. También especifica los tipos de documentos que se deben probar antes de pasar el sistema a producción.

Cargado por

TaTianaCruz
Derechos de autor
© © All Rights Reserved
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como DOCX, PDF, TXT o lee en línea desde Scribd
Está en la página 1/ 21

API REST

NUBEFACT ONLINE
FECHA VERSIN DE ESTE DOCUMENTO DETALLE

05/05/2016 1.00 EXPLICACIN DEL ARCHIVO JSON

30/08/2016 1.01 RESPUESTA DE XML, PDF Y CDR ZIPEADO EN BASE64

06/09/2016 1.02 DATOS DE LA REPRESENTACIN IMPRESA

16/11/2016 1.03 ASIGNAR EL NMERO CORRELATIVO AL DOCUMENTO

6/12/2016 1.04 MEJORAS EN LAS ANULACIONES O COMUNICACIONES DE BAJA

RECURSOS:
Para poder usar nuestra API para ONLINE necesitas una URL y un TOKEN.
URL: La puedes conseguir ingresando a tu cuenta en www.nubefact.com desde la opcin API.
EJEMPLO: https://www.nubefact.com/api/v1/48239908-7ae7-4353-824d-071765d4
TOKEN: La puedes generar ingresando a tu cuenta en www.nubefact.com desde la opcin API.
EJEMPLO: 1c4239064a3f441880d7ced75eea4383b831c0bf26944169b1a0abe0a1d1c180
Para hacer PRUEBAS de esta API RECOMENDAMOS usar:
INSOMNIA: Un probador de API gratuito https://insomnia.rest/
POSTMAN: Una aplicacin para CHROME https://www.getpostman.com/
JSON: Usamos JSON para recibir y entregarte la informacin por ser un formato de texto ligero para el intercambio de datos.

AUTENTICACIN POST VIA Authorization Token:


Ir a https://www.nubefact.com/api_tokens desde donde debes generar un cdigo TOKEN de autorizacin.
IMPORTANTE:
Conctate a la URL usando el TOKEN
Todas las solicitudes se hacen va POST.
Debes enviar en el HEADER la siguiente informacin:
Authorization Token token="8d19d8c7c1f6402687720eab85cd57a54f5a7a3fa163476bbcf381ee2b5e0c69"
Content-Type application/json

ARCHIVO .JSON PARA FACTURAS, BOLETAS,


NOTAS DE CRDITO Y DBITO:
IMPORTANTE:
Se espera que durante la integracin se realicen las siguiente tareas:
Para construir el archivo JSON se debe tener en cuenta las especificaciones indicadas en http://json.org
Determinar los tipos de operaciones para elaborar el JSON de acuerdo a cada tipo
Operaciones Gravadas
Operaciones Exoneradas
Operaciones Inafectas
Operaciones de Exportacin
Operaciones Gratuitas
El archivo debe ser construido de tal forma que:
Sea construido en codificacin UTF-8.
No tenga caracteres especiales escondidos en una codificacin distinta a UTF-8 o espacios innecesarios.
Que no tenga comillas dobles () en los atributos, en la descripcin, denominacin, direccin, ETC, ejemplo: clavos 3 pulgadas
(esto interrumpe la estructura del json), se deben usar un escape, como por ejemplo: clavos 3\ pulgadas
La suma de cada lnea del comprobante debe coincidir con los totales.
La impresin sigue estando a cargo de su sistema actual. Puede elaborar una representacin impresa en cualquier tamao o usar
nuestra representacin impresa que entregaremos en pdf en nuestras respuestas.

Antes de pasar el sistema a produccin, solicitaremos que se generen desde su sistema los siguientes documentos va API:
1 Factura Electrnica en Soles
1 Factura Electrnica en Dlares
1 Factura Electrnica para operaciones Exoneradas o Inafectas
1 Factura Electrnica para Exportacin
1 Nota de Crdito Electrnica modificando o anulando una Factura Electrnica
1 Nota de Dbito Electrnica modificando o modificando una Factura Electrnica
1 Factura Electrnica combinada con operaciones Gravadas, Inafectas o Exoneradas
1 Consulta de Estado en la Sunat de la Factura Electrnica
1 Boleta de Venta Electrnica en Soles
1 Boleta de Venta Electrnica en Dlares
1 Boleta de Venta Electrnica para operaciones Exoneradas o Inafectas
1 Boleta de Venta Electrnica para Exportacin
1 Boleta de Venta Electrnica combinada con operaciones Gravadas, Inafectas o Exoneradas
1 Nota de Crdito Electrnica modificando o anulando una Boleta de Venta Electrnica
1 Nota de Dbito Electrnica modificando o modificando una Boleta de Venta Electrnica
1 Consulta de Estado en la Sunat de la Boleta de Venta Electrnica
1 Comunicacin de Baja de Factura Electrnica
1 Comunicacin de Baja de Boleta de Venta Electrnica
1 Consulta de Estado de Comunicacin de Baja

Se debe construir y enviarnos un archivo JSON siguiendo la siguiente estructura:

{
"type": "send_invoice",
"invoice": {
"tipo": "1",
"serie": "F001",
"numero": "1",
"entidad_numero_de_documento": "20600695771",
"entidad_tipo_de_documento": "6",
"entidad_denominacion": "NUBEFACT SA",
"entidad_direccion": "CALLE LIBERTAD 116 MIRAFLORES - LIMA - PERU",
"entidad_email": "[email protected]",
"fecha_de_emision": "05-06-2016",
"fecha_de_vencimiento": "",
"moneda": "1",
"tipo_de_cambio": "",
"operacion_gratuita": "false",
"total_gravada": "1000",
"total_inafecta": "",
"total_exonerada": "",
"total_igv": "180",
"total_gratuita": "",
"descuento_global": "",
"total_otros_cargos": "10",
"total": "1190",
"detraccion": "false",
"observaciones": "",
"documento_que_se_modifica_tipo": "",
"documento_que_se_modifica_serie": "",
"documento_que_se_modifica_numero": "",
"tipo_de_nota_de_credito": "",
"tipo_de_nota_de_debito": "",
"enviar_automaticamente_a_la_sunat": "true",
"enviar_automaticamente_al_cliente": "false",
"cancelado": "true",
"codigo_unico": "1-F001-1",
"invoice_lines": [
{
"unit_code": "ZZ",
"cantidad": "2",
"tipo_de_igv": "1",
"valor_unitario": "250",
"precio_unitario": "295",
"subtotal": "500",
"igv": "90",
"total": "590",
"descripcion": "MENU DE DIA"
},
{
"unit_code": "ZZ",
"cantidad": "2",
"tipo_de_igv": "1",
"valor_unitario": "250",
"precio_unitario": "295",
"subtotal": "500",
"igv": "90",
"total": "590",
"descripcion": "MENU DE DIA"
}
]
}
}

EXPLICACIN:
ESTE VALOR SIEMPRE DEBER SER "send_invoice" PARA ENVIAR
"type"
FACTURAS, BOLETAS Y NOTAS DE CRDITO Y DBITO

1 = "FACTURA"
2 = "BOLETA"
"tipo"
3 = "NOTA DE CRDITO"
4 = "NOTA DE DBITO"

EMPIEZA CON "F" PARA FACTURAS Y "B" PARA BOLETAS, SOLO DE 4


"serie"
DGITOS

NMERO CORRELATIVO DEL DOCUMENTO, HASTA 8 CARACTERES, SIN


numero
CEROS A LA IZQUIERDA

"entidad_numero_de_documento" RUC CLIENTE O NMERO DE DNI

6 = "RUC - REGISTRO NICO DE CONTRIBUYENTE"


1 = "DNI - DOC. NACIONAL DE IDENTIDAD"
- = "VARIOS - VENTAS MENORES A S/.700.00 Y OTROS"
"entidad_tipo_de_documento" 4 = "CARNET DE EXTRANJERA"
7 = "PASAPORTE"
A = "CDULA DIPLOMTICA DE IDENTIDAD"
0 = "NO DOMICILIADO, SIN RUC (EXPORTACIN)"

"entidad_denominacion" RAZN SOCIAL O NOMBRE COMPLETO

"entidad_direccion" DIRECCIN COMPLETA (OPCIONAL EN BOLETAS)

"entidad_email" OPCIONAL (SI DESEA ENVIAR UN EMAIL AL CLIENTE)

"fecha_de_emision" DIA-MES-AO (SEPARADO CON GUIONES)

"fecha_de_vencimiento" DIA-MES-AO (SEPARADO CON GUIONES)

1 = SOLES
"moneda"
2 = DLARES

"tipo_de_cambio" OBLIGATORIO SI ES EN DLARES

"operacion_gratuita" "true" o "false" (MINSCULA CON COMILLAS)

"total_gravada" CON 2 DECIMALES, SIN COMAS EN LOS MILES, EJEMPLO (1000.12)

"total_inafecta" CON 2 DECIMALES, SIN COMAS EN LOS MILES, EJEMPLO (1000.12)

"total_exonerada" CON 2 DECIMALES, SIN COMAS EN LOS MILES, EJEMPLO (1000.12)

"total_igv" CON 2 DECIMALES, SIN COMAS EN LOS MILES, EJEMPLO (1000.12)

"total_gratuita" CON 2 DECIMALES, SIN COMAS EN LOS MILES, EJEMPLO (1000.12)

"descuento_global" CON 2 DECIMALES, SIN COMAS EN LOS MILES, EJEMPLO (1000.12)

CON 2 DECIMALES, SIN COMAS EN LOS MILES, EJEMPLO (1000.12)


"total_otros_cargos"
(EJEMPLO EN RESTAURANTE ES LA PROPINA)

"total" CON 2 DECIMALES, SIN COMAS EN LOS MILES, EJEMPLO (1000.12)


"detraccion" CON 2 DECIMALES, SIN COMAS EN LOS MILES, EJEMPLO (1000.12)

"observaciones" OPCIONAL

1 = FACTURAS ELECTRNICAS
"documento_que_se_modifica_tipo"
2 = BOLETAS DE VENTA ELECTRNICAS

"documento_que_se_modifica_serie" SERIE de la FACTURA o BOLETA que se modifica (previamente comunicado)

NMERO de la FACTURA o BOLETA que se modifica (previamente


"documento_que_se_modifica_numero"
comunicado)

1 = ANULACIN DE LA OPERACIN
2 = ANULACIN POR ERROR EN EL RUC
3 = CORRECCIN POR ERROR EN LA DESCRIPCIN
4 = DESCUENTO GLOBAL
"tipo_de_nota_de_credito" 5 = DESCUENTO POR TEM
6 = DEVOLUCIN TOTAL
7 = DEVOLUCIN POR TEM
8 = BONIFICACIN
9 = DISMINUCIN EN EL VALOR

1 = INTERESES POR MORA


"tipo_de_nota_de_debito" 2 = AUMENTO DE VALOR
3 = PENALIDADES

"enviar_automaticamente_a_la_sunat" "true" o "false" (MINSCULA CON COMILLAS)

"enviar_automaticamente_al_cliente" "true" o "false" (MINSCULA CON COMILLAS)

"true" o "false" (MINSCULA CON COMILLAS). SI EL COMPROBANTE FUE


"cancelado"
COBRADO

CDIGO NICO GENERADO Y ASIGNADO POR TU SISTEMA. PUEDE


"codigo_unico" ESTAR COMPUESTO POR EL TIPO DE DOCUMENTO, SERIE Y NUMERO
CORRELATIVO.

"invoice_lines": [
{
"unit_code": "ZZ",
AQU VAN LAS LNEAS DEL DOCUMENTO
"cantidad": "2",
"unit_code" = NIU PARA PRODUCTO, ZZ PARA SERVICIO
"tipo_de_igv": "1",
"tipo_de_igv" = TIPO DE IGV, considerar la siguiente tabla:
"valor_unitario": "250",
1 = "Gravado - Operacin Onerosa"
"precio_unitario": "295",
2 = "Gravado Retiro por premio"
"subtotal": "500",
3 = "Gravado Retiro por donacin"
"igv": "90",
4 = "Gravado Retiro"
"total": "590",
5 = "Gravado Retiro por publicidad"
"descripcion": "MENU DE DIA"
6 = "Gravado Bonificaciones"
},
7 = "Gravado Retiro por entrega a trabajadores"
{
8 = "Exonerado - Operacin Onerosa"
"unit_code": "ZZ",
9 = "Inafecto - Operacin Onerosa"
"cantidad": "2",
10 = "Inafecto Retiro por Bonificacin"
"tipo_de_igv": "1",
11 = "Inafecto Retiro"
"valor_unitario": "250",
12 = "Inafecto Retiro por Muestras Mdicas"
"precio_unitario": "295",
13 = "Inafecto - Retiro por Convenio Colectivo"
"subtotal": "500",
14 = "Inafecto Retiro por premio"
"igv": "90",
15 = "Inafecto - Retiro por publicidad"
"total": "590",
16 = "Exportacin"
"descripcion": "MENU DE DIA"
}
]

RESPUESTA DE NUBEFACT ONLINE PARA


FACTURAS, BOLETAS, NOTAS DE CRDITO Y
DBITO
Recibirs una respuesta con la siguiente estructura:

{
"invoice": {
"serie": "F001",
"numero": 7,
"key": "bddaef88-ea1b-4c0f-9961-a0f71ded59e0-527894c2-16a4-495f-88ea-23ca4e52bc88",
"aceptada_por_sunat": true,
"sunat_description": "La Factura numero F001-7, ha sido aceptada",
"sunat_note": null,
"sunat_responsecode": "0",
"sunat_soap_error": "",
"digest_value": "nu/xRVCY0me66s93KNQNx1QJ1ZU=",
"codigo_de_barras": "20219719443 | 01 | F001 | 000007 | 180.00 | 1,190.00 | 05/05/2016 | 6 | 20547551398 |
UNv/nKSCy08PFSwAR02wZvqXVcs= |
nGEDbsDZsXnrWjf//kpu2BnGeK+DmKZjoSGnCW3na1lki7pktxfDVe8ihxm9\ncrhNi5EPFmdTLcbxcc+W+lCpDj9h8LeIz5MlhdPPEmpZUfLDa
Bhytf/fruZg\nadQi0WvCjHqW3Z7CRgbJh7t40Wvz9FbPfZhs121baF+fwYwYQpY43lzJR+MR\nMmMeoSVB6kL9TFilUF1EoZ4NTBeFX2hEF9
QVkPwqcvcznXIFMmhdG7pvX/p+\nryAYCDbMq4kcmiyqP0xgqL6wHjLiURq1eQa6JssMPm4a1Fag83xSmt62YjYL\ncwvHyG0Asu40jXPOA2
2kYyFLbGsI94/9ExSKZsPK2w== |",
"xml_zip_base64": "DmKZjoSGnCW3na1lki7pktxfDVe8ihxm9...=",
"pdf_zip_base64": "kpu2BnGeK...=",
"cdr_zip_base64": "nGEDbsDZsXnrWjf...="
}
}

EXPLICACIN
"serie" SERIE DEL DOCUMENTO

"numero" NMERO DEL DOCUMENTO (ASIGNADO POR NUBEFACT)

LLAVE NICA O CDIGO NICO DEL DOCUMENTO


ELECTRNICO asignado por NUBEFACT. Puedes construir un
"key" LINK para ver la factura en PDF con este cdigo.
Slo debes reemplazar el KEY en el siguiente link:
https://www.nubefact.com/see_invoice/KEY.pdf

"aceptada_por_sunat" "true" o "false"

"sunat_description" CUANDO HAY ERRORES LA SUNAT DESCRIBIR EL ERROR

"sunat_note" CUANDO HAY ERRORES LA SUNAT DESCRIBIR EL ERROR

"sunat_responsecode" CUANDO HAY ERRORES LA SUNAT DESCRIBIR EL ERROR

"sunat_soap_error" OTROS ERRORES QUE IMPOSIBILITAN EL ENVO

"digest_value" CDIGO HASH PARA LA REPRESENTACIN IMPRESA.

PUEDE USAR ESTE VALOR PARA GENERAR UN CDIGO DE


BARRAS EN PDF417, VISITE EL SIGUIENTE LINK:
"codigo_de_barras"
http://generator.onbarcode.com/online-pdf417-barcode-
generator.aspx

CONTENIDO DEL ARCHIVO XML ZIPEADO EN BASE64 QUE


"xml_zip_base64" PUEDES ALMACENAR DE SER NECESARIO. (Se debe activar
esta opcin desde Configuracin principal en NUBEFACT)

CONTENIDO DEL ARCHIVO PDF ZIPEADO EN BASE64 QUE


"pdf_zip_base64" PUEDES ALMACENAR DE SER NECESARIO. (Se debe activar
esta opcin desde Configuracin principal en NUBEFACT)

CONTENIDO DEL ARCHIVO CDR de SUNAT ZIPEADO EN


BASE64 QUE PUEDES ALMACENAR DE SER NECESARIO. (Se
"cdr_zip_base64"
debe activar esta opcin desde Configuracin principal en
NUBEFACT)

CONSULTAR ESTADO DE FACTURAS Y BOLETAS Y


NOTAS DE CRDITO Y DBITO
Puedes consultar el estado de cada documento electrnico siguiendo la siguiente estructura:

OPCIN 1:
{
"type": "status_invoice",
"invoice": {
"tipo": "1",
"serie": "F001",
"numero": "1"
}
}

OPCIN 2:
{
"type": "status_invoice",
"invoice": {
"key": "cfb7bcda-6cb7-4c0e-81db-173821b7a05e-fe015ff7-c12c-4764-8e30-fc50cb79aaf2"
}
}

EXPLICACIN
OPCIN 1:
"type" ESTE VALOR SIEMPRE DEBER SER = "status_invoice"

1 = "FACTURA"
2 = "BOLETA"
"tipo"
3 = "NOTA DE CRDITO"
4 = "NOTA DE DBITO"

"serie" SERIE DEL DOCUMENTO

numero NMERO DEL DOCUMENTO

LLAVE NICA O CDIGO NICO DEL DOCUMENTO ELECTRNICO


"key"
asignado por NUBEFACT.

OPCIN 2:
"type" ESTE VALOR SIEMPRE DEBER SER = "status_invoice"

LLAVE NICA O CDIGO NICO DEL DOCUMENTO ELECTRNICO


"key"
asignado por NUBEFACT.

Visita la siguiente direccin para ver ejemplos: https://www.nubefact.com/integracion

ARCHIVO .JSON PARA COMUNICACIONES DE BAJA


(ANULACIN DE DOCUMENTOS)
Las Facturas Electrnicas pueden ser anuladas solamente dentro de los 6 das de haber sido emitidos.
Las Boletas de Ventas Electrnicas pueden ser anuladas solamente dentro de los 3 das de haber sido emitidos.
Se debe tener conexin a internet en el momento en que se anula o comunica de baja un documento.

Se debe construir el JSON de envo siguiendo la siguiente estructura:

{
"type": "send_voided_document",
"voided_document": {
"codigo_unico": "ANULADO-ID000001",
"documento_tipo": "1",
"documento_serie": "F001",
"documento_numero": "1",
"motivo": "ERROR DEL SISTEMA"
}
}

EXPLICACIN
"type" ESTE VALOR SIEMPRE DEBER SER = "send_voided_document"

CDIGO NICO GENERADO Y ASIGNADO POR TU SISTEMA. PUEDE


"codigo_unico" ESTAR COMPUESTO POR EL TIPO DE DOCUMENTO, SERIE Y NUMERO
CORRELATIVO.

1 = FACTURAS ELECTRNICAS (previamente comunicado)


"documento_tipo"
2 = BOLETAS DE VENTA ELECTRNICAS (previamente comunicado)

"documento_serie" SERIE de la FACTURA o BOLETA que se modifica (previamente comunicado)

NMERO de la FACTURA o BOLETA que se modifica (previamente


"documento_numero"
comunicado)

"motivo" MOTIVO DE ANULACIN, EJEMPLO: "ERROR DE SISTEMA"

RESPUESTA DE NUBEFACT.COM PARA


COMUNICACIONES DE BAJA (ANULACIN DE
DOCUMENTOS)
{
"voided_document": {
"numero": 1,
"key": "cfb7bcda-6cb7-4c0e-81db-173821b7a05e-fe015ff7-c12c-4764-8e30-fc50cb79aaf2",
"sunat_ticket_numero": "201600340677910",
"aceptada_por_sunat": true,
"sunat_description": "La Comunicacion de baja numero RA-20160504-1, ha sido aceptada",
"sunat_note": null,
"sunat_responsecode": "0",
"sunat_soap_error": "",
"xml_zip_base64": "DmKZjoSGnCW3na1lki7pktxfDVe8ihxm9...=",
"pdf_zip_base64": "kpu2BnGeK...=",
"cdr_zip_base64": "nGEDbsDZsXnrWjf...=",
"error_nubefact": ""
}
}

EXPLICACIN
"numero" NMERO DEL DOCUMENTO (ASIGNADO POR NUBEFACT)

LLAVE NICA O CDIGO NICO DEL DOCUMENTO


"key"
ELECTRNICO asignado por NUBEFACT.

"sunat_ticket_numero" NMERO DE TICKET ASIGNADO POR LA SUNAT

"aceptada_por_sunat" "true" o "false"

"sunat_description" CUANDO HAY ERRORES LA SUNAT DESCRIBIR EL ERROR

"sunat_note" CUANDO HAY ERRORES LA SUNAT DESCRIBIR EL ERROR

"sunat_responsecode" CUANDO HAY ERRORES LA SUNAT DESCRIBIR EL ERROR

"sunat_soap_error" OTROS ERRORES QUE IMPOSIBILITAN EL ENVO

"xml_zip_base64" CONTENIDO DEL ARCHIVO XML ZIPEADO EN BASE64 QUE


PUEDES ALMACENAR DE SER NECESARIO. (Se debe activar
esta opcin desde Configuracin principal en NUBEFACT)

CONTENIDO DEL ARCHIVO PDF ZIPEADO EN BASE64 QUE


"pdf_zip_base64" PUEDES ALMACENAR DE SER NECESARIO. (Se debe activar
esta opcin desde Configuracin principal en NUBEFACT)

CONTENIDO DEL ARCHIVO CDR de SUNAT ZIPEADO EN


BASE64 QUE PUEDES ALMACENAR DE SER NECESARIO. (Se
"cdr_zip_base64"
debe activar esta opcin desde Configuracin principal en
NUBEFACT)

CONSULTAR ESTADO DE COMUNICACIONES DE


BAJA (ANULACIN DE DOCUMENTOS)
Puedes consultar el estado de cada documento electrnico siguiendo la siguiente estructura:
OPCIN 1 (RECOMENDADO)
{
"type": "status_voided_document",
"voided_document": {
"documento_tipo": "1",
"documento_serie": "F001",
"documento_numero": "1"
}
}

OPCIN 2
{
"type": "status_voided_document",
"voided_document": {
"key": "cfb7bcda-6cb7-4c0e-81db-173821b7a05e-fe015ff7-c12c-4764-8e30-fc50cb79aaf2"
}
}

EXPLICACIN
OPCIN 1 (RECOMENDADO)
"type" ESTE VALOR SIEMPRE DEBER SER = "status_voided_document"

1 = "FACTURA"
"documento_tipo"
2 = "BOLETA"

"documento_serie" SERIE DEL DOCUMENTO

"documento_numero" NMERO DEL DOCUMENTO

OPCIN 2
"type" ESTE VALOR SIEMPRE DEBER SER = "status_voided_document"

LLAVE NICA O CDIGO NICO DEL DOCUMENTO ELECTRNICO


"key"
asignado por NUBEFACT.

REPRESENTACIN IMPRESA
Caractersticas que deben estar presentes si se genera la representacin impresa:

FORMATO FACTURA:
FORMATO TICKET:

EJEMPLOS PARA INVOCAR NUESTRO SERVICIO CON JSON


Los siguientes cdigos se proporcionan como ejemplo, es posible que deba buscar ms informacin y encontrar el modo correcto en el
lenguaje de programacin que est usando.

PHP

No necesitas ninguna librera adicional, solo usa el siguiente cdigo:


<?php
//URL para enviar documentos
$url = "https://www.nubefact.com/api/v1/25264c6c-d023-44e5-93f6-f842021625f9";

//TOKEN para enviar documentos


$token = "1c4239064a3f441880d7ced75eea4383b831c0bf26944169b1a0abe0a1d1c180";

//Constructor de archivo JSON


$data = array(
'type'=>'send_invoice',
'invoice'=> array(
"tipo"=> "1",
"serie"=> "F001",
"numero"=> "1",
"entidad_numero_de_documento"=> "20600695771",
"entidad_tipo_de_documento"=> "6",
"entidad_denominacion"=> "NUBEFACT SA",
"entidad_direccion"=> "CALLE LIBERTAD 116 MIRAFLORES - LIMA - PERU",
"entidad_email"=> "[email protected]",
"fecha_de_emision"=> "28-09-2016",
"fecha_de_vencimiento"=> "",
"moneda"=> "1",
"tipo_de_cambio"=> "",
"operacion_gratuita"=> "false",
"total_gravada"=> "1000",
"total_inafecta"=> "",
"total_exonerada"=> "",
"total_igv"=> "180",
"total_gratuita"=> "",
"descuento_global"=> "",
"total_otros_cargos"=> "10",
"total"=> "1190",
"detraccion"=> "false",
"observaciones"=> "",
"documento_que_se_modifica_tipo"=> "",
"documento_que_se_modifica_serie"=> "",
"documento_que_se_modifica_numero"=> "",
"tipo_de_nota_de_credito"=> "",
"tipo_de_nota_de_debito"=> "",
"enviar_automaticamente_a_la_sunat"=> "false",
"enviar_automaticamente_al_cliente"=> "false",
"cancelado"=> "true",
"codigo_unico"=> "1-F001-1",
"invoice_lines"=> array( array(
"unit_code"=> "ZZ",
"cantidad"=> "1",
"tipo_de_igv"=> "1",
"valor_unitario"=> "500",
"precio_unitario"=> "590",
"subtotal"=> "500",
"igv"=> "90",
"total"=> "590",
"descripcion"=> "INKA KOLA DE 1.5 LITROS"
),
array(
"unit_code"=> "ZZ",
"cantidad"=> "1",
"tipo_de_igv"=> "1",
"valor_unitario"=> "500",
"precio_unitario"=> "590",
"subtotal"=> "500",
"igv"=> "90",
"total"=> "590",
"descripcion"=> "INKA KOLA DE 1.5 LITROS"
)
)
)
);
$data_json = json_encode($data);

//Invocamos el servicio de NUBEFACT


$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt(
$ch, CURLOPT_HTTPHEADER, array(
'Authorization: Token token="'.$token.'"',
'Content-Type: application/json',
)
);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$respuesta = curl_exec($ch);
curl_close($ch);

//Leemos la respuesta de NUBEFACT y la guardamos en nuestra base de datos


$leer_respuesta = json_decode($respuesta, true);
if (isset($leer_respuesta['errors'])) {
//Mostramos los errores si los hay
echo $leer_respuesta['errors'];
} else {
//Mostramos la respuesta
echo $leer_respuesta['invoice']['serie'];
echo $leer_respuesta['invoice']['numero'];
echo $leer_respuesta['invoice']['key'];
echo $leer_respuesta['invoice']['aceptada_por_sunat'];
echo $leer_respuesta['invoice']['sunat_description'];
echo $leer_respuesta['invoice']['sunat_note'];
echo $leer_respuesta['invoice']['sunat_responsecode'];
echo $leer_respuesta['invoice']['sunat_soap_error'];
echo $leer_respuesta['invoice']['digest_value'];
echo $leer_respuesta['invoice']['codigo_de_barras'];
echo $leer_respuesta['invoice']['xml_zip_base64'];
echo $leer_respuesta['invoice']['pdf_zip_base64'];
echo $leer_respuesta['invoice']['cdr_zip_base64'];
}
?>

CURL

curl -X POST -H "Authorization: Token token=\"1c4239064a3f441880d7ced75eea4383b831c0bf26944169b1a0abe0a1d1c180\"" -H


"Content-Type: application/json" -H "Cache-Control: no-cache" -H "Postman-Token: a2cd5225-ed69-1ed7-6f4e-28a66bd8d2b6" -d
'AQUI_VA_EL_CONTENIDO_EN_JSON' "https://www.nubefact.com/api/v1/25264c6c-d023-44e5-93f6-f842021625f9"

C#
Debes usar la siguiente librera: http://www.newtonsoft.com/json
Tambin puedes usar esta utilera para construir clases para el Json: http://jsonutils.com/

/// USAR LO SIGUIENTE


using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Windows.Forms;
using Newtonsoft.Json;

/// CREAMOS LAS CLASES PARA CONSTRUIR EL JSON Y LEER LA RESPUESTA EN JSON
public class Root
{
public string type { get; set; }
public Invoice invoice { get; set; }
}
public class Invoice
{
public string tipo { get; set; }
public string serie { get; set; }
public string numero { get; set; }
public string entidad_numero_de_documento { get; set; }
public string entidad_tipo_de_documento { get; set; }
public string entidad_denominacion { get; set; }
public string entidad_direccion { get; set; }
public string entidad_email { get; set; }
public string fecha_de_emision { get; set; }
public string fecha_de_vencimiento { get; set; }
public string moneda { get; set; }
public string tipo_de_cambio { get; set; }
public string operacion_gratuita { get; set; }
public string total_gravada { get; set; }
public string total_inafecta { get; set; }
public string total_exonerada { get; set; }
public string total_igv { get; set; }
public string total_gratuita { get; set; }
public string descuento_global { get; set; }
public string total_otros_cargos { get; set; }
public string total { get; set; }
public string detraccion { get; set; }
public string observaciones { get; set; }
public string documento_que_se_modifica_tipo { get; set; }
public string documento_que_se_modifica_serie { get; set; }
public string documento_que_se_modifica_numero { get; set; }
public string tipo_de_nota_de_credito { get; set; }
public string tipo_de_nota_de_debito { get; set; }
public string enviar_automaticamente_a_la_sunat { get; set; }
public string enviar_automaticamente_al_cliente { get; set; }
public string cancelado { get; set; }
public string codigo_unico { get; set; }
public List<InvoiceLine> invoice_lines { get; set; }
}
public class InvoiceLine
{
public string unit_code { get; set; }
public string cantidad { get; set; }
public string tipo_de_igv { get; set; }
public string valor_unitario { get; set; }
public string precio_unitario { get; set; }
public string subtotal { get; set; }
public string igv { get; set; }
public string total { get; set; }
public string descripcion { get; set; }
}

public class Respuesta


{
public string errors { get; set; }
public RespuestaInvoice invoice { get; set; }
}
public class RespuestaInvoice
{
public string serie { get; set; }
public int numero { get; set; }
public string key { get; set; }
public bool aceptada_por_sunat { get; set; }
public string sunat_description { get; set; }
public object sunat_note { get; set; }
public string sunat_responsecode { get; set; }
public string sunat_soap_error { get; set; }
public string digest_value { get; set; }
public string codigo_de_barras { get; set; }
public string xml_zip_base64 { get; set; }
public string pdf_zip_base64 { get; set; }
public string cdr_zip_base64 { get; set; }
}

/// CONSTRUIMOS EL JSON


Root root = new Root();
root.type = "send_invoice";
Invoice invoice = new Invoice();
invoice.tipo = "1";
invoice.serie = "F001";
invoice.numero = "1";
invoice.entidad_numero_de_documento = "20600695771";
invoice.entidad_tipo_de_documento = "6";
invoice.entidad_denominacion = "NUBEFACT SA";
invoice.entidad_direccion = "CALLE LIBERTAD 116 MIRAFLORES - LIMA - PERU";
invoice.entidad_email = "[email protected]";
invoice.fecha_de_emision = "11-10-2016";
invoice.fecha_de_vencimiento = "";
invoice.moneda = "1";
invoice.tipo_de_cambio = "";
invoice.operacion_gratuita = "false";
invoice.total_gravada = "1000";
invoice.total_inafecta = "";
invoice.total_exonerada = "";
invoice.total_igv = "180";
invoice.total_gratuita = "";
invoice.descuento_global = "";
invoice.total_otros_cargos = "10";
invoice.total = "1190";
invoice.detraccion = "false";
invoice.observaciones = "";
invoice.documento_que_se_modifica_tipo = "";
invoice.documento_que_se_modifica_serie = "";
invoice.documento_que_se_modifica_numero = "";
invoice.tipo_de_nota_de_credito = "";
invoice.tipo_de_nota_de_debito = "";
invoice.enviar_automaticamente_a_la_sunat = "true";
invoice.enviar_automaticamente_al_cliente = "false";
invoice.cancelado = "true";
invoice.codigo_unico = "1-F001-1";
List<InvoiceLine> invoice_lines = new List<InvoiceLine>()
{
new InvoiceLine() {
unit_code = "ZZ",
cantidad = "1",
tipo_de_igv = "1",
valor_unitario = "500",
precio_unitario = "590",
subtotal = "500",
igv = "90",
total = "590",
descripcion = "INKA KOLA DE 1.5 LITROS"
},
new InvoiceLine() {
unit_code = "ZZ",
cantidad = "1",
tipo_de_igv = "1",
valor_unitario = "500",
precio_unitario = "590",
subtotal = "500",
igv = "90",
total = "590",
descripcion = "INKA KOLA DE 1.5 LITROS"
},
};
invoice.invoice_lines = invoice_lines;
root.invoice = invoice;
string json = JsonConvert.SerializeObject(root);
/// INVOCAMOS EL SERVICIO DE LA API DE NUBEFACT
string url = "https://www.nubefact.com/api/v1/25264c6c-d023-44e5-93f6-f842021625f9";
string token = "1c4239064a3f441880d7ced75eea4383b831c0bf26944169b1a0abe0a1d1c180";
/// CODIFICAMOS EL JSON EN UTF-8
byte[] bytes = Encoding.Default.GetBytes(json);
string json_en_utf_8 = Encoding.UTF8.GetString(bytes);
string json_de_respuesta = SendJson(url, json_en_utf_8, token);
/// LEEMOS LA RESPUESTA
dynamic leer_respuesta = JsonConvert.DeserializeObject<Respuesta>(json_de_respuesta);
if ((leer_respuesta.errors == null))
{
MessageBox.Show("SERIE: " + leer_respuesta.invoice.serie);
MessageBox.Show("NUMERO: " + leer_respuesta.invoice.numero);
MessageBox.Show("KEY: " + leer_respuesta.invoice.key);
MessageBox.Show("ACEPTADA_POR_SUNAT: " + leer_respuesta.invoice.aceptada_por_sunat);
MessageBox.Show("DIGEST_VALUE: " + leer_respuesta.invoice.digest_value);
MessageBox.Show("CODIGO_DE_BARRAS: " + leer_respuesta.invoice.codigo_de_barras);
}
else
{
MessageBox.Show("ERRORES: " + leer_respuesta.errors);
}

/// CONSTRUIMOS LA FUNCION PARA CONECTARNOS VA POST


private string SendJson(string url, string json, string token)
{
try
{
using (var client = new WebClient())
{
client.Headers[HttpRequestHeader.ContentType] = "application/json";
client.Headers[HttpRequestHeader.Authorization] = "Token token=" + token;
string respuesta = client.UploadString(url, "POST", json);
return respuesta;
}
}
catch (WebException ex)
{
var respuesta = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
return respuesta;
}
}

VB.NET

Debes usar la siguiente librera: http://www.newtonsoft.com/json


Tambin puedes usar esta utilera para construir clases para el Json: http://jsonutils.com/
' USAR LO SIGUIENTE
Imports System.IO
Imports System.Net
Imports System.Text
Imports Newtonsoft.Json

' CREAMOS LAS CLASES PARA CONSTRUIR EL JSON Y LEER LA RESPUESTA EN JSON
Public Class Root
Public Property type As String
Public Property invoice As Invoice
End Class

Public Class Invoice


Public Property tipo As String
Public Property serie As String
Public Property numero As String
Public Property entidad_numero_de_documento As String
Public Property entidad_tipo_de_documento As String
Public Property entidad_denominacion As String
Public Property entidad_direccion As String
Public Property entidad_email As String
Public Property fecha_de_emision As String
Public Property fecha_de_vencimiento As String
Public Property moneda As String
Public Property tipo_de_cambio As String
Public Property operacion_gratuita As String
Public Property total_gravada As String
Public Property total_inafecta As String
Public Property total_exonerada As String
Public Property total_igv As String
Public Property total_gratuita As String
Public Property descuento_global As String
Public Property total_otros_cargos As String
Public Property total As String
Public Property detraccion As String
Public Property observaciones As String
Public Property documento_que_se_modifica_tipo As String
Public Property documento_que_se_modifica_serie As String
Public Property documento_que_se_modifica_numero As String
Public Property tipo_de_nota_de_credito As String
Public Property tipo_de_nota_de_debito As String
Public Property enviar_automaticamente_a_la_sunat As String
Public Property enviar_automaticamente_al_cliente As String
Public Property cancelado As String
Public Property codigo_unico As String
Public Property invoice_lines As List(Of InvoiceLine)
End Class

Public Class InvoiceLine


Public Property unit_code As String
Public Property cantidad As String
Public Property tipo_de_igv As String
Public Property valor_unitario As String
Public Property precio_unitario As String
Public Property subtotal As String
Public Property igv As String
Public Property total As String
Public Property descripcion As String
End Class

Public Class Respuesta


Public Property errors As String
Public Property invoice As RespuestaInvoice
End Class

Public Class RespuestaInvoice


Public Property serie As String
Public Property numero As Integer
Public Property key As String
Public Property aceptada_por_sunat As Boolean
Public Property sunat_description As String
Public Property sunat_note As Object
Public Property sunat_responsecode As String
Public Property sunat_soap_error As String
Public Property digest_value As String
Public Property codigo_de_barras As String
Public Property xml_zip_base64 As String
Public Property pdf_zip_base64 As String
Public Property cdr_zip_base64 As String
End Class

' CONSTRUIMOS EL JSON


Dim root As New Root()
root.type = "send_invoice"
Dim invoice As New Invoice()
invoice.tipo = "1"
invoice.serie = "F001"
invoice.numero = "1"
invoice.entidad_numero_de_documento = "20600695771"
invoice.entidad_tipo_de_documento = "6"
invoice.entidad_denominacion = "NUBEFACT SA"
invoice.entidad_direccion = "CALLE LIBERTAD 116 MIRAFLORES - LIMA - PERU"
invoice.entidad_email = "[email protected]"
invoice.fecha_de_emision = "11-10-2016"
invoice.fecha_de_vencimiento = ""
invoice.moneda = "1"
invoice.tipo_de_cambio = ""
invoice.operacion_gratuita = "false"
invoice.total_gravada = "1000"
invoice.total_inafecta = ""
invoice.total_exonerada = ""
invoice.total_igv = "180"
invoice.total_gratuita = ""
invoice.descuento_global = ""
invoice.total_otros_cargos = "10"
invoice.total = "1190"
invoice.detraccion = "false"
invoice.observaciones = ""
invoice.documento_que_se_modifica_tipo = ""
invoice.documento_que_se_modifica_serie = ""
invoice.documento_que_se_modifica_numero = ""
invoice.tipo_de_nota_de_credito = ""
invoice.tipo_de_nota_de_debito = ""
invoice.enviar_automaticamente_a_la_sunat = "true"
invoice.enviar_automaticamente_al_cliente = "false"
invoice.cancelado = "true"
invoice.codigo_unico = "1-F001-1"
Dim invoice_lines As New List(Of InvoiceLine)
invoice_lines.Add(New InvoiceLine() With {
.unit_code = "ZZ",
.cantidad = "1",
.tipo_de_igv = "1",
.valor_unitario = "500",
.precio_unitario = "590",
.subtotal = "500",
.igv = "90",
.total = "590",
.descripcion = "INKA KOLA DE 1.5 LITROS"
})
invoice_lines.Add(New InvoiceLine() With {
.unit_code = "ZZ",
.cantidad = "1",
.tipo_de_igv = "1",
.valor_unitario = "500",
.precio_unitario = "590",
.subtotal = "500",
.igv = "90",
.total = "590",
.descripcion = "INKA KOLA DE 1.5 LITROS"
})
invoice.invoice_lines = invoice_lines
root.invoice = invoice
Dim json_para_envio = JsonConvert.SerializeObject(root)
MsgBox(json_para_envio)
' INVOCAMOS EL SERVICIO DE LA API DE NUBEFACT
Dim uri = "https://www.nubefact.com/api/v1/25264c6c-d023-44e5-93f6-f842021625f9"
Dim data = Encoding.UTF8.GetBytes(json_para_envio)
Dim token = "1c4239064a3f441880d7ced75eea4383b831c0bf26944169b1a0abe0a1d1c180"
Dim json_de_respuesta = SendJson(uri, data, token)
' LEEMOS LA RESPUESTA
Dim leer_respuesta = JsonConvert.DeserializeObject(Of Respuesta)(json_de_respuesta)
If IsNothing(leer_respuesta.errors) Then
MsgBox("SERIE: " & leer_respuesta.invoice.serie)
MsgBox("NUMERO: " & leer_respuesta.invoice.numero)
MsgBox("KEY: " & leer_respuesta.invoice.key)
MsgBox("ACEPTADA_POR_SUNAT: " & leer_respuesta.invoice.aceptada_por_sunat)
MsgBox("DIGEST_VALUE: " & leer_respuesta.invoice.digest_value)
MsgBox("CODIGO_DE_BARRAS: " & leer_respuesta.invoice.codigo_de_barras)
Else
MsgBox("ERRORES: " & leer_respuesta.errors)
End If

' CONSTRUIMOS LA FUNCION PARA CONECTARNOS VA POST


Private Function SendJson(uri As String, jsonDataBytes As Byte(), token As String) As String
Try
Dim req As WebRequest = WebRequest.Create(uri)
req.ContentType = "application/json"
req.Headers.Add(HttpRequestHeader.Authorization, "Token token=" & token)
req.Method = "POST"
req.ContentLength = jsonDataBytes.Length
Dim stream = req.GetRequestStream()
stream.Write(jsonDataBytes, 0, jsonDataBytes.Length)
stream.Close()
Dim response = req.GetResponse().GetResponseStream()
Dim reader As New StreamReader(response)
Dim respuesta = reader.ReadToEnd()
reader.Close()
response.Close()
Return respuesta
Catch Ex As WebException
Dim respuesta = New StreamReader(Ex.Response.GetResponseStream()).ReadToEnd()
Return respuesta
End Try
End Function

JAVA

package apirest;
public class ApiRest {
public static void main(String[] args) {
ConsumingPost cp = new ConsumingPost();
cp.apiConsume();
}
}

package apirest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class ConsumingPost {

private String URL = "https://www.nubefact.com/api/v1/25264c6c-d023-44e5-93f6-f842021625f9";


private String STR_TOKEN = "Token
token=\"1c4239064a3f441880d7ced75eea4383b831c0bf26944169b1a0abe0a1d1c180\"";

public void apiConsume(){


try {

HttpClient cliente = new DefaultHttpClient();


HttpPost post = new HttpPost(URL);
post.addHeader("Authorization",STR_TOKEN); // Cabecera del token
post.addHeader("Content-Type","application/json"); // Cabecera del Content-Type

JSONObject objetoPrincipal = new JSONObject(); // Instancear el JSONObject


objetoPrincipal.put("type","send_invoice"); // Agregar el objeto clave y valor

JSONObject objetoSecundario = new JSONObject(); // Instancear el segundario


objetoSecundario.put("tipo","1");
objetoSecundario.put("serie","F001");
objetoSecundario.put("numero","1");
objetoSecundario.put("entidad_numero_de_documento","20600695771");
objetoSecundario.put("entidad_tipo_de_documento","6");
objetoSecundario.put("entidad_denominacion","NUBEFACT SA");
objetoSecundario.put("entidad_direccion","CALLE LIBERTAD 116 MIRAFLORES - LIMA - PERU");
objetoSecundario.put("entidad_email","[email protected]");
objetoSecundario.put("fecha_de_emision","09-10-2016");
objetoSecundario.put("fecha_de_vencimiento","");
objetoSecundario.put("moneda","1");
objetoSecundario.put("tipo_de_cambio","");
objetoSecundario.put("operacion_gratuita","false");
objetoSecundario.put("total_gravada","1000");
objetoSecundario.put("total_inafecta","");
objetoSecundario.put("total_exonerada","");
objetoSecundario.put("total_igv","180");
objetoSecundario.put("total_gratuita","");
objetoSecundario.put("descuento_global","");
objetoSecundario.put("total_otros_cargos","10");

objetoSecundario.put("total","1190");
objetoSecundario.put("detraccion","false");
objetoSecundario.put("observaciones","");
objetoSecundario.put("documento_que_se_modifica_tipo","");
objetoSecundario.put("documento_que_se_modifica_serie","");
objetoSecundario.put("documento_que_se_modifica_numero","");
objetoSecundario.put("tipo_de_nota_de_credito","");
objetoSecundario.put("tipo_de_nota_de_debito","");
objetoSecundario.put("enviar_automaticamente_a_la_sunat","true");
objetoSecundario.put("enviar_automaticamente_al_cliente","true");

objetoSecundario.put("cancelado","true");
objetoSecundario.put("codigo_unico","FACTURA-ID00000010");
objetoPrincipal.put("invoice",objetoSecundario);

JSONArray lista = new JSONArray();


JSONObject detalle_linea_1 = new JSONObject();
detalle_linea_1.put("unit_code", "ZZ");
detalle_linea_1.put("cantidad", "1");
detalle_linea_1.put("tipo_de_igv", "1");
detalle_linea_1.put("valor_unitario", "500");
detalle_linea_1.put("precio_unitario", "590");
detalle_linea_1.put("subtotal", "500");
detalle_linea_1.put("igv", "90");
detalle_linea_1.put("total", "590");
detalle_linea_1.put("descripcion", "INKA KOLA DE 1.5 LITROS");

JSONObject detalle_linea_2 = new JSONObject();

detalle_linea_2.put("unit_code", "ZZ");
detalle_linea_2.put("cantidad", "1");
detalle_linea_2.put("tipo_de_igv", "1");
detalle_linea_2.put("valor_unitario", "500");
detalle_linea_2.put("precio_unitario", "590");
detalle_linea_2.put("subtotal", "500");
detalle_linea_2.put("igv", "90");
detalle_linea_2.put("total", "590");
detalle_linea_2.put("descripcion", "INKA KOLA DE 1.5 LITROSSSDSADSD");

lista.add(detalle_linea_1);
lista.add(detalle_linea_2);

objetoSecundario.put("invoice_lines", lista);

StringEntity parametros = new StringEntity(objetoPrincipal.toString());


post.setEntity(parametros);
HttpResponse response = cliente.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String linea = "";
if((linea = rd.readLine()) != null) {

JSONParser parsearRsptaJson = new JSONParser();


JSONObject json_rspta = (JSONObject) parsearRsptaJson.parse(linea);

if(json_rspta.get("errors") != null ){
System.out.println("Error => " + json_rspta.get("errors"));
}else{

JSONParser parsearRsptaDetalleOK = new JSONParser();


JSONObject json_rspta_ok = (JSONObject)
parsearRsptaDetalleOK.parse(json_rspta.get("invoice").toString());

System.out.println(json_rspta_ok.get("serie"));
System.out.println(json_rspta_ok.get("numero"));
System.out.println(json_rspta_ok.get("key"));
System.out.println(json_rspta_ok.get("aceptada_por_sunat"));
System.out.println(json_rspta_ok.get("sunat_description"));
System.out.println(json_rspta_ok.get("sunat_note"));
System.out.println(json_rspta_ok.get("sunat_responsecode"));
System.out.println(json_rspta_ok.get("sunat_soap_error"));
System.out.println(json_rspta_ok.get("digest_value"));
System.out.println(json_rspta_ok.get("codigo_de_barras"));
System.out.println(json_rspta_ok.get("xml_zip_base64"));
System.out.println(json_rspta_ok.get("pdf_zip_base64"));
System.out.println(json_rspta_ok.get("cdr_zip_base64"));
}
}
} catch (UnsupportedEncodingException ex1) {
System.err.println("Error UnsupportedEncodingException: "+ex1.getMessage());
} catch (IOException ex2) {
System.err.println("Error IOException: "+ex2.getMessage());
} catch (ParseException ex3) {
System.err.println("Error ParseException: "+ex3.getMessage());
} catch (Exception ex4){
System.err.println("Exepction: "+ex4.getMessage());
}
}
}
VISUAL BASIC 6

Debes las siguientes libreras a tu aplicacin:


https://github.com/VBA-tools/VBA-JSON
https://github.com/VBA-tools/VBA-Dictionary
Los siguientes archivos los puedes decargar en el siguiente link, debes agregar esos archivos a tu aplicacin:
https://drive.google.com/open?id=0B9aiKQ80nIRAeWYyN3JDaWFYZDA
El cdigo de ejemplo es:

' Aqu construimos el archivo JSON


Dim JsonEnvio As Object
Dim invoice_json As String
Dim tipo, serie As String

tipo = """1"""
serie = """F001"""
numero = """1"""
invoice_json = invoice_json & "{"
invoice_json = invoice_json & """type"": ""send_invoice"","
invoice_json = invoice_json & """invoice"": {"
invoice_json = invoice_json & """tipo"":" & tipo & ","
invoice_json = invoice_json & """serie"":" & serie & ","
invoice_json = invoice_json & """numero"":" & numero & ","
invoice_json = invoice_json & """entidad_numero_de_documento"": ""20600695771"","
invoice_json = invoice_json & """entidad_tipo_de_documento"": ""6"","
invoice_json = invoice_json & """entidad_denominacion"": ""NUBEFACT SA"","
invoice_json = invoice_json & """entidad_direccion"": ""CALLE LIBERTAD 116 MIRAFLORES - LIMA - PERU"","
invoice_json = invoice_json & """entidad_email"": ""[email protected]"","
invoice_json = invoice_json & """fecha_de_emision"": ""09-10-2016"","
invoice_json = invoice_json & """fecha_de_vencimiento"": """","
invoice_json = invoice_json & """moneda"": ""1"","
invoice_json = invoice_json & """tipo_de_cambio"": """","
invoice_json = invoice_json & """operacion_gratuita"": ""false"","
invoice_json = invoice_json & """total_gravada"": ""1000"","
invoice_json = invoice_json & """total_inafecta"": """","
invoice_json = invoice_json & """total_exonerada"": """","
invoice_json = invoice_json & """total_igv"": ""180"","
invoice_json = invoice_json & """total_gratuita"": """","
invoice_json = invoice_json & """descuento_global"": """","
invoice_json = invoice_json & """total_otros_cargos"": ""10"","
invoice_json = invoice_json & """total"": ""1190"","
invoice_json = invoice_json & """detraccion"": ""false"","
invoice_json = invoice_json & """observaciones"": """","
invoice_json = invoice_json & """documento_que_se_modifica_tipo"": """","
invoice_json = invoice_json & """documento_que_se_modifica_serie"": """","
invoice_json = invoice_json & """documento_que_se_modifica_numero"": """","
invoice_json = invoice_json & """tipo_de_nota_de_credito"": """","
invoice_json = invoice_json & """tipo_de_nota_de_debito"": """","
invoice_json = invoice_json & """enviar_automaticamente_a_la_sunat"": ""true"","
invoice_json = invoice_json & """enviar_automaticamente_al_cliente"": ""false"","
invoice_json = invoice_json & """cancelado"": ""true"","
invoice_json = invoice_json & """codigo_unico"": ""1-F001-1"","
invoice_json = invoice_json & """invoice_lines"": ["
invoice_json = invoice_json & "{"
invoice_json = invoice_json & """unit_code"": ""ZZ"","
invoice_json = invoice_json & """cantidad"": ""1"","
invoice_json = invoice_json & """tipo_de_igv"": ""1"","
invoice_json = invoice_json & """valor_unitario"": ""500"","
invoice_json = invoice_json & """precio_unitario"": ""590"","
invoice_json = invoice_json & """subtotal"": ""500"","
invoice_json = invoice_json & """igv"": ""90"","
invoice_json = invoice_json & """total"": ""590"","
invoice_json = invoice_json & """descripcion"": ""INKA KOLA DE 1.5 LITROS"""
invoice_json = invoice_json & "}," ' CUIDADO: Retirar la coma si es la ltima linea o item del documento
invoice_json = invoice_json & "{"
invoice_json = invoice_json & """unit_code"": ""ZZ"","
invoice_json = invoice_json & """cantidad"": ""1"","
invoice_json = invoice_json & """tipo_de_igv"": ""1"","
invoice_json = invoice_json & """valor_unitario"": ""500"","
invoice_json = invoice_json & """precio_unitario"": ""590"","
invoice_json = invoice_json & """subtotal"": ""500"","
invoice_json = invoice_json & """igv"": ""90"","
invoice_json = invoice_json & """total"": ""590"","
invoice_json = invoice_json & """descripcion"": ""INKA KOLA DE 1.5 LITROS"""
invoice_json = invoice_json & "}" ' CUIDADO: Retirar la coma si es la ltima linea o item del documento
invoice_json = invoice_json & "]"
invoice_json = invoice_json & "}"
invoice_json = invoice_json & "}"

Set JsonEnvio = JsonConverter.ParseJson(invoice_json)


MsgBox "Este es el archivo JSON que se enviar: " & JsonConverter.ConvertToJson(JsonEnvio)

' Aqu invocamos el servicio de NUBEFACT va http POST y enviamos el ARCHIVO JSON
Dim myMSXML
Set myMSXML = CreateObject("Microsoft.XmlHttp")
' Para algunas versiones de XMLHTTP, use:
' Set myMSXML = CreateObject("MSXML2.ServerXMLHTTP")
' Set myMSXML = CreateObject("MSXML2.XMLHTTP")
myMSXML.open "POST", "https://www.nubefact.com/api/v1/25264c6c-d023-44e5-93f6-f842021625f9", False
myMSXML.setRequestHeader "Content-Type", "application/json"
myMSXML.setRequestHeader "Authorization", "Token
token=1c4239064a3f441880d7ced75eea4383b831c0bf26944169b1a0abe0a1d1c180"
myMSXML.send JsonConverter.ConvertToJson(JsonEnvio)

' Aqu leemos las respuesta de NUBEFACT


Dim JsonRespuesta As String
Dim LeerJsonRespuesta As Dictionary
JsonRespuesta = myMSXML.responseText
Set LeerJsonRespuesta = JsonConverter.ParseJson(JsonRespuesta)
If LeerJsonRespuesta("errors") = "" Then
MsgBox "Serie: " & LeerJsonRespuesta("invoice")("serie")
MsgBox "Nmero: " & LeerJsonRespuesta("invoice")("numero")
MsgBox "Key: " & LeerJsonRespuesta("invoice")("key")
MsgBox "Aceptada por Sunat: " & LeerJsonRespuesta("invoice")("aceptada_por_sunat")
MsgBox "Cdigo Hash: " & LeerJsonRespuesta("invoice")("digest_value")
MsgBox "Cdigo de barras: " & LeerJsonRespuesta("invoice")("codigo_de_barras")
Else
MsgBox "Existen Errores: " & LeerJsonRespuesta("errors")
End If

End Sub

VISUAL FOX PRO

USAR LA SIGUIENTE LIBRERA: https://github.com/ronaldmacedo/vfpjson

* USAR LA SIGUIENTE LIBRERIA: https://github.com/ronaldmacedo/vfpjson

SET PROCEDURE TO json ADDITIVE

* CONSTRUIMOS EL JSON
TEXT TO json_para_envio NOSHOW
{
"type": "send_invoice",
"invoice": {
"tipo": "1",
"serie": "F001",
"numero": "1",
"entidad_numero_de_documento": "20600695771",
"entidad_tipo_de_documento": "6",
"entidad_denominacion": "NUBEFACT SA",
"entidad_direccion": "CALLE LIBERTAD 116 MIRAFLORES - LIMA - PERU",
"entidad_email": "[email protected]",
"fecha_de_emision": "12-10-2016",
"fecha_de_vencimiento": "",
"moneda": "1",
"tipo_de_cambio": "",
"operacion_gratuita": "false",
"total_gravada": "1000",
"total_inafecta": "",
"total_exonerada": "",
"total_igv": "180",
"total_gratuita": "",
"descuento_global": "",
"total_otros_cargos": "10",
"total": "1190",
"detraccion": "false",
"observaciones": "",
"documento_que_se_modifica_tipo": "",
"documento_que_se_modifica_serie": "",
"documento_que_se_modifica_numero": "",
"tipo_de_nota_de_credito": "",
"tipo_de_nota_de_debito": "",
"enviar_automaticamente_a_la_sunat": "true",
"enviar_automaticamente_al_cliente": "false",
"cancelado": "true",
"codigo_unico": "1-F001-1",
"invoice_lines": [
{
"unit_code": "ZZ",
"cantidad": "1",
"tipo_de_igv": "1",
"valor_unitario": "500",
"precio_unitario": "590",
"subtotal": "500",
"igv": "90",
"total": "590",
"descripcion": "INKA KOLA DE 1.5 LITROS"
},
{
"unit_code": "ZZ",
"cantidad": "1",
"tipo_de_igv": "1",
"valor_unitario": "500",
"precio_unitario": "590",
"subtotal": "500",
"igv": "90",
"total": "590",
"descripcion": "INKA KOLA DE 1.5 LITROS"
}
]
}
}
ENDTEXT
* INVOCAMOS EL SERVICIO DE NUBEFACT

web = "https://www.nubefact.com/api/v1/25264c6c-d023-44e5-93f6-f842021625f9"

post_connect = CreateObject("MSXML2.ServerXMLHTTP")
* Para algunas versiones de XMLHTTP, use:
* post_connect = CreateObject("Microsoft.XMLHTTP")
* post_connect = CreateObject("MSXML2.XMLHTTP")
post_connect.Open("POST", web, .F.)
post_connect.setRequestHeader("Content-Type", "application/json")
post_connect.setRequestHeader("Authorization", "Token
token=1c4239064a3f441880d7ced75eea4383b831c0bf26944169b1a0abe0a1d1c180")
post_connect.Send(json_para_envio)
json_respuesta = post_connect.responsetext

* LEEMOS LA RESPUESTA
leer_respuesta = json_decode(json_respuesta)
IF EMPTY(leer_respuesta.get('errors')) THEN
MESSAGEBOX(leer_respuesta._invoice.get('serie'))
MESSAGEBOX(leer_respuesta._invoice.get('numero'))
MESSAGEBOX(leer_respuesta._invoice.get('key'))
MESSAGEBOX(leer_respuesta._invoice.get('aceptada_por_sunat'))
MESSAGEBOX(leer_respuesta._invoice.get('digest_value'))
MESSAGEBOX(leer_respuesta._invoice.get('codigo_de_barras'))
ELSE
MESSAGEBOX(leer_respuesta.get('errors'))
ENDIF

También podría gustarte