Aller au contenu principal

SDK .NET

Le SDK .NET fournit une boite a outils complete pour l'integration avec Worldline Direct en utilisant C#. Il prend en charge toutes les methodes d'integration et gere l'authentification, la signature des requetes et l'analyse des reponses.

Fonctionnalites

  • Acces a toutes les fonctionnalites de l'API RESTful
  • Prise en charge de Hosted Checkout, Hosted Tokenization et serveur a serveur
  • Cycle de vie complet du paiement : creation, capture, remboursement, annulation
  • Verification des signatures webhook
  • Journalisation et debogage integres

Exigences

ExigenceVersion
.NET Framework4.6.1 ou ulterieur
.NET Core2.0 ou ulterieur
.NET 5/6/7/8Pris en charge

Plateformes prises en charge : Windows, Linux, macOS

Installation

Installez via NuGet Package Manager :

dotnet add package OnlinePayments.Sdk

Ou via la console Package Manager :

Install-Package OnlinePayments.Sdk

Demarrage rapide

Initialiser le client

using OnlinePayments.Sdk;

var configuration = new CommunicatorConfiguration
{
ApiEndpoint = new Uri("https://payment.preprod.direct.worldline-solutions.com"),
ApiKeyId = "YOUR_API_KEY",
SecretApiKey = "YOUR_API_SECRET",
Integrator = "YourCompanyName"
};

var client = Factory.CreateClient(configuration);
var merchantClient = client.WithNewMerchant("YOUR_MERCHANT_ID");

Parametres de configuration

ParametreDescription
ApiEndpointURL de l'environnement (test ou production)
ApiKeyIdVotre cle API du Portail Marchand
SecretApiKeyVotre secret API du Portail Marchand
IntegratorLe nom de votre entreprise pour le suivi des requetes

URLs des environnements :

EnvironnementURL
Testhttps://payment.preprod.direct.worldline-solutions.com
Productionhttps://payment.direct.worldline-solutions.com

Creer des paiements

Hosted Checkout

var request = new CreateHostedCheckoutRequest
{
Order = new Order
{
AmountOfMoney = new AmountOfMoney
{
Amount = 2980, // Montant en centimes
CurrencyCode = "EUR"
},
Customer = new Customer
{
MerchantCustomerId = "customer-123",
BillingAddress = new Address
{
CountryCode = "NL"
}
}
},
HostedCheckoutSpecificInput = new HostedCheckoutSpecificInput
{
ReturnUrl = "https://yoursite.com/return",
Variant = "my-template"
}
};

var response = await merchantClient.HostedCheckout
.CreateHostedCheckoutAsync(request);

// Rediriger le client vers la page de paiement
string redirectUrl = response.RedirectUrl;
string hostedCheckoutId = response.HostedCheckoutId;

Paiement serveur a serveur

var request = new CreatePaymentRequest
{
Order = new Order
{
AmountOfMoney = new AmountOfMoney
{
Amount = 2980,
CurrencyCode = "EUR"
},
References = new OrderReferences
{
MerchantReference = "order-12345"
}
},
CardPaymentMethodSpecificInput = new CardPaymentMethodSpecificInput
{
PaymentProductId = 1, // Visa
Card = new Card
{
CardholderName = "John Doe",
CardNumber = "4111111111111111",
Cvv = "123",
ExpiryDate = "1225"
},
ThreeDSecure = new ThreeDSecure
{
RedirectionData = new RedirectionData
{
ReturnUrl = "https://yoursite.com/return"
}
}
}
};

var response = await merchantClient.Payments
.CreatePaymentAsync(request);

Hosted Tokenization

var request = new CreateHostedTokenizationRequest
{
Variant = "my-tokenization-template.html"
};

var response = await merchantClient.HostedTokenization
.CreateHostedTokenizationAsync(request);

string hostedTokenizationUrl = response.PartialRedirectUrl;
string hostedTokenizationId = response.HostedTokenizationId;

Recuperer le statut du paiement

// Obtenir les details du paiement
var payment = await merchantClient.Payments
.GetPaymentDetailsAsync(paymentId);

int statusCode = payment.StatusOutput.StatusCode;
string status = payment.Status;

// Obtenir le statut du hosted checkout
var checkoutStatus = await merchantClient.HostedCheckout
.GetHostedCheckoutStatusAsync(hostedCheckoutId);

Operations de maintenance

Capturer un paiement

var request = new CapturePaymentRequest
{
Amount = 2980,
IsFinal = true
};

var capture = await merchantClient.Payments
.CapturePaymentAsync(paymentId, request);

Rembourser un paiement

var request = new RefundRequest
{
AmountOfMoney = new AmountOfMoney
{
Amount = 2980,
CurrencyCode = "EUR"
}
};

var refund = await merchantClient.Payments
.RefundPaymentAsync(paymentId, request);

Annuler un paiement

var result = await merchantClient.Payments
.CancelPaymentAsync(paymentId);

Gestion des exceptions

Exceptions de paiement

