Pagath.Sdk
0.1.1-alpha
dotnet add package Pagath.Sdk --version 0.1.1-alpha
NuGet\Install-Package Pagath.Sdk -Version 0.1.1-alpha
<PackageReference Include="Pagath.Sdk" Version="0.1.1-alpha" />
<PackageVersion Include="Pagath.Sdk" Version="0.1.1-alpha" />
<PackageReference Include="Pagath.Sdk" />
paket add Pagath.Sdk --version 0.1.1-alpha
#r "nuget: Pagath.Sdk, 0.1.1-alpha"
#:package Pagath.Sdk@0.1.1-alpha
#addin nuget:?package=Pagath.Sdk&version=0.1.1-alpha&prerelease
#tool nuget:?package=Pagath.Sdk&version=0.1.1-alpha&prerelease
Pagath.Sdk
Cliente de servidor para la API de pagos de Pagath: crea órdenes de pago y devoluciones, consulta su estado y verifica la firma de los webhooks. Obtiene y renueva el token OAuth por ti, con o sin inyección de dependencias.
Instalación
dotnet add package Pagath.Sdk --version 0.1.1-alpha
Mientras el paquete sea 0.x y prerelease, fija siempre la versión exacta. Necesitas un proyecto net10.0 o superior.
Inicio rápido
Pide las credenciales de sandbox de tu aplicación conectada y guárdalas en variables de entorno (PAGATH_CLIENT_ID, PAGATH_CLIENT_SECRET). Nunca las escribas en el código. Este ejemplo recorre el flujo completo sin inyección de dependencias: elige una pasarela, crea una orden y consulta su estado.
using System;
using System.Linq;
using Pagath.Sdk;
using var client = new PagathClient(new PagathOptions
{
Environment = PagathEnvironment.Sandbox,
ClientId = Environment.GetEnvironmentVariable("PAGATH_CLIENT_ID")!,
ClientSecret = Environment.GetEnvironmentVariable("PAGATH_CLIENT_SECRET")!
});
// 1. Consulta las pasarelas disponibles y lee los datos que exige la elegida.
var pasarelas = await client.Gateways.ListAsync();
var pasarela = pasarelas.FirstOrDefault(p => p.Gateway == "transfermovil")
?? throw new InvalidOperationException("Tu aplicación no tiene Transfermóvil disponible.");
foreach (var campo in pasarela.GatewayData)
Console.WriteLine($"{campo.Name} ({campo.Type}) requerido: {campo.Required}");
// 2. Guarda tu número de orden antes de enviar. Importe mínimo en sandbox: 1.00.
var reference = "ORD-184";
var creada = await client.Orders.CreateAsync(new CreateOrderRequest<TransfermovilData>
{
Gateway = pasarela.Gateway,
Reference = reference,
Amount = 1.00m,
// Envía GatewayData solo si la pasarela lo declara.
GatewayData = pasarela.GatewayData.Count > 0
? new TransfermovilData(Environment.GetEnvironmentVariable("PAGATH_PHONE")!)
: null
});
// 3. Presenta el enlace o el código QR al pagador.
Console.WriteLine($"{creada.Outcome} {creada.Resource.Id} {creada.Resource.Link} {creada.Resource.QrCode}");
// 4. Consulta el estado por id o por número de orden.
var porId = await client.Orders.GetAsync(creada.Resource.Id);
var porNumero = await client.Orders.GetByReferenceAsync(reference);
Console.WriteLine($"{porId.Resource.PaymentStatus} {porNumero.Resource.PaymentStatus}");
// Los campos de gatewayData que la pasarela declara; el SDK serializa Phone como "phone".
public sealed record TransfermovilData(string Phone);
El sandbox de Transfermóvil cobra de verdad: por eso el ejemplo usa el importe mínimo, 1.00. Con una pasarela sin datos propios, usa CreateOrderRequest sin tipo.
Solo
PaymentStatus.Paidconfirma el cobro. Ni el201de la creación ni el regreso del pagador a tu sitio demuestran que se cobró. Entrega el producto únicamente cuandoResource.PaymentStatusseaPaymentStatus.Paid.
Con inyección de dependencias, registra el cliente y el verificador de webhooks al arrancar. Las opciones se validan al inicio:
using Pagath.Sdk;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddPagath(options =>
{
options.Environment = PagathEnvironment.Sandbox;
options.ClientId = builder.Configuration["PAGATH_CLIENT_ID"]!;
options.ClientSecret = builder.Configuration["PAGATH_CLIENT_SECRET"]!;
});
builder.Services.AddPagathWebhooks(options =>
options.Secret = builder.Configuration["PAGATH_WEBHOOK_SECRET"]!);
var app = builder.Build();
// Inyecta IPagathClient donde lo necesites.
app.MapGet("/ordenes/{reference}", async (string reference, IPagathClient pagath) =>
{
var orden = await pagath.Orders.GetByReferenceAsync(reference);
return Results.Ok(new { orden.Resource.Id, Estado = orden.Resource.PaymentStatus?.ToString() });
});
app.Run();
Recibir webhooks
Pagath envía un webhook a tu servidor cuando cambia el estado de un pago o de una devolución. Verifica la firma sobre el cuerpo en crudo, sin deserializarlo antes. El secreto de firma del destino (whsec_...) no es tu credencial de acceso. Este ejemplo usa una minimal API con AddPagathWebhooks:
using System.Collections.Concurrent;
using System.Text;
using Pagath.Sdk;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddPagathWebhooks(options =>
options.Secret = builder.Configuration["PAGATH_WEBHOOK_SECRET"]!);
var app = builder.Build();
var procesados = new ConcurrentDictionary<string, bool>(); // En producción, usa una tabla con clave única.
app.MapPost("/webhooks/pagath", async (HttpRequest request, PagathWebhookVerifier verifier, CancellationToken ct) =>
{
try
{
using var reader = new StreamReader(request.Body, new UTF8Encoding(false, true), false, leaveOpen: true);
var cuerpo = await reader.ReadToEndAsync(ct);
var cabeceras = request.Headers.ToDictionary(h => h.Key, h => h.Value.ToString(), StringComparer.OrdinalIgnoreCase);
var webhook = verifier.Verify(cuerpo, cabeceras);
if (!procesados.TryAdd(webhook.EventId, true))
return Results.NoContent(); // Entrega repetida: ya la procesaste.
switch (webhook)
{
case PaymentWebhookEvent pago:
Console.WriteLine($"Pago {pago.Data.Reference} {pago.Data.PaymentStatus}");
break;
case RefundWebhookEvent devolucion:
Console.WriteLine($"Devolución {devolucion.Data.RefundId} {devolucion.Data.RefundStatus}");
break;
default:
Console.WriteLine($"Tipo que este SDK no conoce: {webhook.EventType}");
break;
}
// Guarda de forma duradera antes de responder.
return Results.NoContent();
}
catch (Exception error) when (error is PagathWebhookVerificationException or PagathUnsupportedSchemaVersionException or DecoderFallbackException)
{
return Results.BadRequest(); // Firma inválida o cuerpo mal formado: no lo proceses.
}
});
app.Run();
- Responde
2xxsolo después de guardar el webhook. Las entregas pueden repetirse y llegar fuera de orden: deduplica porEventIdy consulta la orden para conocer su estado vigente. - Un
UnknownWebhookEventes un tipo nuevo para esta versión del SDK: confirma con2xxy conservaRawBody. - Sin inyección de dependencias, crea el verificador con
new PagathWebhookVerifier("whsec_...").
Errores e idempotencia
Cada solicitud que Pagath rechaza se convierte en una excepción tipada. Decide por Code, no por el mensaje.
| Excepción | Cuándo ocurre | Qué hacer |
|---|---|---|
PagathValidationException |
La solicitud es inválida (422). | Corrige los campos de Errors. |
PagathAuthenticationException, PagathForbiddenException |
Credenciales o token rechazados (401), o permiso insuficiente (403). | Revisa credenciales, permisos y entorno. |
PagathNotFoundException |
El recurso no existe (404). | Revisa el id o el número de orden. |
PagathConflictException |
La solicitud choca con el estado del recurso (409). | No reutilices número de orden ni clave con otro contenido. |
PagathOperationNotSupportedException, PagathGatewayRejectedException |
La pasarela no admite la operación o la rechazó. | Lee Code y Detail. |
PagathReservationCleanupPendingException |
Pagath no pudo confirmar que liberó el registro (503). | Consulta más tarde; no des por libre el número de orden. |
PagathApiException |
Cualquier otro error de la API; es la base de las anteriores. | Usa Status, Code y Detail. |
PagathOutcomeUnknownException |
Un POST terminó en 504, tiempo agotado o conexión perdida: Pagath pudo ejecutarlo. |
Consulta antes de repetir. |
PagathUnreadableResourceException |
Pagath respondió 2xx, pero el recurso no se puede leer. | La operación se ejecutó: consúltala, no repitas el POST. |
PagathUnsupportedApiVersionException |
Pagath respondió con una versión de API que el SDK no admite. | Actualiza el SDK. Tras un POST, consulta antes de repetir. |
Un tiempo agotado no significa que no se cobró. Para recuperar una operación incierta, consulta por tu número de orden antes de repetirla:
using System;
using Pagath.Sdk;
var numero = "ORD-185"; // Guárdalo antes de enviar.
try
{
var creada = await client.Orders.CreateAsync(new CreateOrderRequest<TransfermovilData>
{
Gateway = "transfermovil",
Reference = numero,
Amount = 1.00m,
GatewayData = new TransfermovilData(Environment.GetEnvironmentVariable("PAGATH_PHONE")!)
});
Console.WriteLine($"{creada.Resource.Id} {creada.Outcome}");
}
catch (PagathOutcomeUnknownException incierta) when (incierta.Reference is not null)
{
// Pagath pudo crear la orden: consúltala antes de crear otra.
var orden = await client.Orders.GetByReferenceAsync(incierta.Reference);
Console.WriteLine($"{orden.Resource.CreationStatus} {orden.Resource.PaymentStatus}");
}
catch (PagathValidationException invalida)
{
Console.Error.WriteLine($"{invalida.Code}: {invalida.Errors.Count} errores");
}
Una respuesta PagathOutcome.Accepted (202) no es un fallo: la creación está en curso o es incierta. Consulta la orden; no crees otra.
Devoluciones
Una devolución exige una clave de idempotencia: guárdala antes de enviar y reutilízala, con el mismo contenido, en cada reintento. Lo mejor es usar el identificador de la devolución en tu sistema; PagathIdempotencyKey.New() genera una aleatoria. Pide refunds:read y refunds:write en Scopes.
using System;
using Pagath.Sdk;
using var clienteDevoluciones = new PagathClient(new PagathOptions
{
Environment = PagathEnvironment.Sandbox,
ClientId = Environment.GetEnvironmentVariable("PAGATH_CLIENT_ID")!,
ClientSecret = Environment.GetEnvironmentVariable("PAGATH_CLIENT_SECRET")!,
Scopes = ["payments:read", "refunds:read", "refunds:write"]
});
var clave = PagathIdempotencyKey.New(); // Guárdala antes de enviar.
var devolucion = await clienteDevoluciones.Refunds.CreateAsync(
new CreateRefundRequest { Reference = "ORD-184", Amount = 0.50m, Description = "Devolución parcial" }, // Número de orden de la orden pagada.
clave);
var estado = await clienteDevoluciones.Refunds.GetAsync(devolucion.Resource.Id);
Console.WriteLine(estado.Resource.RefundStatus);
Configuración
PagathOptions reúne los ajustes del cliente:
| Opción | Qué es |
|---|---|
Environment |
PagathEnvironment.Sandbox, PagathEnvironment.Production o PagathEnvironment.Custom(apiBaseUrl, authBaseUrl). Obligatoria. |
ClientId, ClientSecret |
Credenciales de tu aplicación conectada. Obligatorias, salvo que aportes tu propio IPagathTokenProvider. |
Scopes |
Permisos que pide el SDK. Si los omites, pide los asignados a tu aplicación. |
Timeout |
Plazo de cada petición HTTP. |
new PagathClient(options)crea y libera su propioHttpClient. Connew PagathClient(options, httpClient)onew PagathClient(options, handler)controlas el transporte; ambos aceptan unIPagathTokenProviderpropio.- Crea un solo cliente por aplicación y reutilízalo. Con
AddPagath, el contenedor lo registra como singleton y devuelve elIHttpClientBuilderpara encadenar un manejador de resiliencia. - Aplica los reintentos solo a las consultas (
GET): un manejador que repita un POST puede duplicar un cobro.
Compatibilidad
- API v1 y webhooks v1 (
schemaVersion: "v1"). El SDK rechaza una respuesta de otra versión de API o un webhook de otro esquema. - Destino
net10.0. - Mientras el paquete sea
0.x, su API pública puede cambiar entre versiones: fija la versión exacta. La versión1.0.0seguirá SemVer estricto.
Más información
- Documentación de Pagath y primeros pasos
- Guía del SDK de .NET
- Recibir webhooks
- Catálogo de errores
- Ejemplos: sin inyección de dependencias y con inyección de dependencias
Licencia
MIT.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- Microsoft.Extensions.Http (>= 10.0.0)
- StandardWebhooks.StandardWebhooks (>= 1.0.1)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 0.1.1-alpha | 0 | 12/2/2026 |
| 0.1.0-alpha | 0 | 12/2/2026 |