C# / .NET
SDK ufficiale C#/.NET per il gateway di pagamento Cost+
SDK ufficiale C#/.NET per il gateway di pagamento Cost+. Semplifica il flusso di reindirizzamento HPP (Pagina di Pagamento Ospitata), la firma dei payload HMAC e la verifica dei webhook.
Caratteristiche
- Zero dipendenze — utilizza solo
System.Text.JsoneSystem.Security.Cryptographyintegrati - Target .NET 8.0 con funzionalità C# 12 (record, namespace file-scoped, pattern matching)
- Tipi di riferimento nullable abilitati ovunque
- Generazione firma HMAC-SHA256 e verifica a tempo costante
- Mappatura automatica snake_case/PascalCase tra API e SDK
- Analisi webhook + verifica dell'ordine basata su API
- Superficie API completamente asincrona
Requisiti
- .NET 8.0 SDK o successivo
- Un account commerciante Cost+ — dashboard.costplus.io
Installazione
dotnet add package NoPaynOppure come riferimento a progetto locale:
dotnet add reference path/to/src/NoPayn/NoPayn.csprojGuida Rapida
1. Inizializza il Client
using NoPayn;
using NoPayn.Models;
var nopayn = new NoPaynClient(new NoPaynConfig(
ApiKey: "your-api-key",
MerchantId: "your-project"
));2. Crea un Pagamento e Reindirizza all'HPP
var result = await nopayn.GeneratePaymentUrlAsync(new CreateOrderParams
{
Amount = 1295, // €12.95 in cents
Currency = "EUR",
MerchantOrderId = "ORDER-001",
Description = "Premium Widget",
ReturnUrl = "https://shop.example.com/success",
FailureUrl = "https://shop.example.com/failure",
WebhookUrl = "https://shop.example.com/webhook",
Locale = "en-GB",
ExpirationPeriod = "PT30M",
});
// Redirect the customer
// result.OrderUrl → HPP (customer picks payment method)
// result.PaymentUrl → direct link to the first transaction's payment method
// result.Signature → HMAC-SHA256 for verification
// result.OrderId → NoPayn order UUID3. Gestisci il Webhook
app.MapPost("/webhook", async (HttpContext ctx) =>
{
using var reader = new StreamReader(ctx.Request.Body);
var rawBody = await reader.ReadToEndAsync();
var verified = await nopayn.VerifyWebhookAsync(rawBody);
Console.WriteLine(verified.Order.Status); // "completed", "cancelled", etc.
Console.WriteLine(verified.IsFinal); // true when the order won't change
if (verified.Order.Status == "completed")
{
// Fulfil the order
}
return Results.Ok();
});Riferimento API
new NoPaynClient(config, httpClient?)
| Parametro | Tipo | Obbligatorio | Predefinito |
|---|---|---|---|
ApiKey | string | Sì | — |
MerchantId | string | Sì | — |
BaseUrl | string | No | https://api.nopayn.co.uk |
Un HttpClient opzionale può essere passato come secondo parametro del costruttore per la gestione HTTP personalizzata o il testing.
client.CreateOrderAsync(params): Task<Order>
Crea un ordine tramite POST /v1/orders/.
| Parametro | Tipo | Obbligatorio | Descrizione |
|---|---|---|---|
Amount | int | Sì | Importo nell'unità valutaria più piccola (centesimi) |
Currency | string | Sì | Codice ISO 4217 (EUR, GBP, USD, NOK, SEK) |
MerchantOrderId | string? | No | Il tuo riferimento interno dell'ordine |
Description | string? | No | Descrizione dell'ordine |
ReturnUrl | string? | No | Reindirizzamento dopo pagamento riuscito |
FailureUrl | string? | No | Reindirizzamento in caso di annullamento/scadenza/errore |
WebhookUrl | string? | No | Notifiche asincrone di cambio stato |
Locale | string? | No | Lingua HPP (en-GB, de-DE, nl-NL, ecc.) |
PaymentMethods | IReadOnlyList<string>? | No | Filtra i metodi HPP |
ExpirationPeriod | string? | No | Durata ISO 8601 (PT30M) |
Metodi di pagamento disponibili: credit-card, apple-pay, google-pay, vipps-mobilepay
client.GetOrderAsync(orderId): Task<Order>
Recupera i dettagli dell'ordine tramite GET /v1/orders/{id}/.
client.CreateRefundAsync(orderId, amount, description?): Task<Refund>
Emette un rimborso totale o parziale tramite POST /v1/orders/{id}/refunds/.
client.GeneratePaymentUrlAsync(params): Task<PaymentUrlResult>
Metodo di convenienza che crea un ordine e restituisce:
public record PaymentUrlResult(
string OrderId, // NoPayn order UUID
string OrderUrl, // HPP URL
string? PaymentUrl, // Direct payment URL (first transaction)
string Signature, // HMAC-SHA256 of amount:currency:orderId
Order Order // Full order object
);client.GenerateSignature(amount, currency, orderId): string
Genera una firma HMAC-SHA256 esadecimale.
client.VerifySignature(amount, currency, orderId, signature): bool
Verifica a tempo costante di una firma HMAC-SHA256.
client.VerifyWebhookAsync(rawBody): Task<VerifiedWebhook>
Analizza il corpo del webhook, poi chiama GET /v1/orders/{id}/ per verificare lo stato effettivo.
Utility HMAC Standalone
using NoPayn;
var sig = NoPaynSignature.Generate("your-api-key", 1295, "EUR", "order-uuid");
var ok = NoPaynSignature.Verify("your-api-key", 1295, "EUR", "order-uuid", sig);Gestione degli Errori
using NoPayn.Exceptions;
try
{
await nopayn.CreateOrderAsync(new CreateOrderParams { Amount = 100, Currency = "EUR" });
}
catch (ApiException ex)
{
Console.Error.WriteLine(ex.StatusCode); // 401, 400, etc.
Console.Error.WriteLine(ex.ErrorBody); // Raw API error response
}
catch (NoPaynException ex)
{
Console.Error.WriteLine(ex.Message); // Network or parsing error
}| Eccezione | Descrizione |
|---|---|
NoPaynException | Eccezione base (rete, parsing) |
ApiException | Errore HTTP dall'API |
WebhookException | Payload webhook non valido |
Stati dell'Ordine
| Stato | Finale? | Descrizione |
|---|---|---|
new | No | Ordine creato |
processing | No | Pagamento in corso |
completed | Sì | Pagamento riuscito — consegna la merce |
cancelled | Sì | Pagamento annullato dal cliente |
expired | Sì | Link di pagamento scaduto |
error | Sì | Errore tecnico |
Best Practice per i Webhook
- Verifica sempre tramite API — il payload del webhook contiene solo l'ID dell'ordine, mai lo stato. Il metodo
VerifyWebhookAsync()dell'SDK lo fa automaticamente. - Restituisci HTTP 200 per confermare la ricezione. Qualsiasi altro codice attiva fino a 10 tentativi (ogni 2 minuti).
- Implementa un poller di backup — per gli ordini più vecchi di 10 minuti che non hanno raggiunto uno stato finale, interroga
GetOrderAsync()come rete di sicurezza. - Sii idempotente — potresti ricevere lo stesso webhook più volte.
Carte di Test
Usa queste carte in modalità test Cost+ (sito web sandbox):
| Carta | Numero | Note |
|---|---|---|
| Visa (successo) | 4111 1111 1111 1111 | Qualsiasi CVV |
| Mastercard (successo) | 5544 3300 0003 7 | Qualsiasi CVV |
| Visa (rifiutata) | 4111 1111 1111 1105 | Do Not Honor |
| Visa (fondi insufficienti) | 4111 1111 1111 1151 | Insufficient Funds |
Usa qualsiasi data di scadenza futura e qualsiasi CVC a 3 cifre.
App Demo
Un'app demo ASP.NET Core basata su Docker è inclusa nel repository GitHub per testare il flusso di pagamento completo.
Supporto
Hai bisogno di aiuto? Contatta il nostro team di supporto a support@costplus.io.