try
{
var response = await merchantClient.Payments
.CreatePaymentAsync(request);
}
catch (DeclinedPaymentException e)
{
// Paiement refuse
var payment = e.CreatePaymentResponse.Payment;
Console.WriteLine($"Paiement refuse : {payment.StatusOutput.StatusCode}");

foreach (var error in e.Errors)
{
Console.WriteLine($"Erreur {error.Code}: {error.Message}");
}
}
catch (ValidationException e)
{
// Requete invalide (400)
foreach (var error in e.Errors)
{
Console.WriteLine($"Erreur de validation : {error.PropertyName} - {error.Message}");
}
}
catch (AuthorizationException e)
{
// Acces refuse (403)
Console.WriteLine("Authentification echouee. Verifiez vos identifiants API.");
}
catch (ReferenceException e)
{
// Ressource non trouvee (404/409/410)
Console.WriteLine($"Erreur de ressource : {e.Message}");
}
catch (PlatformException e)
{
// Erreur serveur (500/502/503)
Console.WriteLine($"Erreur plateforme : {e.Message}");
}

Types d'exceptions HTTP

Code de statutType d'exceptionDescription
400ValidationExceptionErreurs de validation des entrees
403AuthorizationExceptionAcces refuse
404/409/410ReferenceExceptionProblemes de ressource
409IdempotenceExceptionRequete en double
500/502/503PlatformExceptionErreurs serveur

Requetes idempotentes

Empchez les paiements en double en utilisant des cles d'idempotence :

string idempotenceKey = Guid.NewGuid().ToString();
var context = new CallContext().WithIdempotenceKey(idempotenceKey);

try
{
var response = await merchantClient.Payments
.CreatePaymentAsync(request, context);
}
catch (IdempotenceException e)
{
// La requete a deja ete traitee
var existingResponse = e.IdempotenceRequestTimestamp;
}

Traitement des webhooks

// Stocker votre secret webhook
InMemorySecretKeyStore.Instance.StoreSecretKey("webhookKeyId", "webhookSecret");

var helper = new WebhooksHelper(
DefaultMarshaller.Instance,
InMemorySecretKeyStore.Instance
);

// Dans votre point d'acces webhook
[HttpPost("webhook")]
public IActionResult HandleWebhook()
{
var body = new StreamReader(Request.Body).ReadToEnd();
var headers = Request.Headers
.Select(h => new RequestHeader(h.Key, h.Value.FirstOrDefault()))
.ToList();

try
{
var webhookEvent = helper.Unmarshal(body, headers);

// Traiter l'evenement
var payment = webhookEvent.Payment;
var eventType = webhookEvent.Type;

return Ok();
}
catch (SignatureValidationException e)
{
return BadRequest("Signature invalide");
}
}

Configuration avancee

Journalisation

Activez la journalisation des requetes/reponses pour le debogage :

// Activer la journalisation
client.EnableLogging(new SystemConsoleCommunicatorLogger());

// Effectuer des operations...

// Desactiver la journalisation
client.DisableLogging();
Donnees sensibles

Le SDK masque automatiquement les donnees sensibles (numeros de carte, CVV) dans les journaux.

Pool de connexions

Partagez les connexions entre plusieurs clients :

var communicator = Factory.CreateCommunicator(configuration);

var client1 = Factory.CreateClient(communicator);
var client2 = Factory.CreateClient(communicator);

// Les deux clients partagent le meme pool de connexions

Gestion des ressources

// L'instruction using assure une liberation appropriee
using (var client = Factory.CreateClient(configuration))
{
var merchantClient = client.WithNewMerchant("MERCHANT_ID");
// Utiliser merchantClient...
} // Connexion automatiquement fermee

// Ou fermer manuellement les connexions inactives
client.CloseIdleConnections(TimeSpan.FromMinutes(5));

Obtenir les moyens de paiement disponibles

var queryParams = new GetPaymentProductsParams
{
CountryCode = "NL",
CurrencyCode = "EUR"
};

var products = await merchantClient.Products
.GetPaymentProductsAsync(queryParams);

foreach (var product in products.PaymentProducts)
{
Console.WriteLine($"{product.Id}: {product.DisplayHints.Label}");
}

Exemple complet

using OnlinePayments.Sdk;
using OnlinePayments.Sdk.Domain;

public class PaymentService
{
private readonly IClient _client;
private readonly IMerchantClient _merchantClient;

public PaymentService(string apiKey, string apiSecret, string merchantId)
{
var configuration = new CommunicatorConfiguration
{
ApiEndpoint = new Uri("https://payment.preprod.direct.worldline-solutions.com"),
ApiKeyId = apiKey,
SecretApiKey = apiSecret,
Integrator = "MyCompany"
};

_client = Factory.CreateClient(configuration);
_merchantClient = _client.WithNewMerchant(merchantId);
}

public async Task<CreateHostedCheckoutResponse> CreateCheckout(
long amountInCents,
string currency,
string returnUrl)
{
var request = new CreateHostedCheckoutRequest
{
Order = new Order
{
AmountOfMoney = new AmountOfMoney
{
Amount = amountInCents,
CurrencyCode = currency
}
},
HostedCheckoutSpecificInput = new HostedCheckoutSpecificInput
{
ReturnUrl = returnUrl
}
};

return await _merchantClient.HostedCheckout
.CreateHostedCheckoutAsync(request);
}

public async Task<PaymentResponse> GetPaymentStatus(string paymentId)
{
return await _merchantClient.Payments
.GetPaymentDetailsAsync(paymentId);
}

public void Dispose()
{
_client?.Dispose();
}
}

Ressources

Prochaines etapes