Developer-friendly & type-safe Csharp SDK specifically catered to leverage Mollie API.
To add the NuGet package to a .NET project:
dotnet add package MollieTo add a reference to a local instance of the SDK in a .NET project:
dotnet add reference src/Mollie/Mollie.csprojusing Mollie;
using Mollie.Models.Components;
using Mollie.Models.Requests;
var sdk = new Client(
testmode: false,
security: new Security() {
ApiKey = "<YOUR_BEARER_TOKEN_HERE>",
}
);
ListBalancesRequest req = new ListBalancesRequest() {
Currency = "EUR",
From = "bal_gVMhHKqSSRYJyPsuoPNFH",
Limit = 50,
IdempotencyKey = "123e4567-e89b-12d3-a456-426",
};
var res = await sdk.Balances.ListAsync(req);
// handle responseThis SDK supports the following security schemes globally:
| Name | Type | Scheme |
|---|---|---|
ApiKey |
http | HTTP Bearer |
OAuth |
oauth2 | OAuth2 token |
You can set the security parameters through the security optional parameter when initializing the SDK client instance. The selected scheme will be used by default to authenticate with the API for all operations that support it. For example:
using Mollie;
using Mollie.Models.Components;
using Mollie.Models.Requests;
var sdk = new Client(
security: new Security() {
ApiKey = "<YOUR_BEARER_TOKEN_HERE>",
},
testmode: false
);
ListBalancesRequest req = new ListBalancesRequest() {
Currency = "EUR",
From = "bal_gVMhHKqSSRYJyPsuoPNFH",
Limit = 50,
IdempotencyKey = "123e4567-e89b-12d3-a456-426",
};
var res = await sdk.Balances.ListAsync(req);
// handle responseThis SDK supports the usage of Idempotency Keys. See our documentation on how to use it.
using Mollie;
using Mollie.Models.Components;
using Mollie.Models.Requests;
using System.Collections.Generic;
var sdk = new Mollie.Client(security: new Security() {
ApiKey = Environment.GetEnvironmentVariable("MOLLIE_API_KEY") ?? "test_...",
});
var paymentRequest = new PaymentRequest() {
Description = "Description",
Amount = new Amount() {
Currency = "EUR",
Value = "5.00",
},
RedirectUrl = "https://example.org/redirect"
};
var idempotencyKey = "<some-idempotency-key>";
var payment1 = await sdk.Payments.CreateAsync(
idempotencyKey: idempotencyKey,
paymentRequest: paymentRequest
);
var payment2 = await sdk.Payments.CreateAsync(
idempotencyKey: idempotencyKey,
paymentRequest: paymentRequest
);
Console.WriteLine("Payment created with ID: " + payment1.PaymentResponse?.Id);
Console.WriteLine("Payment created with ID: " + payment2.PaymentResponse?.Id);
if (payment1.PaymentResponse?.Id == payment2.PaymentResponse?.Id) {
Console.WriteLine("Payments are the same");
} else {
Console.WriteLine("Payments are different");
}The SDK allows you to append a custom suffix to the User-Agent header for all requests. This can be used to identify
your application or integration when interacting with the API, making it easier to track usage or debug requests. The suffix is automatically added to the default User-Agent string generated by the SDK. You can add it when creating the
client:
var sdk = new Mollie.Client(
security: new Security() {
ApiKey = Environment.GetEnvironmentVariable("MOLLIE_API_KEY") ?? "test_...",
},
customUserAgent: "insert something here"
);The SDK allows you to define the profileId and testmode in the client. This way, you don't need to add this
information to the payload every time when using OAuth. This will not override the details provided in the individual
requests.
var sdk = new Mollie.Client(
security: new Security() {
OAuth = Environment.GetEnvironmentVariable("MOLLIE_OAUTH_KEY") ?? "",
},
testmode: true,
profileId: "pfl_..."
);Available methods
- List - List balances
- Get - Get balance
- GetPrimary - Get primary balance
- GetReport - Get balance report
- ListTransactions - List balance transactions
- Create - Create a Connect balance transfer
- List - List all Connect balance transfers
- Get - Get a Connect balance transfer
- List - List capabilities
- Create - Create client link
- Create - Create customer
- List - List customers
- Get - Get customer
- Update - Update customer
- Delete - Delete customer
- CreatePayment - Create customer payment
- ListPayments - List customer payments
- Get - Get organization
- GetCurrent - Get current organization
- GetPartner - Get partner status
- Create - Create payment link
- List - List payment links
- Get - Get payment link
- Update - Update payment link
- Delete - Delete payment link
- ListPayments - Get payment link payments
- Create - Create payment
- List - List payments
- Get - Get payment
- Update - Update payment
- Cancel - Cancel payment
- ReleaseAuthorization - Release payment authorization
- Create - Create profile
- List - List profiles
- Get - Get profile
- Update - Update profile
- Delete - Delete profile
- GetCurrent - Get current profile
- Create - Create payment refund
- List - List payment refunds
- Get - Get payment refund
- Cancel - Cancel payment refund
- All - List all refunds
- Create - Create sales invoice
- List - List sales invoices
- Get - Get sales invoice
- Update - Update sales invoice
- Delete - Delete sales invoice
- List - List settlements
- Get - Get settlement
- GetOpen - Get open settlement
- GetNext - Get next settlement
- ListPayments - List settlement payments
- ListCaptures - List settlement captures
- ListRefunds - List settlement refunds
- ListChargebacks - List settlement chargebacks
- Create - Create subscription
- List - List customer subscriptions
- Get - Get subscription
- Update - Update subscription
- Cancel - Cancel subscription
- All - List all subscriptions
- ListPayments - List subscription payments
- RequestApplePaySession - Request Apple Pay payment session
- Get - Get a Webhook Event
Certain parameters are configured globally. These parameters may be set on the SDK client instance itself during initialization. When configured as an option during SDK initialization, These global values will be used as defaults on the operations that use them. When such operations are called, there is a place in each to override the global value, if needed.
For example, you can set profileId to `` at SDK initialization and then you do not have to pass the same value on calls to operations like List. But if you want to do so you may, which will locally override the global setting. See the example code below for a demonstration.
The following global parameters are available.
| Name | Type | Description |
|---|---|---|
| profileId | string | The identifier referring to the profile you wish to retrieve the resources for. Most API credentials are linked to a single profile. In these cases the profileId can be omitted. Fororganization-level credentials such as OAuth access tokens however, the profileId parameter is required. |
| testmode | bool | Most API credentials are specifically created for either live mode or test mode. In those cases the testmode queryparameter can be omitted. For organization-level credentials such as OAuth access tokens, you can enable test mode by setting the testmode query parameter to true.Test entities cannot be retrieved when the endpoint is set to live mode, and vice versa. |
| customUserAgent | string | Custom user agent string to be appended to the default Mollie SDK user agent. |
using Mollie;
using Mollie.Models.Components;
using Mollie.Models.Requests;
var sdk = new Client(
testmode: false,
profileId: "<id>",
customUserAgent: "<value>",
security: new Security() {
ApiKey = "<YOUR_BEARER_TOKEN_HERE>",
}
);
ListBalancesRequest req = new ListBalancesRequest() {
Currency = "EUR",
From = "bal_gVMhHKqSSRYJyPsuoPNFH",
Limit = 50,
IdempotencyKey = "123e4567-e89b-12d3-a456-426",
};
var res = await sdk.Balances.ListAsync(req);
// handle responseSome of the endpoints in this SDK support retries. If you use the SDK without any configuration, it will fall back to the default retry strategy provided by the API. However, the default retry strategy can be overridden on a per-operation basis, or across the entire SDK.
To change the default retry strategy for a single API call, simply pass a RetryConfig to the call:
using Mollie;
using Mollie.Models.Components;
using Mollie.Models.Requests;
var sdk = new Client(
testmode: false,
security: new Security() {
ApiKey = "<YOUR_BEARER_TOKEN_HERE>",
}
);
ListBalancesRequest req = new ListBalancesRequest() {
Currency = "EUR",
From = "bal_gVMhHKqSSRYJyPsuoPNFH",
Limit = 50,
IdempotencyKey = "123e4567-e89b-12d3-a456-426",
};
var res = await sdk.Balances.ListAsync(
retryConfig: new RetryConfig(
strategy: RetryConfig.RetryStrategy.BACKOFF,
backoff: new BackoffStrategy(
initialIntervalMs: 1L,
maxIntervalMs: 50L,
maxElapsedTimeMs: 100L,
exponent: 1.1
),
retryConnectionErrors: false
),
request: req
);
// handle responseIf you'd like to override the default retry strategy for all operations that support retries, you can use the RetryConfig optional parameter when intitializing the SDK:
using Mollie;
using Mollie.Models.Components;
using Mollie.Models.Requests;
var sdk = new Client(
retryConfig: new RetryConfig(
strategy: RetryConfig.RetryStrategy.BACKOFF,
backoff: new BackoffStrategy(
initialIntervalMs: 1L,
maxIntervalMs: 50L,
maxElapsedTimeMs: 100L,
exponent: 1.1
),
retryConnectionErrors: false
),
testmode: false,
security: new Security() {
ApiKey = "<YOUR_BEARER_TOKEN_HERE>",
}
);
ListBalancesRequest req = new ListBalancesRequest() {
Currency = "EUR",
From = "bal_gVMhHKqSSRYJyPsuoPNFH",
Limit = 50,
IdempotencyKey = "123e4567-e89b-12d3-a456-426",
};
var res = await sdk.Balances.ListAsync(req);
// handle responseBaseException is the base exception class for all HTTP error responses. It has the following properties:
| Property | Type | Description |
|---|---|---|
Message |
string | Error message |
Request |
HttpRequestMessage | HTTP request object |
Response |
HttpResponseMessage | HTTP response object |
Some exceptions in this SDK include an additional Payload field, which will contain deserialized custom error data when present. Possible exceptions are listed in the Error Classes section.
using Mollie;
using Mollie.Models.Components;
using Mollie.Models.Errors;
using Mollie.Models.Requests;
var sdk = new Client(
testmode: false,
security: new Security() {
ApiKey = "<YOUR_BEARER_TOKEN_HERE>",
}
);
try
{
ListBalancesRequest req = new ListBalancesRequest() {
Currency = "EUR",
From = "bal_gVMhHKqSSRYJyPsuoPNFH",
Limit = 50,
IdempotencyKey = "123e4567-e89b-12d3-a456-426",
};
var res = await sdk.Balances.ListAsync(req);
// handle response
}
catch (BaseException ex) // all SDK exceptions inherit from BaseException
{
// ex.ToString() provides a detailed error message
System.Console.WriteLine(ex);
// Base exception fields
HttpRequestMessage request = ex.Request;
HttpResponseMessage response = ex.Response;
var statusCode = (int)response.StatusCode;
var responseBody = ex.Body;
if (ex is ErrorResponse) // different exceptions may be thrown depending on the method
{
// Check error data fields
ErrorResponsePayload payload = ex.Payload;
long Status = payload.Status;
string Title = payload.Title;
// ...
}
// An underlying cause may be provided
if (ex.InnerException != null)
{
Exception cause = ex.InnerException;
}
}
catch (OperationCanceledException ex)
{
// CancellationToken was cancelled
}
catch (System.Net.Http.HttpRequestException ex)
{
// Check ex.InnerException for Network connectivity errors
}Primary exceptions:
BaseException: The base class for HTTP error responses.ErrorResponse: An error response object. *
Less common exceptions (2)
-
System.Net.Http.HttpRequestException: Network connectivity error. For more details about the underlying cause, inspect theex.InnerException. -
Inheriting from
BaseException:ResponseValidationError: Thrown when the response data could not be deserialized into the expected type.
* Refer to the relevant documentation to determine whether an exception applies to a specific operation.
The default server can be overridden globally by passing a URL to the serverUrl: string optional parameter when initializing the SDK client instance. For example:
using Mollie;
using Mollie.Models.Components;
using Mollie.Models.Requests;
var sdk = new Client(
serverUrl: "https://api.mollie.com/v2",
testmode: false,
security: new Security() {
ApiKey = "<YOUR_BEARER_TOKEN_HERE>",
}
);
ListBalancesRequest req = new ListBalancesRequest() {
Currency = "EUR",
From = "bal_gVMhHKqSSRYJyPsuoPNFH",
Limit = 50,
IdempotencyKey = "123e4567-e89b-12d3-a456-426",
};
var res = await sdk.Balances.ListAsync(req);
// handle responseThe C# SDK makes API calls using an ISpeakeasyHttpClient that wraps the native
HttpClient. This
client provides the ability to attach hooks around the request lifecycle that can be used to modify the request or handle
errors and response.
The ISpeakeasyHttpClient interface allows you to either use the default SpeakeasyHttpClient that comes with the SDK,
or provide your own custom implementation with customized configuration such as custom message handlers, timeouts,
connection pooling, and other HTTP client settings.
The following example shows how to create a custom HTTP client with request modification and error handling:
using Mollie;
using Mollie.Utils;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
// Create a custom HTTP client
public class CustomHttpClient : ISpeakeasyHttpClient
{
private readonly ISpeakeasyHttpClient _defaultClient;
public CustomHttpClient()
{
_defaultClient = new SpeakeasyHttpClient();
}
public async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken? cancellationToken = null)
{
// Add custom header and timeout
request.Headers.Add("x-custom-header", "custom value");
request.Headers.Add("x-request-timeout", "30");
try
{
var response = await _defaultClient.SendAsync(request, cancellationToken);
// Log successful response
Console.WriteLine($"Request successful: {response.StatusCode}");
return response;
}
catch (Exception error)
{
// Log error
Console.WriteLine($"Request failed: {error.Message}");
throw;
}
}
public void Dispose()
{
_httpClient?.Dispose();
_defaultClient?.Dispose();
}
}
// Use the custom HTTP client with the SDK
var customHttpClient = new CustomHttpClient();
var sdk = new Client(client: customHttpClient);You can also provide a completely custom HTTP client with your own configuration:
using Mollie.Utils;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
// Custom HTTP client with custom configuration
public class AdvancedHttpClient : ISpeakeasyHttpClient
{
private readonly HttpClient _httpClient;
public AdvancedHttpClient()
{
var handler = new HttpClientHandler()
{
MaxConnectionsPerServer = 10,
// ServerCertificateCustomValidationCallback = customCertValidation, // Custom SSL validation if needed
};
_httpClient = new HttpClient(handler)
{
Timeout = TimeSpan.FromSeconds(30)
};
}
public async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken? cancellationToken = null)
{
return await _httpClient.SendAsync(request, cancellationToken ?? CancellationToken.None);
}
public void Dispose()
{
_httpClient?.Dispose();
}
}
var sdk = Client.Builder()
.WithClient(new AdvancedHttpClient())
.Build();For simple debugging, you can enable request/response logging by implementing a custom client:
public class LoggingHttpClient : ISpeakeasyHttpClient
{
private readonly ISpeakeasyHttpClient _innerClient;
public LoggingHttpClient(ISpeakeasyHttpClient innerClient = null)
{
_innerClient = innerClient ?? new SpeakeasyHttpClient();
}
public async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken? cancellationToken = null)
{
// Log request
Console.WriteLine($"Sending {request.Method} request to {request.RequestUri}");
var response = await _innerClient.SendAsync(request, cancellationToken);
// Log response
Console.WriteLine($"Received {response.StatusCode} response");
return response;
}
public void Dispose() => _innerClient?.Dispose();
}
var sdk = new Client(client: new LoggingHttpClient());The SDK also provides built-in hook support through the SDKConfiguration.Hooks system, which automatically handles
BeforeRequestAsync, AfterSuccessAsync, and AfterErrorAsync hooks for advanced request lifecycle management.
This SDK is in beta, and there may be breaking changes between versions without a major version update. Therefore, we recommend pinning usage to a specific package version. This way, you can install the same version each time without breaking changes unless you are intentionally looking for the latest version.
While we value open-source contributions to this SDK, this library is generated programmatically. Any manual changes added to internal files will be overwritten on the next generation. We look forward to hearing your feedback. Feel free to open a PR or an issue with a proof of concept and we'll do our best to include it in a future release.