PayForce
API v1 · 2025-01

Integra PayForce en 1 minuto

Script embebible, API REST y plugin WooCommerce. Pagos con redirección segura y webhooks HMAC para tu tienda.

Ejemplo en 1 minuto

Un script, un botón con data-payforce-key y listo. Para backends usa la misma API REST.

<script src="https://payforce.co/js/v1.js"></script>
<button
  data-payforce-key="pf_live_xxxxx"
  data-amount="4999"
  data-description="Mi producto">
  Pagar 49,99€
</button>

Referencia API · Sesiones de pago

POSThttps://payforce.co/api/v1/sessionsCheckout hosted

Crea una sesión y redirige al cliente a checkout_url (alias url). Importes en céntimos.

curl -X POST https://payforce.co/api/v1/sessions \
  -H "Authorization: Bearer pf_live_..." \
  -H "Content-Type: application/json" \
  -d '{"amount":4999,"currency":"eur","description":"Pedido #123","success_url":"https://tu-tienda.com/ok","cancel_url":"https://tu-tienda.com/ko"}'

# 201 Created
{
  "id": "...",
  "checkout_url": "https://payforce.co/checkout/TOKEN",
  "url": "https://payforce.co/checkout/TOKEN",
  "amount": 4999,
  "currency": "eur",
  "status": "open",
  "expires_at": "...",
  "created_at": "..."
}

Descarga el plugin WooCommerce: payforce-woocommerce.php

Introducción

La API de PayForce sigue los estándares REST. Las solicitudes deben enviarse conContent-Type: application/json. Todas las respuestas devuelven JSON con el headerX-PayForce-Version: 2025-01.

Base URL

https://payforce.io/api/v1

Versión

2025-01

Formato

JSON / REST

Autenticación

Todas las peticiones deben incluir tu API key en el headerAuthorizationcomo Bearer token. Puedes generar y gestionar tus API keys desde elDashboard → Desarrolladores.

curl https://payforce.io/api/v1/payments \
  -H "Authorization: Bearer pf_live_a3b4c5d6e7f8..."

⚠ Seguridad

Las API keys con prefijo pf_live_ tienen acceso completo a tu cuenta. Nunca las expongas en código frontend ni en repositorios públicos. Usa variables de entorno siempre.

Payments

GET/api/v1/paymentsLista pagos

Devuelve la lista de pagos paginada por cursor.

curl https://payforce.io/api/v1/payments?limit=20 \
  -H "Authorization: Bearer pf_live_..."

# Response
{
  "object":      "list",
  "data": [
    {
      "id":          "clx1234...",
      "stripe_id":   "pi_3Qx...",
      "amount":      4999,
      "currency":    "eur",
      "status":      "SUCCEEDED",
      "description": "Suscripción mensual",
      "created_at":  "2025-04-10T14:23:00Z"
    }
  ],
  "has_more":    false,
  "next_cursor": null
}
limitinteger

Resultados por página (default 20, max 100)

cursorstring

ID del último pago para paginación

statusstring

SUCCEEDED | FAILED | PROCESSING | CANCELED

POST/api/v1/paymentsCrea un pago
curl -X POST https://payforce.io/api/v1/payments \
  -H "Authorization: Bearer pf_live_..." \
  -H "Content-Type: application/json" \
  -d '{
    "amount":         4999,
    "currency":       "eur",
    "description":    "Suscripción Pro",
    "customer_email": "cliente@empresa.com"
  }'

# Response 201
{
  "id":            "clx1234...",
  "stripe_id":     "pi_3Qx...",
  "client_secret": "pi_3Qx..._secret_...",
  "amount":        4999,
  "currency":      "eur",
  "status":        "processing"
}

Customers

POST/api/v1/customersCrea un cliente
curl -X POST https://payforce.io/api/v1/customers \
  -H "Authorization: Bearer pf_live_..." \
  -H "Content-Type: application/json" \
  -d '{
    "name":     "Arista Móvil S.L.",
    "email":    "contacto@arista.com",
    "phone":    "+34600000000",
    "currency": "eur"
  }'
