Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.cobrix.co/llms.txt

Use this file to discover all available pages before exploring further.

Node.js / TypeScript

Configuración

// config.ts
export const config = {
  apiKey: process.env.COBRIX_API_KEY!,
  baseUrl:
    process.env.NODE_ENV === 'production'
      ? 'https://api.cobrix.co'
      : 'https://api-staging.cobrix.co',
}

Cliente

// cobrix.ts
import { randomUUID } from 'node:crypto'
import { config } from './config'

async function request<T>(method: string, path: string, body?: unknown): Promise<T> {
  const headers: Record<string, string> = {
    'X-API-Key': config.apiKey,
  }

  if (body) {
    headers['Content-Type'] = 'application/json'
    headers['Idempotency-Key'] = randomUUID()
  }

  const response = await fetch(`${config.baseUrl}${path}`, {
    method,
    headers,
    body: body ? JSON.stringify(body) : undefined,
  })

  if (!response.ok) {
    const error = await response.json().catch(() => ({}))
    throw new Error(`Cobrix API ${response.status}: ${error.message ?? response.statusText}`)
  }

  return response.json()
}

export const cobrix = {
  createHostedPayment: (body: HostedPaymentInput) =>
    request<Payment>('POST', '/api/external/payments', body),
  createDirectPayment: (body: DirectPaymentInput) =>
    request<Payment>('POST', '/api/external/payments/direct', body),
  getPayment: (id: string) =>
    request<Payment>('GET', `/api/external/payments/${id}`),
  listPayments: (query = '') =>
    request<PaymentList>('GET', `/api/external/payments${query ? `?${query}` : ''}`),
  cancelPayment: (id: string) =>
    request<Payment>('DELETE', `/api/external/payments/${id}`),
}

export interface Payment {
  id: string
  status: 'pending' | 'processing' | 'completed' | 'failed' | 'expired' | 'canceled'
  mode: 'hosted' | 'direct'
  amountMinor: number
  currency: 'VES' | 'USD' | 'CRC'
  checkoutUrl?: string
  invoiceId?: string
  paymentId?: string
  externalReference?: string
  expiresAt: string
  completedAt?: string
  createdAt: string
}

export interface HostedPaymentInput {
  customerEmail: string
  customerName?: string
  amountMinor: number
  currency: 'VES' | 'USD' | 'CRC'
  description?: string
  callbackUrl?: string
  externalReference?: string
  metadata?: Record<string, unknown>
}

export interface DirectPaymentInput extends HostedPaymentInput {
  paymentMethod: string
  paymentDetails?: Record<string, unknown>
}

export interface PaymentList {
  payments: Payment[]
  total: number
  page: number
  limit: number
}

Uso

// ejemplo hosted
const payment = await cobrix.createHostedPayment({
  customerEmail: '[email protected]',
  customerName: 'Jane Doe',
  amountMinor: 15000,
  currency: 'VES',
  description: 'Suscripción mensual',
  callbackUrl: 'https://tu-app.com/webhooks/cobrix',
  externalReference: order.id,
})

res.redirect(payment.checkoutUrl!)

Webhook handler (Express)

import express from 'express'

const router = express.Router()

router.post('/cobrix', express.json(), async (req, res) => {
  const event = req.body
  res.status(200).json({ received: true })

  if (event.eventType !== 'external_payment.completed') return

  const paymentId = event.payload.id
  if (await db.webhookEvents.exists(paymentId)) return
  await db.webhookEvents.create({ id: paymentId })

  const fresh = await cobrix.getPayment(paymentId)
  if (fresh.status === 'completed' && fresh.externalReference) {
    await orderService.markAsPaid(fresh.externalReference, fresh)
  }
})

export default router

Python

Cliente

# cobrix.py
import os
import uuid
import requests

BASE_URL = (
    'https://api.cobrix.co'
    if os.environ.get('APP_ENV') == 'production'
    else 'https://api-staging.cobrix.co'
)
API_KEY = os.environ['COBRIX_API_KEY']


def _request(method: str, path: str, body: dict | None = None):
    headers = {'X-API-Key': API_KEY}
    if body is not None:
        headers['Content-Type'] = 'application/json'
        headers['Idempotency-Key'] = str(uuid.uuid4())

    response = requests.request(method, f'{BASE_URL}{path}', headers=headers, json=body)
    response.raise_for_status()
    return response.json()


def create_hosted_payment(**body):
    return _request('POST', '/api/external/payments', body)


def create_direct_payment(**body):
    return _request('POST', '/api/external/payments/direct', body)


def get_payment(payment_id: str):
    return _request('GET', f'/api/external/payments/{payment_id}')


def cancel_payment(payment_id: str):
    return _request('DELETE', f'/api/external/payments/{payment_id}')

Uso

payment = create_hosted_payment(
    customerEmail='[email protected]',
    amountMinor=15000,
    currency='VES',
    callbackUrl='https://tu-app.com/webhooks/cobrix',
    externalReference=str(order.id),
)

print('Redirect to:', payment['checkoutUrl'])

Webhook handler (Flask)

from flask import Blueprint, request, jsonify
import cobrix

webhooks = Blueprint('webhooks', __name__)

@webhooks.route('/cobrix', methods=['POST'])
def cobrix_webhook():
    event = request.get_json()
    response = jsonify({'received': True}), 200

    if event.get('eventType') != 'external_payment.completed':
        return response

    payment_id = event['payload']['id']
    if db.webhook_seen(payment_id):
        return response
    db.record_webhook(payment_id)

    fresh = cobrix.get_payment(payment_id)
    if fresh['status'] == 'completed' and fresh.get('externalReference'):
        order_service.mark_paid(fresh['externalReference'], fresh)

    return response

cURL · flujo completo

BASE=https://api-staging.cobrix.co
KEY=sk_test_acme_...

# 1. Crear pago hosted
curl -s -X POST "$BASE/api/external/payments" \
  -H "Content-Type: application/json" \
  -H "X-API-Key: $KEY" \
  -H "Idempotency-Key: $(uuidgen)" \
  -d '{
    "customerEmail": "[email protected]",
    "amountMinor": 15000,
    "currency": "VES",
    "description": "Order #123"
  }' | jq .

# 2. Consultar estado
curl -s "$BASE/api/external/payments/{id}" \
  -H "X-API-Key: $KEY" | jq .

# 3. Listar pendientes
curl -s "$BASE/api/external/payments?status=pending&limit=10" \
  -H "X-API-Key: $KEY" | jq .

# 4. Cancelar pago pendiente
curl -s -X DELETE "$BASE/api/external/payments/{id}" \
  -H "X-API-Key: $KEY" | jq .

# 5. Crear pago directo
curl -s -X POST "$BASE/api/external/payments/direct" \
  -H "Content-Type: application/json" \
  -H "X-API-Key: $KEY" \
  -H "Idempotency-Key: $(uuidgen)" \
  -d '{
    "customerEmail": "[email protected]",
    "amountMinor": 15000,
    "currency": "VES",
    "paymentMethod": "pago_movil",
    "description": "POS sale #456"
  }' | jq .