API de cobros online
Cobrá con CWallet en tu tienda.
Un endpoint para empezar.
Creás un checkout en pesos desde tu servidor, mandás al comprador al link de pago y te avisamos con un webhook firmado cuando pagó. Devoluciones totales o parciales, modo prueba y 1% de comisión por pago.
Base URL
https://getcwallet.app/api/v1
Claves
cwt_test_… (prueba) y cwt_live_… (real). Solo desde tu servidor.
Reintentos seguros
Mandá Idempotency-Key en cada POST: repetir no crea dos cobros.
Cómo funciona
- Tu servidor crea el checkout con el monto del pedido (en pesos o la moneda que uses).
- Redirigís al comprador a
url. Paga con su cuenta CWallet (si no tiene, la crea en un minuto) o escaneando el QR desde el celular. - Vuelve a tu
success_urlcon?checkout_id=…. - Confirmás el pedido con el webhook
checkout.paid(o consultandoGET /checkouts/{id}). Nunca confíes solo en la vuelta del navegador.
| POST | /checkouts | Crear un checkout y obtener el link de pago |
| GET | /checkouts | Listar (limit, status, order_id, starting_after) |
| GET | /checkouts/{id} | Consultar un checkout |
| POST | /checkouts/{id}/cancel | Cancelar uno abierto |
| POST | /checkouts/{id}/refunds | Devolver total o parcial |
| POST | /checkouts/{id}/simulate | Modo prueba: simular el pago |
Crear (curl)
# 1) Crear el checkout desde tu servidor (nunca desde el navegador)
curl -X POST https://getcwallet.app/api/v1/checkouts \
-H "Authorization: Bearer $CWALLET_SECRET_KEY" \
-H "Idempotency-Key: pedido-1234" \
-H "Content-Type: application/json" \
-d '{"amount":"25000","currency":"ARS","order_id":"1234",
"success_url":"https://mitienda.com/gracias","cancel_url":"https://mitienda.com/carrito"}'Respuesta 201
{
"id": "6b0c…", "object": "checkout", "livemode": false, "status": "open",
"amount": "25000", "currency": "ARS", "token": "USDT", "token_amount": "15.58", "fx_rate": "1605.085",
"order_id": "1234", "url": "https://getcwallet.app/checkout/6b0c…",
"success_url": "https://mitienda.com/gracias", "cancel_url": "https://mitienda.com/carrito",
"fee": "0", "net_amount": "15.58", "amount_refunded": "0", "refunds": [],
"created_at": "…", "expires_at": "…", "paid_at": null
}Código para tu plataforma
Node.js (Express)
// npm i express — Node 18+ (fetch incluido)
import express from 'express';
import crypto from 'node:crypto';
// rawBody: the request body exactly as received (string), before JSON.parse.
export function verifyCWalletWebhook(rawBody: string, header: string, secret: string): boolean {
const parts = Object.fromEntries(header.split(',').map(p => p.split('=') as [string, string]));
const t = Number(parts.t);
if (!parts.v1 || !Number.isFinite(t) || Math.abs(Date.now() / 1000 - t) > 300) return false; // 5 minutes
const expected = crypto.createHmac('sha256', secret).update(`${parts.t}.${rawBody}`).digest('hex');
return parts.v1.length === expected.length && crypto.timingSafeEqual(Buffer.from(parts.v1), Buffer.from(expected));
}
const app = express();
const KEY = process.env.CWALLET_SECRET_KEY; // cwt_test_… o cwt_live_…
const WEBHOOK_SECRET = process.env.CWALLET_WEBHOOK_SECRET;
app.post('/pagar/:orderId', async (req, res) => {
const order = await db.orders.find(req.params.orderId); // tu base
const r = await fetch('https://getcwallet.app/api/v1/checkouts', {
method: 'POST',
headers: { Authorization: `Bearer ${KEY}`, 'Content-Type': 'application/json', 'Idempotency-Key': `order-${order.id}` },
body: JSON.stringify({ amount: order.total.toFixed(2), currency: 'ARS', order_id: String(order.id),
success_url: 'https://mitienda.com/gracias', cancel_url: 'https://mitienda.com/carrito' }),
});
const checkout = await r.json();
if (!r.ok) return res.status(502).json(checkout.error);
res.redirect(303, checkout.url);
});
app.post('/webhooks/cwallet', express.text({ type: '*/*' }), async (req, res) => {
if (!verifyCWalletWebhook(req.body, req.get('CWallet-Signature') ?? '', WEBHOOK_SECRET)) return res.sendStatus(401);
const event = JSON.parse(req.body);
if (event.type === 'checkout.paid') await db.orders.markPaid(event.data.object.order_id, event.data.object.id);
res.sendStatus(200); // respondé rápido; reintentamos si no es 2xx
});Next.js
// app/api/cwallet/checkout/route.ts — Next.js App Router
export async function POST(req: Request) {
const { orderId, total } = await req.json(); // validá el total contra tu base
const r = await fetch('https://getcwallet.app/api/v1/checkouts', {
method: 'POST',
headers: { Authorization: `Bearer ${process.env.CWALLET_SECRET_KEY}`, 'Content-Type': 'application/json', 'Idempotency-Key': `order-${orderId}` },
body: JSON.stringify({ amount: String(total), currency: 'ARS', order_id: String(orderId),
success_url: `${process.env.SITE_URL}/gracias`, cancel_url: `${process.env.SITE_URL}/carrito` }),
});
const checkout = await r.json();
return Response.json(r.ok ? { url: checkout.url } : checkout, { status: r.ok ? 200 : 502 });
}
// app/api/cwallet/webhook/route.ts
import crypto from 'node:crypto';
// rawBody: the request body exactly as received (string), before JSON.parse.
export function verifyCWalletWebhook(rawBody: string, header: string, secret: string): boolean {
const parts = Object.fromEntries(header.split(',').map(p => p.split('=') as [string, string]));
const t = Number(parts.t);
if (!parts.v1 || !Number.isFinite(t) || Math.abs(Date.now() / 1000 - t) > 300) return false; // 5 minutes
const expected = crypto.createHmac('sha256', secret).update(`${parts.t}.${rawBody}`).digest('hex');
return parts.v1.length === expected.length && crypto.timingSafeEqual(Buffer.from(parts.v1), Buffer.from(expected));
}
export async function POST(req: Request) {
const raw = await req.text();
if (!verifyCWalletWebhook(raw, req.headers.get('cwallet-signature') ?? '', process.env.CWALLET_WEBHOOK_SECRET!)) return new Response(null, { status: 401 });
const event = JSON.parse(raw);
if (event.type === 'checkout.paid') { /* marcar pedido event.data.object.order_id como pagado */ }
return new Response(null, { status: 200 });
}PHP
<?php
// Crear checkout
$ch = curl_init('https://getcwallet.app/api/v1/checkouts');
curl_setopt_array($ch, [
CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('CWALLET_SECRET_KEY'), 'Content-Type: application/json', 'Idempotency-Key: order-' . $order_id],
CURLOPT_POSTFIELDS => json_encode(['amount' => number_format($total, 2, '.', ''), 'currency' => 'ARS', 'order_id' => (string)$order_id,
'success_url' => 'https://mitienda.com/gracias', 'cancel_url' => 'https://mitienda.com/carrito']),
]);
$checkout = json_decode(curl_exec($ch), true);
header('Location: ' . $checkout['url'], true, 303);
// Webhook
// $raw = file_get_contents('php://input'); $header = $_SERVER['HTTP_CWALLET_SIGNATURE'] ?? '';
function cwallet_verify(string $raw, string $header, string $secret): bool {
parse_str(str_replace(',', '&', $header), $p);
if (empty($p['t']) || empty($p['v1']) || abs(time() - (int)$p['t']) > 300) return false;
$expected = hash_hmac('sha256', $p['t'] . '.' . $raw, $secret);
return hash_equals($expected, $p['v1']);
}
$raw = file_get_contents('php://input');
if (!cwallet_verify($raw, $_SERVER['HTTP_CWALLET_SIGNATURE'] ?? '', getenv('CWALLET_WEBHOOK_SECRET'))) { http_response_code(401); exit; }
$event = json_decode($raw, true);
if ($event['type'] === 'checkout.paid') { /* marcar pedido $event['data']['object']['order_id'] */ }
http_response_code(200);Python (Flask)
# pip install requests flask
import os, json, requests
from flask import Flask, request, redirect, abort
import hmac, hashlib, time
def verify_cwallet(raw_body: bytes, header: str, secret: str) -> bool:
parts = dict(p.split("=", 1) for p in header.split(","))
t, v1 = parts.get("t"), parts.get("v1")
if not t or not v1 or abs(time.time() - int(t)) > 300:
return False
expected = hmac.new(secret.encode(), f"{t}.".encode() + raw_body, hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, v1)
app = Flask(__name__)
KEY = os.environ["CWALLET_SECRET_KEY"]
@app.post("/pagar/<order_id>")
def pagar(order_id):
total = get_order_total(order_id) # tu base
r = requests.post("https://getcwallet.app/api/v1/checkouts", timeout=15,
headers={"Authorization": f"Bearer {KEY}", "Idempotency-Key": f"order-{order_id}"},
json={"amount": f"{total:.2f}", "currency": "ARS", "order_id": order_id,
"success_url": "https://mitienda.com/gracias", "cancel_url": "https://mitienda.com/carrito"})
r.raise_for_status()
return redirect(r.json()["url"], code=303)
@app.post("/webhooks/cwallet")
def webhook():
if not verify_cwallet(request.get_data(), request.headers.get("CWallet-Signature", ""), os.environ["CWALLET_WEBHOOK_SECRET"]):
abort(401)
event = json.loads(request.get_data())
if event["type"] == "checkout.paid":
mark_paid(event["data"]["object"]["order_id"])
return "", 200WooCommerce
Plugin oficial 2.0.0: https://getcwallet.app/downloads/cwallet-woocommerce-2.0.0.zip
1. Plugins → Añadir nuevo → Subir plugin → elegí el .zip y activalo.
2. WooCommerce → Ajustes → Pagos → CWallet: pegá la clave de prueba (cwt_test_…) y la real (cwt_live_…).
3. En getcwallet.app/dashboard/business cargá la URL de webhook que muestra el plugin (…/wp-json/cwallet/v2/webhook)
y copiá cada secret al plugin.
4. Compra de prueba → "Simular pago aprobado". Después desactivá el modo prueba.
Incluye: moneda de la tienda (ARS, USD…), USDT o CWT a elección del comprador, devoluciones desde el pedido y HPOS.Tiendanube
App de Tiendanube: CWallet aparece como medio de pago en el checkout de la tienda.
1. En getcwallet.app/dashboard/business → Integraciones → "Conectar mi tienda" y aceptá los permisos en Tiendanube.
2. Listo: el comprador elige CWallet, paga en la página de CWallet y vuelve a la tienda; el pedido queda pagado solo.
(Disponible cuando Tiendanube termine de habilitar la app. Mientras tanto: links de pago o la API desde tu backend.)Webhooks
Configurá la URL en el panel (una para prueba y otra para real). Cada aviso trae CWallet-Signature: t=…,v1=…: HMAC-SHA256 de t + "." + body con tu secret. Rechazá firmas con más de 5 minutos. Reintentamos hasta 6 veces; un evento puede llegar dos veces, usá su id.
| checkout.paid | El comprador pagó. Marcá el pedido como pagado. |
| checkout.expired | Venció sin pagarse. |
| checkout.cancelled | Lo cancelaste desde la API. |
| refund.succeeded | Se hizo una devolución (data.object es el reembolso, con el checkout). |
Node
import crypto from 'node:crypto';
// rawBody: the request body exactly as received (string), before JSON.parse.
export function verifyCWalletWebhook(rawBody: string, header: string, secret: string): boolean {
const parts = Object.fromEntries(header.split(',').map(p => p.split('=') as [string, string]));
const t = Number(parts.t);
if (!parts.v1 || !Number.isFinite(t) || Math.abs(Date.now() / 1000 - t) > 300) return false; // 5 minutes
const expected = crypto.createHmac('sha256', secret).update(`${parts.t}.${rawBody}`).digest('hex');
return parts.v1.length === expected.length && crypto.timingSafeEqual(Buffer.from(parts.v1), Buffer.from(expected));
}PHP
<?php
// $raw = file_get_contents('php://input'); $header = $_SERVER['HTTP_CWALLET_SIGNATURE'] ?? '';
function cwallet_verify(string $raw, string $header, string $secret): bool {
parse_str(str_replace(',', '&', $header), $p);
if (empty($p['t']) || empty($p['v1']) || abs(time() - (int)$p['t']) > 300) return false;
$expected = hash_hmac('sha256', $p['t'] . '.' . $raw, $secret);
return hash_equals($expected, $p['v1']);
}Python
import hmac, hashlib, time
def verify_cwallet(raw_body: bytes, header: str, secret: str) -> bool:
parts = dict(p.split("=", 1) for p in header.split(","))
t, v1 = parts.get("t"), parts.get("v1")
if not t or not v1 or abs(time.time() - int(t)) > 300:
return False
expected = hmac.new(secret.encode(), f"{t}.".encode() + raw_body, hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, v1)Referencia completa
CWallet — API de cobros online (base https://getcwallet.app/api/v1)
Autenticación: Authorization: Bearer cwt_test_… (prueba) o cwt_live_… (real). Usala solo desde tu servidor.
Idempotency-Key (header, recomendado en POST): reintentar con la misma clave devuelve el mismo resultado.
Límite: 300 solicitudes por minuto por clave. Comisión: 1% de cada pago real.
POST /checkouts
amount (string, obligatorio) — en currency. Hasta 2 decimales en moneda local, 6 en CWT/USDT.
currency — ARS (por defecto), USD, BOB, PYG, UYU, CLP, COP, PEN, CWT o USDT. Moneda local se convierte con la cotización del momento.
token — opcional. Sin token, el comprador elige con qué pagar: USDT o CWT (si tu comercio acepta CWT; así también usa regalos de empresas).
Mandá USDT o CWT para aceptar solo esa moneda. La respuesta trae payment_methods y, una vez pagado, token = la moneda usada.
order_id (≤100), description (≤140), metadata (≤20 claves, valores simples)
customer_email — si lo mandás y el comprador no paga en 30 minutos, le enviamos un recordatorio con el link (una sola vez).
El comprador que paga recibe el comprobante por email.
success_url / cancel_url — https (en prueba también http://localhost). Volvemos con ?checkout_id=…
expires_in_minutes — 15 a 4320 (por defecto 60)
→ 201 checkout { id, status: open|paid|expired|cancelled, url, amount, currency, token, token_amount, fx_rate, fee, net_amount, … }
GET /checkouts?limit=20&status=paid&order_id=1234&starting_after=<id> → { data: [...], has_more }
GET /checkouts/{id}
POST /checkouts/{id}/cancel — solo abiertos
POST /checkouts/{id}/refunds — { amount?, reason? } en la moneda del checkout; sin amount devuelve todo lo que queda
POST /checkouts/{id}/simulate — solo modo prueba: lo marca como pagado y dispara checkout.paid
Errores: { error: { type, code, message } } con HTTP 400/401/402/404/409/429/5xx.
Webhooks: checkout.paid, checkout.expired, checkout.cancelled, refund.succeeded. Cuerpo: { id, type, created, livemode, data: { object } }.
Firma: header CWallet-Signature: t=<unix>,v1=<HMAC-SHA256(secret, t + "." + body)>. Rechazá firmas de más de 5 minutos.
Reintentos: hasta 6 intentos (1 min, 5 min, 30 min, 2 h, 6 h, 24 h). Respondé 2xx rápido y procesá aparte; un mismo evento puede llegar dos veces (usá id).¿Usás la API anterior (/create-payment-intent, solo USDT y app móvil)? Sigue funcionando; para tiendas online recomendamos los checkouts.