GET/api/v1/customers?q=aristaLista y busca clientes
curl "https://payforce.io/api/v1/customers?q=arista&limit=10" \
  -H "Authorization: Bearer pf_live_..."

Invoices

Lista y gestiona las facturas manuales del merchant.

GET/api/v1/invoices
curl https://payforce.io/api/v1/invoices?status=PAID \
  -H "Authorization: Bearer pf_live_..."

Webhooks

PayForce envía eventos en tiempo real a tu endpoint cuando ocurren cambios importantes. Cada petición incluye el header X-PayForce-Signature firmado con HMAC-SHA256.

payment.succeeded
payment.failed
payment.refunded
customer.created
invoice.paid
invoice.overdue
// Verificar la firma del webhook en tu servidor
import crypto from "crypto";

function verifyWebhook(payload: string, signature: string, secret: string) {
  const expected = crypto
    .createHmac("sha256", secret)
    .update(payload)
    .digest("hex");
  return crypto.timingSafeEqual(
    Buffer.from(signature),
    Buffer.from(expected)
  );
}

// En tu handler:
app.post("/webhook", (req, res) => {
  const sig    = req.headers["x-payforce-signature"];
  const valid  = verifyWebhook(req.rawBody, sig, process.env.PF_WEBHOOK_SECRET);
  if (!valid) return res.status(401).send("Invalid signature");

  const event = req.body;
  switch (event.type) {
    case "payment.succeeded":
      fulfillOrder(event.data);
      break;
  }
  res.sendStatus(200);
});

Migración desde Stripe / Lemon Squeezy

Importa toda tu base de clientes, productos y pagos históricos con un solo comando.

RECOMENDADOCLI interactivo
# Sin instalación
npx payforce-migrate

# O instalar globalmente
npm install -g payforce-migrate
payforce-migrate
POST/api/migrateAPI de migración

Desde Stripe:

curl -X POST https://payforce.io/api/migrate \
  -H "Authorization: Bearer pf_live_..." \
  -H "Content-Type: application/json" \
  -d '{
    "source":        "stripe",
    "stripe_secret": "sk_live_...",
    "dry_run":       true
  }'

Desde Lemon Squeezy:

curl -X POST https://payforce.io/api/migrate \
  -H "Authorization: Bearer pf_live_..." \
  -H "Content-Type: application/json" \
  -d '{
    "source":     "lemon_squeezy",
    "ls_api_key": "eyJ0eXAiOi...",
    "dry_run":    false
  }'
sourcestring

"stripe" | "lemon_squeezy"

stripe_secretstring

Stripe secret key (sk_live_ o sk_test_)

ls_api_keystring

LemonSqueezy API key

dry_runboolean

true = previsualiza sin escribir (default: false)

Códigos de error

Todos los errores siguen el formato:

{
  "error": {
    "code":    "authentication_error",
    "message": "API key inválida o revocada.",
    "docs":    "https://payforce.io/developers"
  }
}
HTTPCodeDescripción
401authentication_errorAPI key inválida, revocada o expirada.
422invalid_paramParámetro obligatorio faltante o inválido.
422account_not_readyLa cuenta Stripe del merchant no está configurada.
429rate_limitDemasiadas solicitudes. Máximo 100 req/min.
500internal_errorError interno del servidor. Contacta soporte.

SDKs

TypeScript / Node

@payforce/sdk
npm install @payforce/sdk

Python

payforce-python
pip install payforce

PHP

payforce/payforce-php
composer require payforce/payforce-php
// TypeScript / Node.js
import PayForce from "@payforce/sdk";

const pf = new PayForce({ apiKey: process.env.PF_SECRET_KEY });

// Crear un pago
const payment = await pf.payments.create({
  amount:      4999,       // céntimos
  currency:    "eur",
  description: "Suscripción Pro",
});

console.log(payment.client_secret); // pasa esto al frontend