C# / .NET
SDK officiel C#/.NET pour la passerelle de paiement Cost+
SDK officiel C#/.NET pour la passerelle de paiement Cost+. Simplifie le flux de redirection HPP (page de paiement hébergée), la signature de payload HMAC et la vérification des webhooks.
Fonctionnalités
- Zéro dépendance — utilise uniquement
System.Text.JsonetSystem.Security.Cryptographyintégrés - Cible .NET 8.0 avec les fonctionnalités C# 12 (records, file-scoped namespaces, pattern matching)
- Types référence nullable activés partout
- Génération de signature HMAC-SHA256 et vérification en temps constant
- Mappage automatique snake_case/PascalCase entre l'API et le SDK
- Analyse des webhooks + vérification des commandes via l'API
- Surface API entièrement asynchrone
Prérequis
- .NET 8.0 SDK ou ultérieur
- Un compte marchand Cost+ — dashboard.costplus.io
Installation
dotnet add package NoPaynOu en tant que référence de projet local :
dotnet add reference path/to/src/NoPayn/NoPayn.csprojDémarrage rapide
1. Initialiser le client
using NoPayn;
using NoPayn.Models;
var nopayn = new NoPaynClient(new NoPaynConfig(
ApiKey: "your-api-key",
MerchantId: "your-project"
));2. Créer un paiement et rediriger vers la 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. Gérer le 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();
});Référence API
new NoPaynClient(config, httpClient?)
| Paramètre | Type | Obligatoire | Par défaut |
|---|---|---|---|
ApiKey | string | Oui | — |
MerchantId | string | Oui | — |
BaseUrl | string | Non | https://api.nopayn.co.uk |
Un HttpClient optionnel peut être passé en second paramètre du constructeur pour une gestion HTTP personnalisée ou des tests.
client.CreateOrderAsync(params): Task<Order>
Crée une commande via POST /v1/orders/.
| Paramètre | Type | Obligatoire | Description |
|---|---|---|---|
Amount | int | Oui | Montant dans la plus petite unité monétaire (centimes) |
Currency | string | Oui | Code ISO 4217 (EUR, GBP, USD, NOK, SEK) |
MerchantOrderId | string? | Non | Votre référence interne de commande |
Description | string? | Non | Description de la commande |
ReturnUrl | string? | Non | Redirection après paiement réussi |
FailureUrl | string? | Non | Redirection en cas d'annulation/expiration/erreur |
WebhookUrl | string? | Non | Notifications asynchrones de changement de statut |
Locale | string? | Non | Langue de la HPP (en-GB, de-DE, nl-NL, etc.) |
PaymentMethods | IReadOnlyList<string>? | Non | Filtrer les méthodes HPP |
ExpirationPeriod | string? | Non | Durée ISO 8601 (PT30M) |
Méthodes de paiement disponibles : credit-card, apple-pay, google-pay, vipps-mobilepay
client.GetOrderAsync(orderId): Task<Order>
Récupère les détails de la commande via GET /v1/orders/{id}/.
client.CreateRefundAsync(orderId, amount, description?): Task<Refund>
Effectue un remboursement total ou partiel via POST /v1/orders/{id}/refunds/.
client.GeneratePaymentUrlAsync(params): Task<PaymentUrlResult>
Méthode utilitaire qui crée une commande et renvoie :
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
Génère une signature HMAC-SHA256 hexadécimale.
client.VerifySignature(amount, currency, orderId, signature): bool
Vérification en temps constant d'une signature HMAC-SHA256.
client.VerifyWebhookAsync(rawBody): Task<VerifiedWebhook>
Analyse le corps du webhook, puis appelle GET /v1/orders/{id}/ pour vérifier le statut réel.
Utilitaires HMAC autonomes
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);Gestion des erreurs
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
}| Exception | Description |
|---|---|
NoPaynException | Exception de base (réseau, parsing) |
ApiException | Erreur HTTP de l'API |
WebhookException | Payload de webhook invalide |
Statuts des commandes
| Statut | Final ? | Description |
|---|---|---|
new | Non | Commande créée |
processing | Non | Paiement en cours |
completed | Oui | Paiement réussi — livrez les marchandises |
cancelled | Oui | Paiement annulé par le client |
expired | Oui | Le lien de paiement a expiré |
error | Oui | Erreur technique |
Bonnes pratiques pour les webhooks
- Vérifiez toujours via l'API — le payload du webhook contient uniquement l'identifiant de la commande, jamais le statut. Le
VerifyWebhookAsync()du SDK le fait automatiquement. - Renvoyez HTTP 200 pour accuser réception. Tout autre code déclenche jusqu'à 10 tentatives (espacées de 2 minutes).
- Implémentez un polling de secours — pour les commandes de plus de 10 minutes qui n'ont pas atteint un statut final, interrogez
GetOrderAsync()comme filet de sécurité. - Soyez idempotent — vous pouvez recevoir le même webhook plusieurs fois.
Cartes de test
Utilisez ces cartes en mode test Cost+ (site web sandbox) :
| Carte | Numéro | Notes |
|---|---|---|
| Visa (succès) | 4111 1111 1111 1111 | N'importe quel CVV |
| Mastercard (succès) | 5544 3300 0003 7 | N'importe quel CVV |
| Visa (refusée) | 4111 1111 1111 1105 | Do Not Honor |
| Visa (fonds insuffisants) | 4111 1111 1111 1151 | Insufficient Funds |
Utilisez n'importe quelle date d'expiration future et n'importe quel CVC à 3 chiffres.
Application de démonstration
Une application de démonstration ASP.NET Core basée sur Docker est incluse dans le dépôt GitHub pour tester le flux de paiement complet.
Support
Besoin d'aide ? Contactez notre équipe de support à support@costplus.io.