diff --git a/src/assets/apis/autopay/en.yaml b/src/assets/apis/autopay/en.yaml index e245bab73..6a9d35da0 100644 --- a/src/assets/apis/autopay/en.yaml +++ b/src/assets/apis/autopay/en.yaml @@ -9,6 +9,13 @@ paths: summary: Get balance operationId: post-balance parameters: + - name: Authorization + in: header + required: true + description: "Basic Auth credentials. Ex: `Basic `" + schema: + type: string + example: "Basic YWFiYmNjZGQ..." - schema: type: string example: application/json;charset=UTF-8 @@ -46,7 +53,7 @@ paths: application/json: schema: type: object - required: [ auth, reference, id ] + required: [ reference, id ] properties: reference: type: string @@ -61,6 +68,13 @@ paths: summary: Settle an AutoPay operationId: post-settlement parameters: + - name: Authorization + in: header + required: true + description: "Basic Auth credentials. Ex: `Basic `" + schema: + type: string + example: "Basic YWFiYmNjZGQ..." - schema: type: string example: application/json;charset=UTF-8 @@ -976,6 +990,47 @@ components: $ref: '../checkout/en.yaml#/components/schemas/AutopayRequest' x-conditional: - id + buyer: + $ref: '../checkout/en.yaml#/components/schemas/Person' + description: | + Data of the **buyer** user, refers to the user who is purchasing a product or service. + + **When creating a session**: Can be sent if you know the user making the purchase, as it helps complete the session information. + If this data is sent, the user will have their personal data pre-filled and can change it in Checkout. + payer: + $ref: '../checkout/en.yaml#/components/schemas/Person' + description: | + Data of the **payer** user, refers to the owner of the payment method or user who paid the requested amount. + + **When creating a session**: Should only be used when you want to "force" the data of the user who will complete the process. + If this data is sent, the user will have their personal data pre-filled but **cannot change it**. + fields: + $ref: '../checkout/en.yaml#/components/schemas/Fields' + paymentMethod: + type: string + description: | + Used to restrict the payment methods available in checkout. + Multiple codes can be sent separated by commas. + See more at [Payment methods](/checkout/payment-methods) + + Ex: `visa,master,pse` + example: visa + cancelUrl: + type: string + description: | + Cancel URL, the user is redirected to this URL when they decide not to continue with the process. + Occurs when the user clicks on _I do not wish to continue_. + example: 'https://commerce.test/cancel' + skipResult: + type: boolean + description: | + If `true` is sent, when the user finishes the process the session result page will not be displayed, instead they will be redirected to the `returnUrl`. See more at [Skip result](/checkout/skip-result) + default: false + noBuyerFill: + type: boolean + description: | + By default, the data sent as `buyer` is pre-filled in the Checkout interface to speed up the payment process, if this parameter is sent as `true` then this pre-filling will not be done. + default: false ipAddress: $ref: '../checkout/en.yaml#/components/schemas/IpAddress' userAgent: diff --git a/src/assets/apis/autopay/es.yaml b/src/assets/apis/autopay/es.yaml index 6846b22e8..eaaace86b 100644 --- a/src/assets/apis/autopay/es.yaml +++ b/src/assets/apis/autopay/es.yaml @@ -8,6 +8,15 @@ paths: summary: Obtener balance operationId: post-balance parameters: + - name: Authorization + in: header + description: | + Credenciales Basic Auth codificadas en Base64. + Ejemplo: `Basic ` + required: true + schema: + type: string + example: "Basic YWFiYmNjZGQ..." - schema: type: string example: application/json;charset=UTF-8 @@ -45,7 +54,7 @@ paths: application/json: schema: type: object - required: [ auth, reference, id ] + required: [ reference, id ] properties: reference: type: string @@ -59,6 +68,15 @@ paths: summary: Asentar un AutoPago operationId: post-settlement parameters: + - name: Authorization + in: header + description: | + Credenciales Basic Auth codificadas en Base64. + Ejemplo: `Basic ` + required: true + schema: + type: string + example: "Basic YWFiYmNjZGQ..." - schema: type: string example: application/json;charset=UTF-8 @@ -966,6 +984,37 @@ components: $ref: '../checkout/es.yaml#/components/schemas/AutopayRequest' x-conditional: - id + buyer: + $ref: '../checkout/es.yaml#/components/schemas/Person' + description: | + Datos del usuario **buyer**, se refiere al usuario que está comprando un producto o servicio. + payer: + $ref: '../checkout/es.yaml#/components/schemas/Person' + description: | + Datos del usuario **payer**, se refiere al dueño del medio de pago o usuario que pagó el monto solicitado. + fields: + $ref: '../checkout/es.yaml#/components/schemas/Fields' + paymentMethod: + type: string + description: | + Se usa para restringir los medios de pago disponibles en el checkout. + Se pueden enviar múltiples códigos separados por comas. + example: visa + cancelUrl: + type: string + description: | + URL de cancelación, el usuario es redirigido a esta url cuando decide no continuar con el proceso. + example: 'https://commerce.test/cancel' + skipResult: + type: boolean + description: | + Si se envía `true`, cuando el usuario finalice el proceso no se mostrará la página de resultado de la sesión, en su lugar será redirigido a la `returnUrl`. + default: false + noBuyerFill: + type: boolean + description: | + Por defecto, los datos enviados como `buyer` son pre-llenados en la interfaz de Checkout para agilizar el proceso de pago, si este parámetro se envía como `true` entonces no se realizará este pre-llenado. + default: false ipAddress: $ref: '../checkout/es.yaml#/components/schemas/IpAddress' userAgent: diff --git a/src/components/ApiReader.jsx b/src/components/ApiReader.jsx index 880c6b376..1918daebf 100644 --- a/src/components/ApiReader.jsx +++ b/src/components/ApiReader.jsx @@ -16,6 +16,10 @@ const TITLES = { es: 'Respuesta', en: 'Response', }, + body: { + es: 'Cuerpo', + en: 'Body', + }, params: { es: { params: 'Parámetros', @@ -384,9 +388,11 @@ export const ApiParams = ({ params = [], type = 'params' }) => { ) } -export const ApiRequest = ({ request = {} }) => { +export const ApiRequest = ({ request = {}, params = [] }) => { const { locale } = useLocale() - const [selected, setSelected] = useState(0); + const [selected, setSelected] = useState(0) + + const headers = params ? params.filter((p) => p.in === 'header') : [] const requestBody = request?.content?.['application/json'] ?? @@ -400,7 +406,7 @@ export const ApiRequest = ({ request = {} }) => { body = multiBodies[selected] } - if (!body?.properties) { + if (!body?.properties && headers.length === 0) { return null } @@ -421,19 +427,33 @@ export const ApiRequest = ({ request = {} }) => { )} - {body.deprecated && ( - {TITLES.deprecated[locale]} - )} - - {body.description && ( - {body.description} - )} + {headers.length > 0 && ( +
+ +
+ )} - + {body && ( + <> + {headers.length > 0 && ( +

{TITLES.body[locale]}

+ )} + + {body.deprecated && ( + {TITLES.deprecated[locale]} + )} + + {body.description && ( + {body.description} + )} + + + + )} ) } @@ -449,7 +469,7 @@ export function ApiReader({ path, method = '', api = {}, type = 'request' }) { } if (type === 'request') { - return + return } if (type === 'response') { diff --git a/src/components/AutoPayDocsList.jsx b/src/components/AutoPayDocsList.jsx new file mode 100644 index 000000000..f977f7eba --- /dev/null +++ b/src/components/AutoPayDocsList.jsx @@ -0,0 +1,77 @@ +import { ItemList } from '@/components/ItemsList' +import { useLocalizePath } from '@/hooks/useLocalizePath' +import { useLocale } from './LocaleProvider' + +const guides = [ + { + href: '/autopay', + action: { es: 'Ver más', en: 'Learn more' }, + name: { + es: 'Inicio', + en: 'Home', + }, + description: { + es: 'Conoce AutoPay, sus beneficios y obtén una visión general de su integración.', + en: 'Discover AutoPay, its benefits, and a high-level overview of the integration.', + }, + }, + { + href: '/autopay/authentication', + action: { es: 'Ver más', en: 'Learn more' }, + name: { + es: 'Integración', + en: 'Integration', + }, + description: { + es: 'Conoce las capacidades, conceptos y flujos clave de AutoPay para lograr una integración exitosa.', + en: 'Learn about AutoPay capabilities, concepts, and key workflows for a successful integration.', + }, + }, + { + href: '/autopay/api/', + action: { es: 'Ver más', en: 'Learn more' }, + name: { + es: 'API', + en: 'API', + }, + description: { + es: 'Consulta en detalle los métodos HTTP disponibles, los parámetros y las posibles respuestas de cada servicio.', + en: 'Explore available HTTP methods, parameters, and possible responses for each service in detail.', + }, + }, + { + href: '/autopay/contracts/', + action: { es: 'Ver más', en: 'Learn more' }, + name: { + es: 'Contratos', + en: 'Contracts', + }, + description: { + es: 'Implementa los endpoints necesarios en tu servidor para gestionar balances, confirmaciones de pago y notificaciones.', + en: 'Implement the required endpoints on your server to handle balances, payment confirmations, and notifications.', + }, + }, +] + +export function AutoPayDocsList() { + const { locale } = useLocale() + const localizePath = useLocalizePath() + + return ( +
+
+ {guides + .map((guide) => ({ + ...guide, + href: localizePath(guide.href), + name: guide.name[locale], + description: guide.description[locale], + action: guide.action[locale], + })) + .map((guide) => ( + + ))} +
+
+ ) +} diff --git a/src/components/AutoPayRequirements.jsx b/src/components/AutoPayRequirements.jsx new file mode 100644 index 000000000..8a9b16e20 --- /dev/null +++ b/src/components/AutoPayRequirements.jsx @@ -0,0 +1,44 @@ +import { ItemList } from '@/components/ItemsList' +import { useLocale } from './LocaleProvider' +import { Scroll, UserOctagon } from 'iconsax-react' + +const guides = [ + { + name: { es: 'Cuenta de Placetopay', en: 'Placetopay account' }, + icon: () => , + description: { + es: 'Debes tener una cuenta activa en PlacetoPay para acceder a tu sitio y tus credenciales API.', + en: 'You must have an active account in PlacetoPay to access your site and your API credentials.', + }, + }, + { + name: { + es: 'Conocimientos básicos en programación', + en: 'Basic programming knowledge', + }, + icon: () => , + description: { + es: 'Se recomienda tener conocimientos de desarrollo web y programación, ya que esta documentación se enfoca en la integración de la API de AutoPay con tu aplicación.', + en: 'Web development and programming knowledge is recommended, as this documentation focuses on integrating the AutoPay API into your application.', + }, + }, +] + +export function AutoPayRequirements() { + const { locale } = useLocale() + return ( +
+
+ {guides + .map((guide) => ({ + ...guide, + name: guide.name[locale], + description: guide.description[locale], + })) + .map((guide) => ( + + ))} +
+
+ ) +} diff --git a/src/components/AutopayBenefits.jsx b/src/components/AutopayBenefits.jsx new file mode 100644 index 000000000..57aeb554e --- /dev/null +++ b/src/components/AutopayBenefits.jsx @@ -0,0 +1,115 @@ +import { useLocale } from './LocaleProvider' +import { ResourceCard } from './ResourceCard' +import { ChartSquare, CpuSetting, Setting5, SecuritySafe, DirectboxReceive, NotificationStatus } from 'iconsax-react' + +const resources = [ + { + name: { + es: 'Conversión y retención', + en: 'Conversion and retention', + }, + description: { + es: 'Reduce fricción en pagos repetitivos (servicios, seguros, suscripciones, etc).', + en: 'Reduce friction in repetitive payments (services, insurance, subscriptions, etc).', + }, + icon: () => , + pattern: { + y: 16, + squares: [ + [0, 1], + [1, 3], + ], + }, + }, + { + name: { + es: 'Automatización operativa', + en: 'Operational automation', + }, + description: { + es: 'Elimina procesos manuales y recordatorios; los cobros se ejecutan en las fechas definidas.', + en: 'Eliminate manual processes and reminders; charges are executed on defined dates.', + }, + icon: () => , + pattern: { + y: -6, + squares: [ + [-1, 2], + [1, 3], + ], + }, + }, + { + name: { + es: 'Control y transparencia', + en: 'Control and transparency', + }, + description: { + es: 'El comercio puede revisar, ajustar o cancelar sus autopagos.', + en: 'The merchant can review, adjust, or cancel their autopayments.', + }, + icon: () => , + pattern: { + y: 32, + squares: [ + [0, 2], + [1, 4], + ], + }, + }, + { + name: { es: 'Seguridad y cumplimiento', en: 'Security and compliance' }, + description: { + es: 'Uso de medios tokenizados y lineamientos PCI, con opciones de autenticación (p. ej., 3DS 3RI si aplica).', + en: 'Use of tokenized methods and PCI guidelines, with authentication options (e.g., 3DS 3RI if applicable).', + }, + icon: () => , + pattern: { + y: 22, + squares: [[0, 1]], + }, + }, + { + name: { es: 'Integrabilidad', en: 'Integrability' }, + description: { + es: 'Además de la integración directa de checkout, el ecosistema expone endpoints para creación, actualización, desactivación y consulta de autopagos.', + en: 'In addition to direct checkout integration, the ecosystem exposes endpoints for creating, updating, deactivating, and querying autopayments.', + }, + icon: () => , + pattern: { + y: 22, + squares: [[0, 1]], + }, + }, + { + name: { es: 'Webhooks', en: 'Webhooks' }, + description: { + es: 'Se soportan webhooks para la notificación de eventos relevantes.', + en: 'Webhooks are supported for notification of relevant events.', + }, + icon: () => , + pattern: { + y: 22, + squares: [[0, 1]], + }, + }, +] + +export function AutopayBenefits() { + const { locale } = useLocale() + return ( +
+
+ {resources.map((resource, index) => ( + + ))} +
+
+ ) +} \ No newline at end of file diff --git a/src/components/DocsList.jsx b/src/components/DocsList.jsx index 9fb85c4d5..ff16912ff 100644 --- a/src/components/DocsList.jsx +++ b/src/components/DocsList.jsx @@ -28,7 +28,7 @@ const guides = [ }, }, { - href: '/checkout/api-reference/session', + href: '/checkout/api/reference/session', action: { es: 'Ver más', en: 'Learn more' }, name: { es: 'API', diff --git a/src/components/react-flow/SequenceDiagram/Diagrams/AutoPay/en/AutoPaySequence.jsx b/src/components/react-flow/SequenceDiagram/Diagrams/AutoPay/en/AutoPaySequence.jsx new file mode 100644 index 000000000..8b493d9ea --- /dev/null +++ b/src/components/react-flow/SequenceDiagram/Diagrams/AutoPay/en/AutoPaySequence.jsx @@ -0,0 +1,111 @@ +import SequenceDiagram from "@/components/react-flow/SequenceDiagram/SequenceDiagram" +import SequenceActor from "@/components/react-flow/SequenceDiagram/SequenceActor" +import SequenceAction from "@/components/react-flow/SequenceDiagram/SequenceAction" +import Line from "@/components/react-flow/SequenceDiagram/Line" + +export default function AutoPaySequence() { + return ( + + + + + + + + + + + + + + + + + + + + + + + + ) +} \ No newline at end of file diff --git a/src/components/react-flow/SequenceDiagram/Diagrams/AutoPay/en/RecurringSequence.jsx b/src/components/react-flow/SequenceDiagram/Diagrams/AutoPay/en/RecurringSequence.jsx new file mode 100644 index 000000000..458286f31 --- /dev/null +++ b/src/components/react-flow/SequenceDiagram/Diagrams/AutoPay/en/RecurringSequence.jsx @@ -0,0 +1,79 @@ +import SequenceDiagram from "@/components/react-flow/SequenceDiagram/SequenceDiagram" +import SequenceActor from "@/components/react-flow/SequenceDiagram/SequenceActor" +import SequenceAction from "@/components/react-flow/SequenceDiagram/SequenceAction" +import Line from "@/components/react-flow/SequenceDiagram/Line" + +export default function RecurringSequence() { + return ( + + {/* Actors: The Engine and the Data */} + + + + {/* Step 1: Trigger */} + + + + + {/* Step 2: Math Calculation */} + + + {/* Step 3: Validation */} + + + + + {/* Result A: Valid Date */} + + + {/* Result B: Expired (Optional visually to avoid clutter) */} + + + ) +} \ No newline at end of file diff --git a/src/components/react-flow/SequenceDiagram/Diagrams/AutoPay/es/AutoPaySequence.jsx b/src/components/react-flow/SequenceDiagram/Diagrams/AutoPay/es/AutoPaySequence.jsx new file mode 100644 index 000000000..6bea1c1de --- /dev/null +++ b/src/components/react-flow/SequenceDiagram/Diagrams/AutoPay/es/AutoPaySequence.jsx @@ -0,0 +1,111 @@ +import SequenceDiagram from "@/components/react-flow/SequenceDiagram/SequenceDiagram" +import SequenceActor from "@/components/react-flow/SequenceDiagram/SequenceActor" +import SequenceAction from "@/components/react-flow/SequenceDiagram/SequenceAction" +import Line from "@/components/react-flow/SequenceDiagram/Line" + +export default function AutoPaySequence() { + return ( + + + + + + + + + + + + + + + + + + + + + + + + ) +} \ No newline at end of file diff --git a/src/components/react-flow/SequenceDiagram/Diagrams/AutoPay/es/RecurringSequence.jsx b/src/components/react-flow/SequenceDiagram/Diagrams/AutoPay/es/RecurringSequence.jsx new file mode 100644 index 000000000..f4dfade4b --- /dev/null +++ b/src/components/react-flow/SequenceDiagram/Diagrams/AutoPay/es/RecurringSequence.jsx @@ -0,0 +1,79 @@ +import SequenceDiagram from "@/components/react-flow/SequenceDiagram/SequenceDiagram" +import SequenceActor from "@/components/react-flow/SequenceDiagram/SequenceActor" +import SequenceAction from "@/components/react-flow/SequenceDiagram/SequenceAction" +import Line from "@/components/react-flow/SequenceDiagram/Line" + +export default function RecurringSequence() { + return ( + + {/* Actores: El Motor y la Data */} + + + + {/* Paso 1: Trigger */} + + + + + {/* Paso 2: Cálculo Matemático */} + + + {/* Paso 3: Validación */} + + + + + {/* Resultado A: Fecha Válida */} + + + {/* Resultado B: Vencido (Opcional visualmente para no saturar, o se puede agregar otra línea) */} + + + ) +} \ No newline at end of file diff --git a/src/constants/navigations.js b/src/constants/navigations.js index 71577839c..44292a9b2 100644 --- a/src/constants/navigations.js +++ b/src/constants/navigations.js @@ -2228,13 +2228,20 @@ export const TAB_NAVIGATION = { icon: Book, links: [ { - title: '', + title: 'Autopay', links: [ { title: 'Introducción', href: '/autopay' }, - { title: 'Autenticación', href: '/autopay/authentication' }, - { title: 'Códigos de respuesta', href: '/autopay/codes' }, - { title: 'Cargos en AutoPay', href: '/autopay/charge-types'}, + { title: 'Cómo funciona', href: '/autopay/how-autopay-works' }, + ], + }, + { + title: 'Integración', + links: [ + { title: 'Autenticación API', href: '/autopay/authentication' }, { title: 'Autenticación de contratos', href: '/autopay/contract-authentication' }, + { title: 'Configuración de recurrencia', href: '/autopay/recurring-setup' }, + { title: 'Códigos de respuesta', href: '/autopay/codes' }, + { title: 'Tipos de Cobro', href: '/autopay/charge-types'}, ], }, ], @@ -2254,7 +2261,7 @@ export const TAB_NAVIGATION = { { title: 'API', links: [ - { title: 'Crear sesión o actualizar un AutoPago', href: '/autopay/api/session' }, + { title: 'Crear o actualizar sesión de AutoPago', href: '/autopay/api/session' }, { title: 'Cancelar AutoPago', href: '/autopay/api/cancel' }, { title: 'Consulta de AutoPagos', href: '/autopay/api/search' }, { title: 'Transacciones de AutoPago', href: '/autopay/api/transactions' }, @@ -2278,7 +2285,7 @@ export const TAB_NAVIGATION = { title: 'Servicios', links: [ { title: 'Consultar monto a cobrar', href: '/autopay/contracts/balance' }, - { title: 'Asentamiento', href: '/autopay/contracts/settlement' }, + { title: 'Confirmar / Asentar pago', href: '/autopay/contracts/settlement' }, { title: 'Notificaciones (Webhook)', href: '/autopay/contracts/webhook' }, ], }, @@ -2293,15 +2300,22 @@ export const TAB_NAVIGATION = { icon: Book, links: [ { - title: '', + title: 'Autopay', links: [ { title: 'Introduction', href: '/autopay' }, - { title: 'Authentication', href: '/autopay/authentication' }, - { title: 'Response Codes', href: '/autopay/codes' }, - { title: 'AutoPay Charges', href: '/autopay/charge-types' }, - { title: 'Contract Authentication', href: '/autopay/contract-authentication' }, + { title: 'How it works', href: '/autopay/how-autopay-works' }, ], }, + { + title: 'Integration', + links: [ + { title: 'API Authentication', href: '/autopay/authentication' }, + { title: 'Contract Authentication', href: '/autopay/contract-authentication' }, + { title: 'Recurring setup', href: '/autopay/recurring-setup' }, + { title: 'Response codes', href: '/autopay/codes' }, + { title: 'Charge Types', href: '/autopay/charge-types' }, + ], + } ], }, { @@ -2342,8 +2356,8 @@ export const TAB_NAVIGATION = { { title: 'Services', links: [ - { title: 'Get Charge Amount', href: '/autopay/contracts/balance' }, - { title: 'Settlement', href: '/autopay/contracts/settlement' }, + { title: 'Query amount to charge', href: '/autopay/contracts/balance' }, + { title: 'Settle / Confirm Payment', href: '/autopay/contracts/settlement' }, { title: 'Notifications (Webhook)', href: '/autopay/contracts/webhook' }, ], }, diff --git a/src/pages/autopay/api/index.mdx b/src/pages/autopay/api/index.mdx index 99465366a..db0a15fff 100644 --- a/src/pages/autopay/api/index.mdx +++ b/src/pages/autopay/api/index.mdx @@ -2,8 +2,57 @@ import { HeroPattern } from '@/components/HeroPattern' -## API para integrarse con AutoPay +# Referencia API AutoPay -Para operar AutoPay de extremo a extremo, el AutoPay expone una serie de endpoints para que el cliente/comercio pueda interactuar con ellos y realizar acciones sobre los autopagos de sus usuarios, como la generación, consulta actualización y desactivación de los mismos. +Bienvenido a la referencia técnica de AutoPay. Nuestra API está construida bajo principios RESTful, utiliza **JSON** para el intercambio de datos y códigos de respuesta HTTP estándar. -En este apartado, podrás obtener más información acerca de las APIS y ejemplos de cada uno de los servicios. +## Entornos y base URL + +Todas las solicitudes deben enviarse a las siguientes URL base, dependiendo del entorno en el que te encuentres: + +| Entorno | Base URL | Descripción | +| :--- | :--- | :--- | +| **Sandbox** | `https://api-test.placetopay.com` | Utilizado para desarrollo y pruebas. No procesa dinero real. | +| **Producción** | `https://api.placetopay.com` | Entorno transaccional real. | + +## Cabeceras (headers) + +Todas las peticiones a la API deben incluir las siguientes cabeceras HTTP para asegurar que el contenido se interprete correctamente: + +```json + Content-Type: application/json + Accept: application/json + User-Agent: TuApp/1.0 (Recomendado para identificar tu tráfico) +``` + +## Estructura de respuesta estándar + +Independientemente del endpoint, todas las respuestas de la API siguen una estructura común. Siempre recibirás un objeto `status` que te indicará el resultado técnico de la operación. + +```json + { + "status": { + "status": "OK", + "reason": "00", + "message": "La petición se ha procesado correctamente", + "date": "2023-06-21T09:56:06-05:00" + }, + ..., + } +``` + +* **`status`**: Indica el éxito (`OK`) o fallo (`FAILED`) de la solicitud técnica. +* **`reason`**: Código interno para manejo de errores programático. +* **`message`**: Descripción legible del resultado. +* **`*`** : Contiene la información solicitada (ej. detalles de la sesión, lista de transacciones). + +--- + +## Servicios disponibles + +Explora los endpoints disponibles para gestionar el ciclo de vida de autopagos: + +* [**Sesiones**](/autopay/api/session): El punto de entrada. Permite crear un nuevo autopago o editar uno existente. +* [**Búsqueda**](/autopay/api/search): Consulta el estado y detalles de tus autopagos. +* [**Transacciones**](/autopay/api/transactions): Obtén el historial de cobros realizados sobre un autopago específico. +* [**Cancelación**](/autopay/api/cancel): Detén un autopago para evitar futuros cobros. diff --git a/src/pages/autopay/api/session.mdx b/src/pages/autopay/api/session.mdx index 8264c1f86..53ecf932b 100644 --- a/src/pages/autopay/api/session.mdx +++ b/src/pages/autopay/api/session.mdx @@ -5,7 +5,7 @@ import { HeroPattern } from '@/components/HeroPattern' export const apiRefs = ['/autopay/session','/autopay/session/{requestId}'] -## Crear o actualizar sessión de AutoPago {{ id: 'session-autopay', tag: 'POST', label: '/autopay/session' }} +## Crear o actualizar sesión de AutoPago {{ id: 'session-autopay', tag: 'POST', label: '/autopay/session' }} El flujo de creación y actualización de un autopago comienza con esta solicitud que genera una sessión. Este proceso permite configurar pagos programados y/o recurrentes de forma automatizada, proporcionando enlace para dirigirse a la interfaz gráfica para que el tarjeta habiente autorice el inicio o actualización del autopago y seleccione el medio de pago. @@ -394,5 +394,3 @@ curl -X "POST" https://test.placetopay.com/autopay/session/000000 \ - ---- \ No newline at end of file diff --git a/src/pages/autopay/api/transactions.mdx b/src/pages/autopay/api/transactions.mdx index ae4452c79..10441571b 100644 --- a/src/pages/autopay/api/transactions.mdx +++ b/src/pages/autopay/api/transactions.mdx @@ -69,7 +69,7 @@ Este servicio permite listar las transacciones de un AutoPago y filtrarlas segú "status": { "status": "OK", "reason": "00", - "description": "La petición se ha procesado correctamente", + "message": "La petición se ha procesado correctamente", "date":"2023-06-21T09:56:06-05:00" }, "pagination": { diff --git a/src/pages/autopay/authentication.mdx b/src/pages/autopay/authentication.mdx index b7804f440..40cbb35a5 100644 --- a/src/pages/autopay/authentication.mdx +++ b/src/pages/autopay/authentication.mdx @@ -2,7 +2,8 @@ import { HeroPattern } from '@/components/HeroPattern' -# Autenticación +# Autenticación API + Para interactuar con la API de AutoPay debes autenticar tus peticiones, de esta forma identificamos y validamos la información para que tus operaciones sean seguras. La API utiliza *Web Services Security UsernameToken Profile 1.1*. ## Credenciales API @@ -10,15 +11,11 @@ Para interactuar con la API de AutoPay debes autenticar tus peticiones, de esta En la integración con AutoPay se debe contar con las credenciales login y secretKey de consumidor. -- **login:** Identificador del sitio, puede considerarse público, pues viaja como dato plano -en las peticiones API. -- **secretKey:** Llave secreta del sitio, debe ser privada, a partir de este dato se -generará un nuevo tranKey que será enviado en las peticiones. +- **login:** Identificador del sitio, puede considerarse público, pues viaja como dato plano en las peticiones API. +- **secretKey:** Llave secreta del sitio, debe ser privada, a partir de este dato se generará un nuevo tranKey que será enviado en las peticiones. - Estas credenciales son propias del sitio y deben ser tratadas de forma segura. No - comparta sus credenciales en áreas de acceso público como Github, código del lado de - cliente u otros lugares de fácil acceso para terceros. + Estas credenciales son propias del sitio y deben ser tratadas de forma segura. No comparta sus credenciales en áreas de acceso público como Github, código del lado del cliente u otros lugares de fácil acceso para terceros. ## Objeto Authentication {{ id: 'authentication-object' }} @@ -65,7 +62,7 @@ El parámetro `auth` debe ser enviado en todas la peticiones API y contiene el g Debes conocer y preparar los siguientes datos: -**login:** Credencial `login` provista al inicar tu integración. Identificador del sitio. +**login:** Credencial `login` provista al iniciar tu integración. Identificador del sitio. **secretKey**: Credencial `secretKey` provista al iniciar tu integración. Llave secreta del sitio. diff --git a/src/pages/autopay/charge-types.mdx b/src/pages/autopay/charge-types.mdx index de5ad7a30..80772bb6b 100644 --- a/src/pages/autopay/charge-types.mdx +++ b/src/pages/autopay/charge-types.mdx @@ -2,14 +2,42 @@ import { HeroPattern } from '@/components/HeroPattern' -# Cargos en AutoPay -Un cargo en **AutoPay** se refiere al monto que se intenta cobrar en cada fecha programada del autopago. Existen varias formas en las que se puede definir el monto a cobrar, conocidas como **"Tipos de cargo"**. +# Tipos de Cobro en AutoPay -## Tipos de cargo -El tipo de cargo define la modalidad de cargo que se va a cobrar, es decir, la forma en que se determina el monto a cobrar en cada ejecución del autopago (por ejemplo, saldo total, pago mínimo, etc.). A continuación se definen los tipos de cargo disponibles en el sistema de AutoPay y cómo operan dentro del flujo general. +AutoPay ofrece tres tipos de configuración para adaptarse a tu modelo de negocio, permitiendo desde cobros planos hasta montos variables basados en consumo. -| Tipo de cargo | Qué cobra | Fuente del monto en ejecución | -|------------------------|-----------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| `TOTAL_BALANCE` | El **saldo total** requerido del período (total a pagar segun recurrencia). | Se consulta el [**balance**](/autopay/contracts/balance) de la obligación vía API del comercio si está está habilitada en cada pago a realizar. | -| `MINIMUM_BALANCE` | El **pago mínimo** requerido del período. | Se consulta el [**balance**](/autopay/contracts/balance) para obtener el mínimo del período en cada pago a realizar. | -| `FIXED` | Un **monto fijo** especificado por el comercio/usuario. | El monto lo provee la solicitud o en su defecto será elegido por el usuario en el momento de la confirmación del autopago. | +La propiedad `recurring.type` define qué lógica se aplicará para determinar el monto final de la transacción. + +## Tabla comparativa + +| Tipo | Modelo de Negocio | ¿Requiere API Balance? | Ejemplo | +| :--- | :--- | :--- | :--- | +| **FIXED** | Valor constante | **No** | Membresías, Colegiaturas, Seguros | +| **TOTAL_BALANCE** | Consumo Variable | **Sí** | Servicios Públicos, Telefonía Post-pago | +| **MINIMUM_BALANCE** | Pagos Flexibles | **Sí** | Créditos Rotativos, Tarjetas de Crédito | + +--- + +## Detalle de los tipos + +### 1. FIXED (Monto fijo) +Es el modelo más sencillo y común. El valor a cobrar se define **una única vez** al momento de crear la suscripción. +* **Comportamiento:** Cobra siempre el mismo importe definido en la creación. +* **Integración:** No requiere consultar tu servidor. +* **Ideal para:** Gimnasios, suscripciones de software (SaaS), colegiaturas escolares, seguros mensuales o donaciones recurrentes. + +### 2. TOTAL_BALANCE (Saldo total) +Diseñado para comercios donde el monto cambia ciclo a ciclo. +* **Comportamiento:** Antes de cada cobro, AutoPay consulta tu endpoint `/balance`. +* **Lógica:** Toma el valor reportado en el campo `amount` de tu API y procesa el cobro por esa cantidad exacta. +* **Ideal para:** Facturas de energía, agua, gas o planes de telefonía basados en consumo. + +### 3. MINIMUM_BALANCE (Pago mínimo) +Diseñado para productos financieros que ofrecen flexibilidad de pago al usuario. +* **Comportamiento:** Consulta tu endpoint `/balance`. +* **Lógica:** Cobra el valor reportado en el campo `min_amount` de tu API. +* **Ideal para:** Créditos donde el usuario ha autorizado el descuento automático del pago mínimo exigible para mantenerse al día. + + + **Requisito Técnico:** Para usar `TOTAL_BALANCE` o `MINIMUM_BALANCE`, es obligatorio que tu servidor exponga el endpoint [Consultar Balance](/autopay/contracts/balance) para que AutoPay pueda preguntarte cuánto cobrar. + \ No newline at end of file diff --git a/src/pages/autopay/codes.mdx b/src/pages/autopay/codes.mdx index 8cb34f9ab..6b7063c97 100644 --- a/src/pages/autopay/codes.mdx +++ b/src/pages/autopay/codes.mdx @@ -4,26 +4,31 @@ import { HeroPattern } from '@/components/HeroPattern' # Códigos de respuesta -## Posibles errores de autenticación - -| Código | Causa | -|--------|-----------------------------------------------------------------------------| -| 100 | Authentication no proporcionado (Encabezado de la autorización mal formada).| -| 101 | El identificador del consumidor no existe. | -| 102 | El hash de TranKey no coincide, puede ser incorrecto o mal formado. | -| 103 | Fecha del seed mayor de 5 minutos. | -| 104 | Consumidor inactivo | - - -## Posibles razones de fallo - -| Código | Causa | -|--------|-----------------------------------------------------------------------------------------------------------------------------------| -| 00 | Operación exitosa. Indica que el flujo fue procesado correctamente sin errores. | -| BR | La solicitud contiene errores, puede tener datos inválidos, incumplir reglas de validación o referenciar recursos no autorizados. | -| X3 | Error en la solicitud enviada a servicios externos, puede tratarse de formato incorrecto, campos inválidos o datos incompletos. | -| XH | Error interno inesperado en el sistema que impidió procesar la operación. | -| ?- | La operación se encuentra en estado pendiente, aplica a flujos asincrónicos que aún no han finalizado. | -| 05 | Ha ocurrido un error durante el procesamiento con el servicio externo. | -| NF | No se ha encontrado el recurso o es inexistente. | -| XA | Monto no autorizado, el valor excede el límite permitido o el saldo disponible. | \ No newline at end of file +Aquí encontrarás el listado de códigos que la API retorna en el objeto `status`. Es importante diferenciar entre errores de autenticación (que impiden llegar al sistema) y errores de procesamiento. + +## Errores de Autenticación + +Estos códigos indican problemas con las credenciales (`login`, `tranKey`, etc). + +| Código | Descripción | +| :--- | :--- | +| **100** | Authentication no proporcionado o encabezado mal formado. | +| **101** | El `login` proporcionado no existe o es incorrecto. | +| **102** | El `tranKey` es incorrecto o el hash no coincide. | +| **103** | El `seed` ha expirado (diferencia mayor a 5 minutos). | +| **104** | El sitio (Comercio) se encuentra inactivo. | + +## Estados de la Transacción + +Estos códigos describen el resultado de la operación al procesarse una transacción del autopago. + +| Código | Significado | +| :--- | :--- | +| **00** | **Aprobada.** La operación se procesó correctamente. | +| **?-** | **Pendiente.** La operación está en curso (flujos asíncronos). | +| **BR** | **Solicitud Incorrecta (Bad Request).** Datos inválidos o faltantes. | +| **X3** | **Error de Validación.** Formato incorrecto en campos específicos. | +| **XA** | **Rechazo Financiero.** Fondos insuficientes o monto no autorizado. | +| **NF** | **No Encontrado.** El recurso (ID o referencia) no existe. | +| **05** | **Error Externo.** Fallo en la comunicación con la red financiera. | +| **XH** | **Error Interno.** Fallo inesperado en el sistema de AutoPay. | \ No newline at end of file diff --git a/src/pages/autopay/contract-authentication.mdx b/src/pages/autopay/contract-authentication.mdx index 7be3a2799..bd474a690 100644 --- a/src/pages/autopay/contract-authentication.mdx +++ b/src/pages/autopay/contract-authentication.mdx @@ -2,34 +2,35 @@ import { HeroPattern } from '@/components/HeroPattern' -# Autenticación de contratos +# Autenticación de Contratos -Para que el servicio de AutoPay pueda interactuar con tu API siguiendo los contratos definidos debes autenticar tus peticiones, de esta forma podrás identificarnos y validar la información para que tus operaciones sean seguras. La API debe utilizar **HTTP Basic Authentication (Basic Auth)**. +Dado que AutoPay enviará peticiones a tu servidor (Balance y Settlement), necesitas un mecanismo para asegurarte de que **realmente somos nosotros** y no un atacante. -## Credenciales API +Utilizamos el estándar **HTTP Basic Authentication**. -En la integración con AutoPay se debe contar con las credenciales `username` y `password` del comercio implementador. +## Credenciales -- **username:** Usuario que el comercio implementador debe **proveer a AutoPay** durante la configuración del sitio. Máximo 60 caracteres. -- **password:** Contraseña que el comercio implementador debe **proveer a AutoPay** durante la configuración del sitio. Máximo 60 caracteres. +A diferencia de la API transaccional, en los contratos **tú defines las credenciales** y nosotros las utilizamos. -Estas credenciales serán usadas por AutoPay para autenticarse **contra los contratos/servicios del comercio**, por lo tanto **el comercio debe validarlas** en cada solicitud entrante. +| Credencial | Definición | Restricciones | +| :--- | :--- | :--- | +| **Username** | El nombre de usuario que definiste para tu integración. | Máximo **60 caracteres**. | +| **Password** | La contraseña segura asociada. | Máximo **60 caracteres**. | - - Estas credenciales son propias del comercio y deben ser tratadas de forma segura. No - comparta sus credenciales en áreas de acceso público como Github, código del lado de - cliente u otros lugares de fácil acceso para terceros. + + Estas credenciales se configuran en el proceso de Onboarding [Solicitud de activación](/autopay/#service-activation). -## Objeto Authentication {{ id: 'authentication-object' }} +## Objeto Authentication -La autenticación se envía en **headers** en cada solicitud que AutoPay realice hacia los contratos del comercio. +La autenticación se envía en los **headers** de cada solicitud HTTP. - Header requerido. Se envía con el formato: Basic base64(username:password) + Header requerido. + Se envía con el formato: Basic base64(username:password) @@ -42,28 +43,25 @@ La autenticación se envía en **headers** en cada solicitud que AutoPay realice -## Cómo validar la autenticación {{ id: 'how-to-validate-authentication' }} - -Debes conocer y preparar los siguientes datos: - -**username:** Usuario que configuraste para que AutoPay consuma tus contratos. Máximo 60 caracteres. +--- -**password:** Contraseña que configuraste para que AutoPay consuma tus contratos. Máximo 60 caracteres. +## Cómo validar la autenticación -**Authorization:** Header recibido en la petición, con el formato: -`Authorization: Basic base64(username:password)` +Tu servidor debe interceptar cada petición entrante y ejecutar la siguiente lógica de seguridad **antes** de procesar cualquier dato de negocio. -### Reglas de validación basicas +### Algoritmo de validación -1. Verificar que exista el header `Authorization`. -2. Verificar que el esquema sea `Basic`. -3. Decodificar el token Base64 y obtener el texto `username:password`. -4. Separar `username` y `password`. -5. Comparar contra tus credenciales configuradas. -6. Si falla, responder `401 Unauthorized` (opcionalmente con `WWW-Authenticate`). +1. **Verificar Cabecera:** Confirma que la petición tiene el header `Authorization`. +2. **Verificar Esquema:** Asegúrate de que empieza con la palabra clave `Basic`. +3. **Decodificar:** Toma la cadena después del espacio y decodifícala de Base64 para obtener `username:password`. +4. **Comparar:** Separa el texto por los dos puntos (`:`) y compara los valores con los que tienes configurados en tus variables de entorno. +5. **Decidir:** + * Si coinciden: **Permite el acceso (HTTP 200)**. + * Si no coinciden: **Rechaza inmediatamente (HTTP 401 Unauthorized)**. - La autenticación Basic debe viajar siempre sobre HTTPS. Base64 no cifra, solo codifica. - - + **Seguridad crítica:** Estas credenciales son privadas y permiten inyectar datos en tu sistema. + * **HTTPS:** La autenticación Basic debe viajar siempre sobre canales cifrados. + * **Código fuente:** **No compartas** tus credenciales en áreas de acceso público como **GitHub**, ni las incluyas en código del lado del cliente (Frontend). Úsalas siempre mediante variables de entorno en tu servidor. + \ No newline at end of file diff --git a/src/pages/autopay/contracts/balance.mdx b/src/pages/autopay/contracts/balance.mdx index 24e877829..6df74abf4 100644 --- a/src/pages/autopay/contracts/balance.mdx +++ b/src/pages/autopay/contracts/balance.mdx @@ -4,26 +4,27 @@ import { HeroPattern } from '@/components/HeroPattern' export const apiRefs = ['/autopay/balance'] -## Consultar monto a cobrar {{ id: 'balance', tag: 'POST', label: '{{baseURL}}/autopay/balance' }} +## Consultar monto a cobrar {{ id: 'balance', tag: 'POST', label: '/autopay/balance' }} - - **baseURL**: Es la URL base del aplicativo del cliente/comercio la cual debe ser entregada por el mismo y configurada en el momento del onboarding del comercio con AutoPay. - +Este endpoint contiene la lógica de los cobros variables (`TOTAL_BALANCE` o `MINIMUM_BALANCE`). Antes de intentar cualquier transacción, AutoPay consultará este servicio para saber **cuánto cobrar** en el instante. - **Autenticación (Basic Authentication):** Este endpoint requiere autenticación vía header `Authorization`. - El comercio debe validar las credenciales configuradas para AutoPay en cada solicitud entrante. Ver más en [**Autenticación de contratos**](/autopay/contract-authentication). + **Endpoint del comercio:** La URL base (`{{baseURL}}`) corresponde a **tu propio servidor**. + Debes exponer este servicio en tu infraestructura y entregar la URL base durante el proceso de onboarding con AutoPay. - - - Este endpoint permite conocer el monto que debe cobrarse asociado a un AutoPay. - Devuelve dos valores: +### Reglas de negocio - - **amount:** monto total a cobrar en el ciclo actual. - - **min_amount:** monto mínimo requerido para ejecutar el cobro. +1. **Moneda:** La moneda (`currency`) que respondas debe coincidir con la configurada en el autopago original. +2. **Saldo Cero:** Si respondes con un `total` de `0`, AutoPay entenderá que no hay deuda pendiente y **no realizará ningún cobro**. +3. **Selección de Monto:** AutoPay leerá el campo correspondiente según la configuración del autopago: + * Si es `TOTAL_BALANCE` tomará el valor de `amount`. + * Si es `MINIMUM_BALANCE` tomará el valor de `min_amount`. - Puede usarse para validar si existen valores pendientes antes de iniciar un proceso de pago o conciliación automática. +--- + + + -## Contratos API del cliente al integrar AutoPay +# Contratos de Cliente (Merchant API) + +A diferencia de la API estándar donde tú inicias las peticiones, en los **Contratos de Cliente** es AutoPay quien **consulta a tu servidor** para realizar operaciones críticas en tiempo real. + +Esta sección documenta los endpoints que tu infraestructura debe exponer para permitir la automatización de cobros y la sincronización de estados. + +## Configuración y Base URL - **baseURL**: Es la URL base del aplicativo del cliente/comercio la cual debe ser entregada por el mismo y configurada en el momento del onboarding del comercio con AutoPay. + **Base URL:** Debes entregar esta URL durante el onboarding. Ten en cuenta que AutoPay concatenará automáticamente el prefijo **/autopay** a todas las peticiones, por lo que tu enrutador debe estar configurado para soportarlo. + + **Ejemplo:** + * Base URL entregada: `https://api.tucomercio.com` + * Petición final de AutoPay: `POST https://api.tucomercio.com/autopay/balance` -Para operar AutoPay de extremo a extremo, el cliente/comercio debe exponer un conjunto de endpoints propios que siguen los contratos definidos en esta documentación. +## Servicios a Implementar -Estos endpoints permiten a Placetopay: -- Consultar el balance/importe a cobrar. -- Confirmar la aplicación del pago -- Recibir notificaciones del ciclo de vida del autopago (activación, actualización, desactivación, resultados de ejecución). +Para garantizar una integración completa, debes exponer los siguientes contratos: -En este apartado, podrás obtener más información acerca de los contratos y ejemplos de cada uno de los servicios que debes implementar. +| Recurso | Método | Función | +| :--- | :--- | :--- | +| [**/balance**](/autopay/contracts/balance) | `POST` | **Exclusivo para Cobro Variable.** Nos permite consultar el monto a cobrar en cada ciclo. Necesario si usas modelos `TOTAL_BALANCE` o `MINIMUM_BALANCE`. | +| [**/settlement**](/autopay/contracts/settlement) | `POST` | **Obligatorio.** Confirmación final del pago aprobado para que puedas registrarlo/asentarlo en tus sistemas internos. | +| [**/webhook**](/autopay/contracts/webhook) | `POST` | **Obligatorio.** Canal de notificación para recibir actualizaciones de estado (creación, cancelación) y resultados de los cobros. | - - Como cliente al implementar estos contratos deberás implementar una autenticación basada en *Basic Autentication*, de esta forma podrás identificarnos y validar la información para que tus operaciones sean seguras. Ver más en [**Autenticación de contratos**](/autopay/contract-authentication). - \ No newline at end of file +--- + +## Requisitos Técnicos + +Tu API debe cumplir con los siguientes estándares: + +### 1. Seguridad (Basic Auth) +AutoPay se autenticará enviando una cabecera `Authorization`. Tú defines las credenciales (`username` y `password`) y debes validarlas en cada petición entrante. + +### 2. Formato y Transporte +* **Protocolo:** HTTPS estricto. +* **Formato:** JSON (`Content-Type: application/json`). +* **Rendimiento:** Se recomienda responder en menos de 3 segundos para evitar timeouts. \ No newline at end of file diff --git a/src/pages/autopay/contracts/settlement.mdx b/src/pages/autopay/contracts/settlement.mdx index 096188132..80284f29a 100644 --- a/src/pages/autopay/contracts/settlement.mdx +++ b/src/pages/autopay/contracts/settlement.mdx @@ -4,22 +4,27 @@ import { HeroPattern } from '@/components/HeroPattern' export const apiRefs = ['/autopay/settlement'] -## Asentar/Confirmar un pago {{ id: 'settlement', tag: 'POST', label: '{{baseURl}}/autopay/settlement' }} - - **baseURL**: Es la URL base del aplicativo del cliente/comercio la cual debe ser entregada por el mismo y configurada en el momento del onboarding del comercio con AutoPay. - +## Confirmar / Asentar pago {{ id: 'settlement', tag: 'POST', label: '/autopay/settlement' }} - - **Autenticación (Basic Authentication):** Este endpoint requiere autenticación vía header `Authorization`. - El comercio debe validar las credenciales configuradas para AutoPay en cada solicitud entrante. Ver más en [**Autenticación de contratos**](/autopay/contract-authentication). - +Este endpoint es el **cierre oficial** de una transacción exitosa. AutoPay invocará este servicio únicamente cuando un cobro haya sido **APROBADO** por la red financiera. + +Tu objetivo aquí es recibir la confirmación y registrar el pago en tu ERP, base de datos o sistema contable. - El asentamiento se realiza solo para las transacciones que han sido procesadas exitosamente y están en estado **APPROVED**. + **Endpoint del comercio:** La URL base (`{{baseURL}}`) corresponde a **tu propio servidor**. + Debes exponer este servicio en tu infraestructura y entregar la URL base durante el proceso de onboarding con AutoPay. + +### Reglas de Negocio Recomendadas + +1. **Idempotencia:** Es posible que, por intermitencias de red, recibas esta confirmación más de una vez para la misma transacción. Tu sistema debe validar si el pago ya fue asentado previamente y responder `200 OK` sin duplicar el registro. +2. **Validación de Monto:** Verifica que el `transaction.amount.total` coincida con lo que esperabas cobrar. +3. **Respuesta Rápida:** Este proceso es síncrono. Responde lo más rápido posible (`< 3s`) para finalizar el ciclo. + +--- + - Este endpoint se utiliza para confirmar un pago previamente procesado, enviando los detalles de la transacción. + **Importante:** + 1. Las transacciones **aprobadas** se envían exclusivamente a través de [Settlement](/autopay/contracts/settlement). + 2. Aunque este endpoint pertenece a contratos y existe una [Autenticación de contratos](/autopay/contracts/authentication), la integridad del mensaje debe validarse mediante la **Firma Digital** descrita a continuación. + -### Validación del webhook {{ id: 'validating-webhooks' }} +### Eventos disponibles {{ id: 'event-types' }} -Debido a que la notificación llega desde un sistema externo a tus servidores, es importante validar que el mensaje es autentico y viene de un origen confiable. Para esto se hace uso de una firma incluida en el mensaje y que fue generada usando el `secretKey` proveniente del sitio que solo conocen los sistemas involucrados. Para conocer más de tu `secretKey`, consulta la documentación de [Autenticación](/autopay/authentication) +| Evento | Descripción | +| :--- | :--- | +| `AUTOPAY_CREATED` | El usuario finalizó el registro y el autopago está activo. | +| `AUTOPAY_UPDATED` | Se actualizó el medio de pago o las reglas del autopago. | +| `AUTOPAY_TRANSACTION_FAILED` | Un intento de cobro automático falló (ej. fondos insuficientes). | +| `AUTOPAY_CANCELED` | El autopago ha sido cancelado y no generará más cobros. | -Para iniciar tu validación debes tener disponible el `secretKey` asociado con tu comercio. +## Validación de seguridad (firmas) {{ id: 'security-validation' }} -**Identificar el algoritmo** para identificar el algoritmo usado en la firma, ten en cuenta lo siguiente: +Es **crítico** verificar que la notificación proviene realmente de Placetopay. Para ello, firmamos cada mensaje digitalmente. Debes replicar este proceso en tu servidor y comparar el resultado. -- Si el campo `signature` comienza con el prefijo `sha256:`, entonces la firma fue generada usando SHA-256. +**Ejemplo de validación:** -**Extraer la firma plana**: Una vez identificado el algoritmo, identifica el campo `signature`. +Supongamos que tu `secretKey` es `ABC123example456trankey+789abc012def3456ABC=` y recibes el siguiente payload: -- Si el prefijo `sha256:` está presente, debes eliminarlo y con esto obtendrás la firma plana que debes comparar, llamaremos a esta `receivedSignature`. +```json {{ title: '1. Payload Recibido' }} +{ + "id": "111111-2222-3333-4444-555555555555", + "type": "AUTOPAY_TRANSACTION_FAILED", + "date": "2023-01-01 12:00:00", + "signature": "sha256:a1b2c3d4e5..." +} +``` -**Generar tu propia firma** Una vez identificado el algoritmo, debes generar tu propia firma usando la siguiente fórmula: +### Proceso paso a paso -- Para SHA-256: `SHA-256(id + type + date + secretKey)` +1. **Concatenar:** Une los valores de `id`, `type`, `date` y tu `secretKey` (en este orden exacto, sin espacios ni separadores). + > Cadena = `111111-2222-3333-4444-555555555555` + `AUTOPAY_TRANSACTION_FAILED` + `2023-01-01 12:00:00` + `ABC123example456trankey+789abc012def3456ABC=` -Con esto obtendrás la firma generada por tu sistema, llamaremos a esta `generatedSignature`. Ten encuenta que los datos para generar la firma se encuentra en el detalle del webhook, ver más en [Contrato de webhook](/autopay/contracts/webhook). +2. **Hashear:** Aplica el algoritmo **SHA-256** a la cadena resultante. -**Comparar firmas**: Finalmente, compara la firma que generaste (`generatedSignature`) con la firma que recibiste en el mensaje (`receivedSignature`). Si ambas firmas son iguales, entonces la notificación es auténtica y puedes proceder a actualizar el estado de la sesión en tu sistema. +3. **Comparar:** Si tu hash coincide con la `signature` recibida (omitiendo el prefijo `sha256:`), la petición es auténtica. - Al recibir una notificación, se recomienda llamar a la API de [consulta de AutoPagos](/autopay/autopay-api) para obtener más detalles sobre el cambio, - de manera que siempre se tenga información precisa y actualizada. + Si la firma no coincide, responde **HTTP 400** e ignora el mensaje. **Nunca** expongas tu `secretKey` en el frontend o repositorios públicos. -## Notificaciones {{ id: 'webhook', tag: 'POST', label: '{{baseURl}}/autopay/webhook' }} +--- - - **baseURL**: Es la URL base del aplicativo del cliente/comercio la cual debe ser entregada por el mismo y configurada en el momento del onboarding del comercio con AutoPay. +## Estructura del webhook {{ id: 'webhook', tag: 'POST', label: '/autopay/webhook' }} + + + **Recomendación:** El webhook es una notificación de evento. Para garantizar que tienes la información más reciente y detallada, se recomienda consultar la API de [Buscar AutoPagos](/autopay/api/search) usando el `id` recibido. + - Debe exponer un endpoint conforme al siguiente contrato. AutoPay enviará notificaciones a dicho endpoint cada vez que un autopago sea creado, se haya actualizado el medio de pago, sea cancelado o fallado algún pago. + +# Cómo funciona AutoPay + +AutoPay es una solución integral que te permite automatizar cobros recurrentes delegando en Placetopay tanto la seguridad (tokenización PCI) como la ejecución programada de los cobros. + +A diferencia de una suscripción tradicional, AutoPay soporta **modelos de cobro variable** (como facturación de servicios públicos o consumo) y **modelos fijos** (como membresías), gestionando automáticamente los reintentos y la actualización de medios de pago. + +## Modelo de integración unificado + +En lugar de tener que coordinar la creación de interfaces, la tokenización de tarjetas y la configuración de reglas de cobro por separado, tu servidor solo necesita comunicarse con la API de Gateway. + +El Gateway se encarga de **centralizar** la operación: + +1. **Gestión de la Interfaz:** Genera automáticamente la sesión segura en WebCheckout para que el usuario ingrese sus datos. +2. **Seguridad (PCI):** Asegura que los datos sensibles sean capturados y tokenizados directamente en nuestros servidores, manteniendo tu comercio fuera del alcance de auditorías PCI complejas. +3. **Programación de Cobros:** Registra y activa las reglas de recurrencia (frecuencia y montos) en el motor de AutoPay para asegurar que los cobros futuros se ejecuten puntualmente. + +## Conceptos clave + +Para integrar AutoPay, es necesario entender dos configuraciones que definen el contrato: + +### 1. Recurrencia (Recurring) +Define la "frecuencia y vida útil" del contrato (Periodicidad, Intervalo y Fechas de vigencia). Es fundamental configurar correctamente estos parámetros para que el motor de cobros funcione según lo esperado. + +👉 [**Ver guía de configuración de Recurrencia**](/autopay/recurring-setup) + +### 2. Tipos de cargo (Charge Type) +Define cómo se calcula el monto a cobrar en cada ciclo. AutoPay permite desde cobros fijos (`FIXED`) hasta consultas en tiempo real de deuda total (`TOTAL_BALANCE`) o pagos mínimos (`MINIMUM_BALANCE`) contra tu sistema. + +👉 [**Ver detalle de Tipos de Cargo**](/autopay/charge-types) + +## Ciclo de vida de la integración + +A continuación, se describe el flujo de creación de un autopago y la ejecución posterior. + + + +### Fases del proceso + +1. **Inicialización:** Tu servidor consume la API del Gateway (`POST /autopay/session`) enviando las reglas de recurrencia. El sistema retorna una URL de redirección. +2. **Captura y tokenización:** El usuario es redirigido a WebCheckout. Allí selecciona su medio de pago, acepta los términos y la tarjeta es tokenizada de forma segura. +3. **Confirmación:** Al finalizar, el usuario regresa a tu sitio. Debes consultar el estado de la sesión para confirmar que el AutoPago fue creado (`APPROVED`). +4. **Ejecución programada (futuro):** + * El motor de AutoPay detecta cuándo es el próximo cobro. + * Si es monto variable, consulta tu API de Balance. + * Ejecuta la transacción usando el token guardado. + * Te notifica el resultado vía Webhook (`AUTOPAY_TRANSACTION_FAILED` o exitosa). + +### Edición de un AutoPago (Actualización) +¿Qué pasa si la tarjeta del usuario vence? El flujo para **editar** una suscripción reutiliza la misma integración: + +1. Creas una nueva sesión en el Gateway (`POST /autopay/session`) especificando la acción `EDIT` y el `id` del autopago existente. +2. Rediriges al usuario a WebCheckout. +3. El usuario actualiza sus datos de pago. +4. Al finalizar, el sistema actualiza el token asociado sin perder el historial de la suscripción. + +## ¿Qué sigue? + +* [Crear una sesión de AutoPago](/autopay/api/session#create-a-session) +* [Implementar los contratos de cliente](/autopay/contracts) (Para cobros variables) +* [Gestión de AutoPagos](/autopay/api/session/#query-a-session) (Consulta y cancelación) \ No newline at end of file diff --git a/src/pages/autopay/index.mdx b/src/pages/autopay/index.mdx index fcaa9960f..5521737d3 100644 --- a/src/pages/autopay/index.mdx +++ b/src/pages/autopay/index.mdx @@ -1,26 +1,45 @@ +import { AutopayBenefits } from '@/components/AutopayBenefits' +import { AutoPayDocsList } from '@/components/AutoPayDocsList' +import { AutoPayRequirements } from '@/components/AutoPayRequirements' import { HeroPattern } from '@/components/HeroPattern' -# AutoPay (BETA) +# PlacetoPay AutoPay (BETA) -**AutoPay Placetopay** es un servicio de pagos automáticos que permite a los comercios habilitar cobros recurrentes o programados con un medio de pago previamente autorizado por el usuario (tarjeta o cuenta bancaria compatible), sin requerir intervención manual en cada transacción. La solución contempla una experiencia de registro guiada para el usuario final, servicios API para que el comercio cree y gestione sesiones de autopago y procesos de ejecución que disparan los cobros según la configuración definida. +**PlacetoPay AutoPay** es un servicio de pagos automáticos que permite a los comercios habilitar cobros recurrentes o programados con un medio de pago previamente autorizado por el usuario. {{ className: 'lead' }} ---- -## ¿Por qué es útil? +La solución contempla una experiencia de registro guiada para el usuario final, servicios API para que el comercio cree y gestione sesiones de autopago, y procesos de ejecución de cobros según la configuración definida. + + + **Importante:** Esta funcionalidad debe ser habilitada explícitamente en tu sitio. + + +## Solicitud de activación {{ id: 'service-activation' }} + +Para acceder a este servicio, ponte en contacto con nuestro equipo de Posventa a través de cualquiera de los siguientes canales y te atenderemos con gusto: -- **Mejora de conversión y retención:** reduce fricción en pagos repetitivos (servicios, seguros, telcos, suscripciones). -- **Automatización operativa:** elimina procesos manuales y recordatorios; los cobros se ejecutan en las fechas pactadas. -- **Control y transparencia:** el comercio puede revisar, ajustar o cancelar sus autopagos. -- **Seguridad y cumplimiento:** uso de medios tokenizados y lineamientos PCI, con opciones de autenticación (p. ej., 3DS 3RI si aplica). -- **Integrabilidad:** además de la integración directa de checkout, el ecosistema expone endpoints para creación/actualización/desactivación y consulta de sesiones/autopagos; también se soportan webhooks para la notificación de eventos relevantes. +* **Correo electrónico:** [servicioposventa@placetopay.com](mailto:servicioposventa@placetopay.com) +* **Página web:** [www.placetopay.com](https://www.placetopay.com) +* **Teléfonos:** (+57) 604 444 2310 / (+57) 317 431 0510 +* **Dirección:** Carrera 65 # 45 - 20, Oficina 430. Medellín, Colombia. --- -## ¿Cómo funciona? -1) [**API de AutoPay:**](/autopay/api) Como cliente podrás interactuar con la API de AutoPay para realizar acciones sobre los autopagos de tus usuarios, como la generación, consulta actualización y desactivación de los mismos. -2) [**Integración directa del cliente:**](/autopay/contracts) -Como cliente tu aplicación podrá exponer algunos endpoints para que AutoPay pueda interactuar con ellos, -obtener la información necesaria de la factura para procesar un pago ([Balance](/autopay/contracts/balance)), registrar resultados de cada pago ([Asentamiento](/autopay/contracts/settlement)) -y recibir información actualizada sobre el estado del autopago ([Webhooks](/autopay/contracts/webhook)). -En esta documentación encontrarás toda la información necesaria para integrar AutoPay en tu plataforma. + +## Beneficios de AutoPay {{ id: 'autopay-benefits' }} + + + --- + +## Cómo utilizar esta documentación {{ id: 'como-utilizar-esta-documentacion' }} + +Aquí encontrarás guías detalladas, referencias de API y ejemplos de código para integrar y configurar AutoPay en tu plataforma de forma ágil y segura. + + + +## Requisitos previos {{ id: 'previous-requirements' }} + +Para poder integrarse de manera exitosa y sin contratiempos, te recomendamos: + + diff --git a/src/pages/autopay/recurring-setup.mdx b/src/pages/autopay/recurring-setup.mdx new file mode 100644 index 000000000..3d813d4f4 --- /dev/null +++ b/src/pages/autopay/recurring-setup.mdx @@ -0,0 +1,85 @@ +import { HeroPattern } from '@/components/HeroPattern' +import RecurringSequence from "@/components/react-flow/SequenceDiagram/Diagrams/AutoPay/es/RecurringSequence" + + + +# Reglas de recurrencia + +El objeto `recurring` es la lógica principal de la automatización. Define **cuándo** se cobra y **hasta cuándo** debe mantenerse activo el contrato. + +## Estructura del objeto + +```json +"recurring": { + "type": "TOTAL_BALANCE", + "periodicity": "M", + "interval": 1, + "nextPayment": "2025-06-03", + "dueDate": "2025-08-03", + "notificationUrl": "https://merchant.test/notification" +} +``` + +## Definición de propiedades + + + + **Requerido.** Define la modalidad del cobro. + * `FIXED`: Monto fijo (Suscripciones). + * `TOTAL_BALANCE`: Cobra la deuda total consultada a tu API. + * `MINIMUM_BALANCE`: Cobra el pago mínimo consultado a tu API. + + [Ver detalle de Tipos de Cargo](/autopay/charge-types) + + + + **Requerido.** Unidad de tiempo para la frecuencia. + * `D`: Días + * `W`: Semanas + * `M`: Meses + * `Y`: Años + + + + **Requerido.** Multiplicador de la periodicidad. + Ejemplo: Para cobrar "Cada 2 Semanas", usa `periodicity: W` e `interval: 2`. + + + + **Requerido.** Formato `YYYY-MM-DD`.
+ Es la fecha de inicio. El sistema no realizará ningún cobro antes de esta fecha. + * **Al crear:** Define cuándo será el **primer** cargo. + * **Automático:** Después de cada cobro exitoso, el sistema actualiza este campo automáticamente sumando la frecuencia configurada. +
+ + + **Opcional.** Formato `YYYY-MM-DD`.
+ Funciona como fecha de caducidad o límite superior del autopago. Si el cálculo del siguiente cobro resulta en una fecha posterior a este límite, el AutoPago se marca como **Finalizado** y deja de procesar cobros. +
+ + + **Requerido.** URL segura (`https`).
+ Endpoint donde tu servidor recibirá las notificaciones (Webhooks) cada vez que ocurra un cobro, un fallo o un cambio de estado en este autopago. +
+
+ +--- + +## Lógica de cálculo de fechas + +El motor de AutoPay (Scheduler) ejecuta un proceso diario. Para determinar la fecha del **siguiente cobro**, el sistema sigue una lógica estricta para asegurar que el autopago siga vigente. + +El siguiente diagrama ilustra cómo se actualiza el objeto `recurring` después de un cobro exitoso: + + + +### Ejemplos de frecuencias comunes + +Aunque la lógica es flexible, aquí tienes las combinaciones más utilizadas: + +| Frecuencia Deseada | Configuración JSON | Resultado Lógico | +| :--- | :--- | :--- | +| **Mensual** | `"periodicity": "M", "interval": 1` | Cobra cada mes el mismo día (ej. 5 Ene, 5 Feb). | +| **Trimestral** | `"periodicity": "M", "interval": 3` | Cobra cada 3 meses. | +| **Quincenal** | `"periodicity": "W", "interval": 2` | Cobra cada 2 semanas (ej. Viernes por medio). | +| **Anual** | `"periodicity": "Y", "interval": 1` | Cobra una vez al año. | \ No newline at end of file diff --git a/src/pages/checkout/index.mdx b/src/pages/checkout/index.mdx index dcd28ccd2..e20c02262 100644 --- a/src/pages/checkout/index.mdx +++ b/src/pages/checkout/index.mdx @@ -42,7 +42,7 @@ Esta documentación está diseñada para ayudarte a aprovechar al máximo todas -## Requisitios prévios {{ id: 'previous-requirements' }} +## Requisitos previos {{ id: 'previous-requirements' }} Para poder integrarse de manera exitosa y sin contratiempos, te recomendamos: diff --git a/src/pages/en/autopay/api/index.mdx b/src/pages/en/autopay/api/index.mdx index 7f696102a..347decd5e 100644 --- a/src/pages/en/autopay/api/index.mdx +++ b/src/pages/en/autopay/api/index.mdx @@ -2,8 +2,57 @@ import { HeroPattern } from '@/components/HeroPattern' -## API to Integrate with AutoPay +# AutoPay API Reference -To operate AutoPay end to end, AutoPay exposes a set of endpoints so that the client/merchant can interact with them and perform actions on their users’ autopays, such as creation, retrieval, update, and deactivation. +Welcome to the AutoPay technical reference. Our API is built on RESTful principles, uses **JSON** for data exchange, and standard HTTP response codes. -In this section, you can find more information about the APIs and examples for each of the services. +## Environments and Base URL + +All requests must be sent to the following base URLs, depending on the environment you are in: + +| Environment | Base URL | Description | +| :--- | :--- | :--- | +| **Sandbox** | `https://api-test.placetopay.com` | Used for development and testing. Does not process real money. | +| **Production** | `https://api.placetopay.com` | Real transactional environment. | + +## Headers + +All API requests must include the following HTTP headers to ensure the content is interpreted correctly: + +```json + Content-Type: application/json + Accept: application/json + User-Agent: YourApp/1.0 (Recommended to identify your traffic) +``` + +## Standard response structure + +Regardless of the endpoint, all API responses follow a common structure. You will always receive a `status` object indicating the technical result of the operation. + +```json + { + "status": { + "status": "OK", + "reason": "00", + "message": "The request has been processed successfully", + "date": "2023-06-21T09:56:06-05:00" + }, + ..., + } +``` + +* **`status`**: Indicates the success (`OK`) or failure (`FAILED`) of the technical request. +* **`reason`**: Internal code for programmatic error handling. +* **`message`**: Readable description of the result. +* **`*`** : Contains the requested information (e.g., session details, transaction list). + +--- + +## Available services + +Explore the available endpoints to manage the autopay lifecycle: + +* [**Sessions**](/autopay/api/session): The entry point. Allows creating a new autopay or editing an existing one. +* [**Search**](/autopay/api/search): Query the status and details of your autopays. +* [**Transactions**](/autopay/api/transactions): Get the history of charges made on a specific autopay. +* [**Cancellation**](/autopay/api/cancel): Stop an autopay to prevent future charges. \ No newline at end of file diff --git a/src/pages/en/autopay/api/transactions.mdx b/src/pages/en/autopay/api/transactions.mdx index 77e024435..f86707791 100644 --- a/src/pages/en/autopay/api/transactions.mdx +++ b/src/pages/en/autopay/api/transactions.mdx @@ -69,7 +69,7 @@ This service allows listing the transactions of an AutoPay and filtering them ac "status": { "status": "OK", "reason": "00", - "description": "The request has been processed successfully", + "message": "The request has been processed successfully", "date":"2023-06-21T09:56:06-05:00" }, "pagination": { diff --git a/src/pages/en/autopay/authentication.mdx b/src/pages/en/autopay/authentication.mdx index 1f3368249..a217125d6 100644 --- a/src/pages/en/autopay/authentication.mdx +++ b/src/pages/en/autopay/authentication.mdx @@ -2,7 +2,7 @@ import { HeroPattern } from '@/components/HeroPattern' -# Authentication +# API Authentication To interact with the AutoPay API, you must authenticate your requests. This allows us to identify and validate the information so your operations remain secure. The API uses *Web Services Security UsernameToken Profile 1.1*. diff --git a/src/pages/en/autopay/charge-types.mdx b/src/pages/en/autopay/charge-types.mdx index eebe55487..e4c4b2219 100644 --- a/src/pages/en/autopay/charge-types.mdx +++ b/src/pages/en/autopay/charge-types.mdx @@ -2,14 +2,42 @@ import { HeroPattern } from '@/components/HeroPattern' -# Charges in AutoPay -A charge in **AutoPay** refers to the amount that is attempted to be collected on each scheduled date of the autopay. There are several ways in which the amount to be charged can be defined, known as **“Charge Types.”** +# AutoPay Charge Types -## Charge types -The charge type defines the charging modality, that is, how the amount to be charged is determined in each autopay execution (for example, total balance, minimum payment, etc.). Below are the charge types available in the AutoPay system and how they operate within the general flow. +AutoPay offers three configuration types to adapt to your business model, allowing everything from flat fees to variable amounts based on consumption. -| Charge type | What it charges | Source of the amount at execution | -|------------------------|---------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| `TOTAL_BALANCE` | The **total balance** required for the period (total to pay according to recurrence). | The [**balance**](/autopay/contracts/balance) of the obligation is queried via the merchant API if it is enabled for each payment to be executed. | -| `MINIMUM_BALANCE` | The **minimum payment** required for the period. | The [**balance**](/autopay/contracts/balance) is queried to obtain the minimum amount for the period for each payment to be executed. | -| `FIXED` | A **fixed amount** specified by the merchant/user. | The amount is provided in the request or, if not, it will be selected by the user at the time of autopay confirmation. | +The `recurring.type` property defines the logic applied to determine the final transaction amount. + +## Comparison Table + +| Type | Business Model | Requires Balance API? | Example | +| :--- | :--- | :--- | :--- | +| **FIXED** | Constant Value | **No** | Memberships, Tuitions, Insurance | +| **TOTAL_BALANCE** | Variable Consumption | **Yes** | Utilities, Post-paid Phone Bills | +| **MINIMUM_BALANCE** | Flexible Payments | **Yes** | Revolving Credits, Credit Cards | + +--- + +## Type Details + +### 1. FIXED (Fixed Amount) +The simplest and most common model. The amount to charge is defined **once** when creating the subscription. +* **Behavior:** Always charges the same amount defined at creation. +* **Integration:** Does not require querying your server. +* **Ideal for:** Gyms, software subscriptions (SaaS), school tuitions, monthly insurance premiums, or recurring donations. + +### 2. TOTAL_BALANCE (Total Balance) +Designed for merchants where the amount changes from cycle to cycle. +* **Behavior:** Before each charge, AutoPay queries your `/balance` endpoint. +* **Logic:** Takes the value reported in the `amount` field of your API and processes the charge for that exact quantity. +* **Ideal for:** Energy, water, gas bills, or consumption-based phone plans. + +### 3. MINIMUM_BALANCE (Minimum Payment) +Designed for financial products that offer payment flexibility to the user. +* **Behavior:** Queries your `/balance` endpoint. +* **Logic:** Charges the value reported in the `min_amount` field of your API. +* **Ideal for:** Credits where the user has authorized the automatic deduction of the minimum payment required to stay current. + + + **Technical Requirement:** To use `TOTAL_BALANCE` or `MINIMUM_BALANCE`, your server must expose the [Balance Query](/autopay/contracts/balance) endpoint so AutoPay can ask how much to charge. + \ No newline at end of file diff --git a/src/pages/en/autopay/codes.mdx b/src/pages/en/autopay/codes.mdx index 96b7a6c6f..d3977dbeb 100644 --- a/src/pages/en/autopay/codes.mdx +++ b/src/pages/en/autopay/codes.mdx @@ -2,28 +2,33 @@ import { HeroPattern } from '@/components/HeroPattern' -# Response codes - -## Possible authentication errors - -| Code | Cause | -|------|-----------------------------------------------------------------------| -| 100 | Authentication not provided (Authorization header is malformed). | -| 101 | The consumer identifier does not exist. | -| 102 | The TranKey hash does not match; it may be incorrect or malformed. | -| 103 | Seed date is older than 5 minutes. | -| 104 | Inactive consumer. | - - -## Possible failure reasons - -| Code | Cause | -|------|--------------------------------------------------------------------------------------------------------------------------------------| -| 00 | Successful operation. Indicates that the flow was processed correctly without errors. | -| BR | The request contains errors; it may include invalid data, violate validation rules, or reference unauthorized resources. | -| X3 | Error in the request sent to external services; it may be due to incorrect format, invalid fields, or incomplete data. | -| XH | Unexpected internal system error that prevented processing the operation. | -| ?- | The operation is in a pending state; applies to asynchronous flows that have not yet completed. | -| 05 | An error occurred during processing with the external service. | -| NF | The resource was not found or does not exist. | -| XA | Amount not authorized; the value exceeds the allowed limit or the available balance. | +# Response Codes + +Here you will find the list of codes that the API returns in the `status` object. It is important to differentiate between authentication errors (which prevent access to the system) and processing errors. + +## Authentication Errors + +These codes indicate problems with credentials (`login`, `tranKey`, etc). + +| Code | Description | +| :--- | :--- | +| **100** | Authentication not provided or malformed header. | +| **101** | The provided `login` does not exist or is incorrect. | +| **102** | The `tranKey` is incorrect or the hash does not match. | +| **103** | The `seed` has expired (difference greater than 5 minutes). | +| **104** | The site (Merchant) is inactive. | + +## Transaction States + +These codes describe the result of the operation when processing an autopay transaction. + +| Code | Meaning | +| :--- | :--- | +| **00** | **Approved.** The operation was processed successfully. | +| **?-** | **Pending.** The operation is in progress (asynchronous flows). | +| **BR** | **Bad Request.** Invalid or missing data. | +| **X3** | **Validation Error.** Incorrect format in specific fields. | +| **XA** | **Financial Rejection.** Insufficient funds or unauthorized amount. | +| **NF** | **Not Found.** The resource (ID or reference) does not exist. | +| **05** | **External Error.** Communication failure with the financial network. | +| **XH** | **Internal Error.** Unexpected failure in the AutoPay system. | \ No newline at end of file diff --git a/src/pages/en/autopay/contract-authentication.mdx b/src/pages/en/autopay/contract-authentication.mdx index 2b9e02065..3d090d9ac 100644 --- a/src/pages/en/autopay/contract-authentication.mdx +++ b/src/pages/en/autopay/contract-authentication.mdx @@ -1,65 +1,68 @@ import { HeroPattern } from '@/components/HeroPattern' +import { Note } from "@/components/Note"; -# Contract authentication +# Contract Authentication -For the AutoPay service to interact with your API following the defined contracts, you must authenticate incoming requests. This allows you to identify AutoPay and validate the information so your operations remain secure. The API must use **HTTP Basic Authentication (Basic Auth)**. +Since AutoPay will send requests to your server (Balance and Settlement), you need a mechanism to ensure that **it is really us** and not an attacker. -## API credentials +We use the **HTTP Basic Authentication** standard. -When integrating with AutoPay, you must have the merchant’s `username` and `password` credentials. +## Credentials -- **username:** User that the implementing merchant must **provide to AutoPay** during site configuration. Maximum 60 characters. -- **password:** Password that the implementing merchant must **provide to AutoPay** during site configuration. Maximum 60 characters. +Unlike the transactional API, in contracts **you define the credentials** and we use them. -These credentials will be used by AutoPay to authenticate **against the merchant’s contracts/services**, therefore **the merchant must validate them** on every incoming request. +| Credential | Definition | Restrictions | +| :--- | :--- | :--- | +| **Username** | The username you defined for your integration. | Maximum **60 characters**. | +| **Password** | The associated secure password. | Maximum **60 characters**. | - - These credentials belong to the merchant and must be handled securely. Do not share your credentials in publicly accessible areas such as GitHub, client-side code, or other locations easily accessible to third parties. + + These credentials are configured during the Onboarding process [Service Activation](/autopay/#service-activation). -## Authentication object {{ id: 'authentication-object' }} +## Authentication Object -Authentication is sent in the **headers** of every request that AutoPay makes to the merchant’s contracts. +Authentication is sent in the **headers** of every HTTP request. - Required header. It is sent in the following format: Basic base64(username:password) + Required header. + Sent in the format: Basic base64(username:password) - ```bash {{ 'title': 'Authentication Example (Header)' }} + ```bash {{ 'title': 'Example Authentication (Header)' }} Authorization: Basic bWVyY2hhbnRVc2VyOm1lcmNoYW50UGFzcw== ``` -## How to validate authentication {{ id: 'how-to-validate-authentication' }} - -You must know and prepare the following data: - -**username:** The user you configured for AutoPay to consume your contracts. Maximum 60 characters. +--- -**password:** The password you configured for AutoPay to consume your contracts. Maximum 60 characters. +## How to validate authentication -**Authorization:** Header received in the request, with the following format: -`Authorization: Basic base64(username:password)` +Your server must intercept every incoming request and execute the following security logic **before** processing any business data. -### Basic validation rules +### Validation algorithm -1. Verify that the `Authorization` header exists. -2. Verify that the scheme is `Basic`. -3. Decode the Base64 token and obtain the text `username:password`. -4. Split `username` and `password`. -5. Compare them against your configured credentials. -6. If validation fails, respond with `401 Unauthorized` (optionally with `WWW-Authenticate`). +1. **Check Header:** Confirm that the request has the `Authorization` header. +2. **Check Scheme:** Ensure it starts with the keyword `Basic`. +3. **Decode:** Take the string after the space and Base64 decode it to get `username:password`. +4. **Compare:** Split the text by the colon (`:`) and compare the values with those configured in your environment variables. +5. **Decide:** + * If they match: **Allow access (HTTP 200)**. + * If they do not match: **Reject immediately (HTTP 401 Unauthorized)**. - Basic authentication must always be sent over HTTPS. Base64 does not encrypt, it only encodes. - + **Critical security:** These credentials are private and allow data injection into your system. + + * **HTTPS:** Basic authentication must always travel over encrypted channels. + * **Source code:** **Do not share** your credentials in public access areas like **GitHub**, nor include them in client-side code (Frontend). Always use them via environment variables on your server. + \ No newline at end of file diff --git a/src/pages/en/autopay/contracts/balance.mdx b/src/pages/en/autopay/contracts/balance.mdx index 59f0ee137..6cb281bbd 100644 --- a/src/pages/en/autopay/contracts/balance.mdx +++ b/src/pages/en/autopay/contracts/balance.mdx @@ -4,26 +4,25 @@ import { HeroPattern } from '@/components/HeroPattern' export const apiRefs = ['/autopay/balance'] -## Check amount to be charged {{ id: 'balance', tag: 'POST', label: '{{baseURL}}/autopay/balance' }} +## Query amount to charge {{ id: 'balance', tag: 'POST', label: '/autopay/balance' }} - - **baseURL**: This is the base URL of the client/merchant application, which must be provided by the merchant and configured during the AutoPay onboarding process. - +This endpoint contains the logic for variable charges (`TOTAL_BALANCE` or `MINIMUM_BALANCE`). Before attempting any transaction, AutoPay will query this service to know **how much to charge** at that specific moment. - **Authentication (Basic Authentication):** This endpoint requires authentication via the `Authorization` header. - The merchant must validate the credentials configured for AutoPay on each incoming request. See more at [**Contract authentication**](/autopay/contract-authentication). + **Merchant endpoint:** The base URL (`{{baseURL}}`) corresponds to **your own server**. + You must expose this service on your infrastructure and provide the base URL during the AutoPay onboarding process. - - - This endpoint allows retrieving the amount that must be charged for an AutoPay. - It returns two values: +### Business rules - - **amount:** total amount to be charged in the current cycle. - - **min_amount:** minimum amount required to execute the charge. +1. **Currency:** The currency (`currency`) you respond with must match the one configured in the original autopay. +2. **Zero Balance:** If you respond with a `total` of `0`, AutoPay will understand there is no pending debt and **will not perform any charge**. +3. **Amount Selection:** AutoPay will read the corresponding field based on the autopay configuration: + * If `TOTAL_BALANCE`, it will take the value from `amount`. + * If `MINIMUM_BALANCE`, it will take the value from `min_amount`. - It can be used to validate whether there are pending amounts before starting a payment or automatic reconciliation process. + + -## Client API contracts when integrating AutoPay +# Merchant API Contracts + +Unlike the standard API where you initiate requests, in **Merchant Contracts**, AutoPay **queries your server** to perform critical operations in real-time. + +This section documents the endpoints your infrastructure must expose to enable automated charges and status synchronization. + +## Configuration and Base URL - **baseURL**: This is the base URL of the client/merchant application, which must be provided by the merchant and configured during the AutoPay onboarding process. + **Base URL:** You must provide this URL during onboarding. Please note that AutoPay will automatically append the **/autopay** prefix to all requests, so your router must be configured to support it. + + **Example:** + * Provided Base URL: `https://api.yourcommerce.com` + * Final AutoPay request: `POST https://api.yourcommerce.com/autopay/balance` -To operate AutoPay end to end, the client/merchant must expose a set of their own endpoints that follow the contracts defined in this documentation. +## Services to Implement -These endpoints allow Placetopay to: -- Query the balance/amount to be charged. -- Confirm the application of a payment. -- Receive notifications about the AutoPay lifecycle (activation, update, deactivation, execution results). +To ensure a complete integration, you must expose the following contracts: -In this section, you can find more information about the contracts and examples of each of the services you must implement. +| Resource | Method | Function | +| :--- | :--- | :--- | +| [**/balance**](/autopay/contracts/balance) | `POST` | **Exclusive for Variable Charge.** Allows us to query the amount to charge in each cycle. Necessary if using `TOTAL_BALANCE` or `MINIMUM_BALANCE` models. | +| [**/settlement**](/autopay/contracts/settlement) | `POST` | **Required.** Final confirmation of the approved payment so you can register/settle it in your internal systems. | +| [**/webhook**](/autopay/contracts/webhook) | `POST` | **Required.** Notification channel to receive status updates (creation, cancellation) and charge results. | - - As a client, when implementing these contracts you must implement authentication based on *Basic Authentication*. This allows you to identify us and validate the information so your operations remain secure. See more at [**Contract authentication**](/autopay/contract-authentication). - +--- + +## Technical Requirements + +Your API must comply with the following standards: + +### 1. Security (Basic Auth) +AutoPay will authenticate by sending an `Authorization` header. You define the credentials (`username` and `password`) and must validate them on every incoming request. + +### 2. Format and Transport +* **Protocol:** Strict HTTPS. +* **Format:** JSON (`Content-Type: application/json`). +* **Performance:** Responding in less than 3 seconds is recommended to avoid timeouts. \ No newline at end of file diff --git a/src/pages/en/autopay/contracts/settlement.mdx b/src/pages/en/autopay/contracts/settlement.mdx index 6b61b1658..6045558a7 100644 --- a/src/pages/en/autopay/contracts/settlement.mdx +++ b/src/pages/en/autopay/contracts/settlement.mdx @@ -4,22 +4,27 @@ import { HeroPattern } from '@/components/HeroPattern' export const apiRefs = ['/autopay/settlement'] -## Settle/Confirm a payment {{ id: 'settlement', tag: 'POST', label: '{{baseURl}}/autopay/settlement' }} - - **baseURL**: This is the base URL of the client/merchant application, which must be provided by the merchant and configured during the AutoPay onboarding process. - +## Settle / Confirm Payment {{ id: 'settlement', tag: 'POST', label: '/autopay/settlement' }} - - **Authentication (Basic Authentication):** This endpoint requires authentication via the `Authorization` header. - The merchant must validate the credentials configured for AutoPay on each incoming request. Learn more at [**Contract authentication**](/autopay/contract-authentication). - +This endpoint is the **official closure** of a successful transaction. AutoPay will invoke this service only when a charge has been **APPROVED** by the financial network. + +Your goal here is to receive the confirmation and register the payment in your ERP, database, or accounting system. - Settlement is performed only for transactions that have been successfully processed and are in **APPROVED** status. + **Merchant endpoint:** The base URL (`{{baseURL}}`) corresponds to **your own server**. + You must expose this service on your infrastructure and provide the base URL during the AutoPay onboarding process. + +### Recommended Business Rules + +1. **Idempotency:** Due to network intermittency, you may receive this confirmation more than once for the same transaction. Your system must validate if the payment was already settled and respond with `200 OK` without duplicating the record. +2. **Amount Validation:** Verify that `transaction.amount.total` matches what you expected to charge. +3. **Fast Response:** This process is synchronous. Respond as quickly as possible (`< 3s`) to complete the cycle. + +--- + - This endpoint is used to confirm a previously processed payment by sending the transaction details. + **Important:** + 1. **Approved** transactions are sent exclusively via [Settlement](/autopay/contracts/settlement). + 2. Although this endpoint is part of Contracts and there is [Contracts Authentication](/autopay/contracts/authentication), the mechanism to validate message integrity is the **Digital Signature** described below. +
-### Webhook validation {{ id: 'validating-webhooks' }} +### Available events {{ id: 'event-types' }} -Since the notification arrives from a system external to your servers, it is important to validate that the message is authentic and comes from a trusted source. To do this, a signature included in the message is used, which was generated using the `secretKey` provided by the site and known only by the involved systems. To learn more about your `secretKey`, see the [Authentication](/autopay/authentication) documentation. +| Event | Description | +| :--- | :--- | +| `AUTOPAY_CREATED` | Registration finished and autopay is active. | +| `AUTOPAY_UPDATED` | Payment method or rules were updated. | +| `AUTOPAY_TRANSACTION_FAILED` | Automatic charge attempt failed (e.g., insufficient funds). | +| `AUTOPAY_CANCELED` | Autopay has been canceled. | -To start your validation, you must have the `secretKey` associated with your merchant available. +## Security validation (signatures) {{ id: 'security-validation' }} -**Identify the algorithm**: To identify the algorithm used in the signature, keep the following in mind: +It is **critical** to verify that the notification comes from Placetopay. We digitally sign every message. You must replicate the signing process on your server and compare the result. -- If the `signature` field starts with the `sha256:` prefix, then the signature was generated using SHA-256. +**Validation example:** -**Extract the raw signature**: Once the algorithm is identified, locate the `signature` field. +Suppose your `secretKey` is `ABC123example456trankey+789abc012def3456ABC=` and you receive: -- If the `sha256:` prefix is present, you must remove it to obtain the raw signature to be compared. We will call this `receivedSignature`. +```json {{ title: '1. Received Payload' }} +{ + "id": "111111-2222-3333-4444-555555555555", + "type": "AUTOPAY_TRANSACTION_FAILED", + "date": "2023-01-01 12:00:00", + "signature": "sha256:a1b2c3d4e5..." +} +``` -**Generate your own signature**: Once the algorithm is identified, you must generate your own signature using the following formula: +### Step-by-step process -- For SHA-256: `SHA-256(id + type + date + secretKey)` +1. **Concatenate:** Join `id`, `type`, `date`, and your `secretKey` (in this exact order, without spaces or separators). + > String = `111111-2222-3333-4444-555555555555` + `AUTOPAY_TRANSACTION_FAILED` + `2023-01-01 12:00:00` + `ABC123example456trankey+789abc012def3456ABC=` -This will produce the signature generated by your system, which we will call `generatedSignature`. Note that the data required to generate the signature is found in the webhook details. See more in the [Webhook contract](/autopay/contracts/webhook). +2. **Hash:** Apply the **SHA-256** algorithm to the resulting string. -**Compare signatures**: Finally, compare the signature you generated (`generatedSignature`) with the signature received in the message (`receivedSignature`). If both signatures are equal, then the notification is authentic and you can proceed to update the session status in your system. +3. **Compare:** If your hash matches the received `signature` (ignoring the `sha256:` prefix), the request is authentic. - When receiving a notification, it is recommended to call the [AutoPay query API](/autopay/autopay-api) to obtain more details about the change, - so that you always have accurate and up-to-date information. + If the signature does not match, respond with **HTTP 400** and ignore the message. **Never** expose your `secretKey` in the frontend or public repositories. -## Notifications {{ id: 'webhook', tag: 'POST', label: '{{baseURl}}/autopay/webhook' }} +--- - - **baseURL**: This is the base URL of the client/merchant application, which must be provided by the merchant and configured during the AutoPay onboarding process. +## Webhook structure {{ id: 'webhook', tag: 'POST', label: '/autopay/webhook' }} + + + **Recommendation:** The webhook is strictly an event notification. To guarantee you have the latest and most detailed information, it is recommended to query the [Search AutoPay](/autopay/api/search) API using the received `id`. + - You must expose an endpoint according to the following contract. AutoPay will send notifications to this endpoint every time an autopay is created, the payment method is updated, an autopay is canceled, or a payment fails. - + +# How AutoPay works + +AutoPay is a comprehensive solution that allows you to automate recurring charges by delegating both security (PCI tokenization) and scheduled execution of charges to Placetopay. + +Unlike a traditional subscription, AutoPay supports **variable charge models** (such as utility billing or consumption) and **fixed models** (such as memberships), automatically managing retries and payment method updates. + +## Unified integration model + +Instead of coordinating interface creation, card tokenization, and charging rule configuration separately, your server only needs to communicate with the Gateway API. + +The Gateway takes charge of **centralizing** the operation: + +1. **Interface Management:** Automatically generates the secure WebCheckout session for the user to enter their data. +2. **Security (PCI):** Ensures sensitive data is captured and tokenized directly on our servers, keeping your merchant scope out of complex PCI audits. +3. **Charge Scheduling:** Registers and activates recurrence rules (frequency and amounts) in the AutoPay engine to ensure future charges are executed on time. + +## Key concepts + +To integrate AutoPay, it is necessary to understand two configurations that define the contract: + +### 1. Recurring +Defines the contract's "frequency and lifespan" (Periodicity, Interval, and Validity Dates). It is fundamental to configure these parameters correctly so the billing engine works as expected. + +👉 [**See Recurring configuration guide**](/autopay/recurring-setup) + +### 2. Charge type +Defines how the amount to be charged is calculated in each cycle. AutoPay allows everything from fixed charges (`FIXED`) to real-time queries of total debt (`TOTAL_BALANCE`) or minimum payments (`MINIMUM_BALANCE`) against your system. + +👉 [**See Charge Types detail**](/autopay/charge-types) + +## Integration lifecycle + +The following describes the flow of creating an AutoPay (Setup) and subsequent execution. + + + +### Process phases + +1. **Initialization:** Your server consumes the Gateway API (`POST /autopay/session`) sending recurrence rules. The system returns a redirection URL. +2. **Capture and tokenization:** The user is redirected to WebCheckout. There, they select their payment method, accept terms, and the card is securely tokenized. +3. **Confirmation:** Upon completion, the user returns to your site. You must query the session status to confirm the AutoPay was created (`APPROVED`). +4. **Scheduled execution (future):** + * The AutoPay engine detects when the next charge is due. + * If it is a variable amount, it queries your Balance API. + * It executes the transaction using the stored token. + * It notifies you of the result via Webhook (`AUTOPAY_TRANSACTION_FAILED` or successful). + +### Editing an AutoPay (update) +What happens if the user's card expires? The flow to **edit** a subscription reuses the same integration: + +1. Create a new session in the Gateway (`POST /autopay/session`) specifying the action `EDIT` and the `id` of the existing AutoPay. +2. Redirect the user to WebCheckout. +3. The user updates their payment details. +4. Upon completion, the system updates the associated token without losing the subscription history. + +## What's next? + +* [Create an AutoPay Session](/autopay/api/session#create-a-session) +* [Implement client contracts](/autopay/contracts) (For variable charges) +* [AutoPay management](/autopay/api/session/#query-a-session) (Query and cancellation) \ No newline at end of file diff --git a/src/pages/en/autopay/index.mdx b/src/pages/en/autopay/index.mdx index 758748098..25ce2d2e6 100644 --- a/src/pages/en/autopay/index.mdx +++ b/src/pages/en/autopay/index.mdx @@ -1,28 +1,45 @@ +import { AutopayBenefits } from '@/components/AutopayBenefits' +import { AutoPayDocsList } from '@/components/AutoPayDocsList' +import { AutoPayRequirements } from '@/components/AutoPayRequirements' import { HeroPattern } from '@/components/HeroPattern' -# AutoPay (BETA) +# PlacetoPay AutoPay (BETA) -**AutoPay Placetopay** is an automatic payment service that allows merchants to enable recurring or scheduled charges using a payment method previously authorized by the user (card or compatible bank account), without requiring manual intervention for each transaction. The solution includes a guided enrollment experience for the end user, API services for the merchant to create and manage autopay sessions, and execution processes that trigger charges according to the defined configuration. +**PlacetoPay AutoPay** is an automated payment service that allows merchants to enable recurring or scheduled charges using a payment method previously authorized by the user. {{ className: 'lead' }} ---- -## Why is it useful? +The solution includes a guided enrollment experience for the end user, API services for merchants to create and manage AutoPay sessions, and charge execution processes based on the defined configuration. + + + **Important:** This feature must be explicitly enabled on your site. + + +## Service activation {{ id: 'service-activation' }} -- **Improved conversion and retention:** reduces friction in repetitive payments (services, insurance, telcos, subscriptions). -- **Operational automation:** eliminates manual processes and reminders; charges are executed on the agreed dates. -- **Control and transparency:** the merchant can review, adjust, or cancel their autopays. -- **Security and compliance:** use of tokenized payment methods and PCI guidelines, with authentication options (e.g., 3DS 3RI when applicable). -- **Integrability:** in addition to direct checkout integration, the ecosystem exposes endpoints for creation/update/deactivation and querying of sessions/autopays; webhooks are also supported to notify relevant events. +To access this service, please contact our Post-Sales team through any of the following channels, and we will be happy to assist you: + +* **Email:** [servicioposventa@placetopay.com](mailto:servicioposventa@placetopay.com) +* **Website:** [www.placetopay.com](https://www.placetopay.com) +* **Phone:** (+57) 604 444 2310 / (+57) 317 431 0510 +* **Address:** Carrera 65 # 45 - 20, Office 430. Medellín, Colombia. --- -## How does it work? -1) [**AutoPay API:**](/en/autopay/api) -As a client, you can interact with the AutoPay API to perform actions on your users’ autopays, such as creation, querying, updating, and deactivation. +## AutoPay Benefits {{ id: 'autopay-benefits' }} -2) [**Direct client integration:**](/en/autopay/contracts) -As a client, your application can expose certain endpoints so AutoPay can interact with them, obtain the necessary invoice information to process a payment ([Balance](/autopay/contracts/balance)), record the results of each payment ([Settlement](/autopay/contracts/settlement)), and receive updated information about the autopay status ([Webhooks](/autopay/contracts/webhook)). + -In this documentation you will find all the information required to integrate AutoPay into your platform. --- + +## How to use this documentation {{ id: 'how-to-use-this-documentation' }} + +Here you will find detailed guides, API references, and code examples to integrate and configure AutoPay into your platform quickly and securely. + + + +## Prerequisites {{ id: 'prerequisites' }} + +For a successful and smooth integration, we recommend: + + \ No newline at end of file diff --git a/src/pages/en/autopay/recurring-setup.mdx b/src/pages/en/autopay/recurring-setup.mdx new file mode 100644 index 000000000..3f401df8a --- /dev/null +++ b/src/pages/en/autopay/recurring-setup.mdx @@ -0,0 +1,85 @@ +import { HeroPattern } from '@/components/HeroPattern' +import RecurringSequence from "@/components/react-flow/SequenceDiagram/Diagrams/AutoPay/en/RecurringSequence" + + + +# Recurring rules + +The `recurring` object is the logic core of the automation. It defines **when** it is charged, and **until when** the contract remains active. + +## Object structure + +```json + "recurring": { + "type": "TOTAL_BALANCE", + "periodicity": "M", + "interval": 1, + "nextPayment": "2025-06-03", + "dueDate": "2025-08-03", + "notificationUrl": "https://merchant.test/notification" + } +``` + +## Property definitions + + + + **Required.** Defines the charging modality. + * `FIXED`: Fixed amount (Subscriptions). + * `TOTAL_BALANCE`: Charges the total debt queried from your API. + * `MINIMUM_BALANCE`: Charges the minimum payment queried from your API. + + [See Charge Types detail](/autopay/charge-types) + + + + **Required.** Time unit for the frequency. + * `D`: Days + * `W`: Weeks + * `M`: Months + * `Y`: Years + + + + **Required.** Multiplier for the periodicity. + Example: To charge "Every 2 Weeks", use `periodicity: W` and `interval: 2`. + + + + **Required.** Format `YYYY-MM-DD`.
+ It is the trigger/start date. The system will not perform any charge before this date. + * **On creation:** Defines when the **first** charge will take place. + * **Automatic:** After each successful charge, the system automatically updates this field by adding the configured frequency. +
+ + + **Optional.** Format `YYYY-MM-DD`.
+ Acts as an expiration date or upper limit. If the calculation of the next charge results in a date after this limit, the AutoPay is marked as **Finished** and stops processing charges. +
+ + + **Required.** Secure URL (`https`).
+ Endpoint where your server will receive notifications (Webhooks) whenever a charge, failure, or status change occurs in this autopay. +
+
+ +--- + +## Date calculation logic + +The AutoPay engine (Scheduler) runs a daily process. To determine the **next charge** date, the system follows strict logic to ensure the autopay remains valid. + +The following diagram illustrates how the `recurring` object is updated after a successful charge: + + + +### Common frequency examples + +Although the logic is flexible, here are the most used combinations: + +| Desired Frequency | JSON Configuration | Logical Result | +| :--- | :--- | :--- | +| **Monthly** | `"periodicity": "M", "interval": 1` | Charges every month on the same day (e.g., Jan 5, Feb 5). | +| **Quarterly** | `"periodicity": "M", "interval": 3` | Charges every 3 months. | +| **Bi-weekly** | `"periodicity": "W", "interval": 2` | Charges every 2 weeks (e.g., every other Friday). | +| **Annual** | `"periodicity": "Y", "interval": 1` | Charges once a year. | \ No newline at end of file