Skip to Content
Docs

.NET

Call the Pay.com API from C# with typed async methods, automatic paging, and webhook verification.

The .NET SDK has a typed async method for each API operation, named after its resource: pay.Charges.CreateAsync(), pay.Holds.CaptureAsync(), and pay.ValueLists.Items.CreateAsync(). Properties are PascalCase, and keep the API's own names for JSON.

Requirements and install

You need .NET 8 or later. The SDK needs nothing but the framework.

Terminal

dotnet add package PayCom

Everything is in the PayCom namespace. A client is safe to share between threads.

Set your key

Keep the key out of your code. The SDK reads it from PAY_COM_API_KEY:

Terminal

export PAY_COM_API_KEY='sk-pay-com-sandbox-…'

The SDK selects the sandbox or live environment automatically from the key prefix (sk-pay-com-sandbox- or sk-pay-com-live-). The key is never written to the SDK's logs or exceptions.

Create your first charge

Charge a saved payment method. Amounts are integers in minor units (for example, 2000 is $20.00 USD):

Program.cs

using PayCom;

var pay = new Pay();

var charge = await pay.Charges.CreateAsync(new ChargesCreateParams
{
    Amount = 2000,
    Currency = "usd",
    Source = "pm_card_685125127054035968",
    Reference = "order-6735",
});

Console.WriteLine($"{charge?.Id} {charge?.Status}");

A property you never set isn't sent. Every property of a response is nullable, since the API can leave a field out.

The SDK sends a new idempotency key with each POST and DELETE, and the same one when it retries. To use your own, pass it after the parameters: pay.Charges.CreateAsync(parameters, new RequestOptions { IdempotencyKey = key }).

It retries twice by default after a network error, a timeout, 409 request_in_progress, 421, 429, 502, 503, or 504. To decide yourself, set MaxRetries = 0, and set a Reference on payments to help you find out what was created.

The SDK retries these only after a 429, or when they never left your server: every PUT and PATCH, WebhookEndpoints.CreateAsync(), and NetworkTokens.RetrieveCryptogramAsync(). If one of these requests receives no response, check whether it succeeded before sending it again.

When you call PaymentLinks.UpdateAsync(), pass every field you want to keep, Amount and Currency included. An update without amount sets the link's amount to 0.

List every item

ListAsync returns one page. ListAutoPagingAsync goes through every item on every page, and fetches each page as you reach it:

Program.cs

using PayCom;

var pay = new Pay();

var page = await pay.Charges.ListAsync(new ChargesListParams { Limit = 10 });
Console.WriteLine($"{page?.Data?.Count} {page?.HasMore}");

await foreach (var charge in pay.Charges.ListAutoPagingAsync(new ChargesListParams { CreatedGreaterThan = DateTimeOffset.Parse("2026-11-01T00:00:00Z") }))
{
    Console.WriteLine(charge.Id);
}

Break out of the loop to stop. Lists that use page numbers work the same way.

Catch a decline

A decline throws PaymentMethodException:

Program.cs

using PayCom;

var pay = new Pay();

try
{
    await pay.Charges.CreateAsync(new ChargesCreateParams
    {
        Amount = 2000,
        Currency = "usd",
        Source = "pm_card_685125127054035968",
    });
}
catch (PaymentMethodException e)
{
    Console.WriteLine($"Declined: {e.DeclineCode}");
}
catch (InvalidRequestException e)
{
    Console.WriteLine($"Fix the request: {e.Code} {e.Message}");
}

Every exception the SDK throws is a PayException, with Type, Code, StatusCode, and the API's body as Body. Include RequestId when contacting Pay.com support. It is empty when the API didn't get or couldn't read the request. After retries, InnerException holds an earlier attempt's error. The exception's class tells you what happened:

Error classCause
PaymentMethodExceptionPayment declined by the issuer or blocked by a risk rule (400)
InvalidRequestException400 or 422. NotFoundException, for 404, is one too
AuthenticationException401
PermissionException403
IdempotencyExceptionAn idempotency key in use, or used for another request
ConflictExceptionAny other 409
RateLimitException429
ApiException5xx, a redirect (none is followed), or a response the SDK didn't expect
ApiConnectionExceptionNo complete response. ApiTimeoutException is one too

When you cancel, the method throws OperationCanceledException, as .NET methods do. See Handle errors for what to do with each.

Verify a webhook

Pass the raw body, the Pay-Signature header, and the endpoint's whole signing secret. Cap the body, since anyone can send to your URL. Return HTTP 400 only when SignatureVerificationException is thrown. Let other errors return 500 so Pay.com retries delivery:

Program.cs

using PayCom;

var builder = WebApplication.CreateBuilder(args);
builder.WebHost.ConfigureKestrel(options => options.Limits.MaxRequestBodySize = 5 * 1024 * 1024);
var app = builder.Build();
var webhooks = new Webhooks();

app.MapPost("/webhooks", async (HttpRequest request) =>
{
    using var reader = new StreamReader(request.Body);
    var body = await reader.ReadToEndAsync();
    PayEvent payEvent;
    try
    {
        payEvent = webhooks.ConstructEvent(body, request.Headers["Pay-Signature"], Environment.GetEnvironmentVariable("PAY_COM_WEBHOOK_SECRET")!);
    }
    catch (SignatureVerificationException)
    {
        return Results.BadRequest("Invalid signature");
    }
    if (payEvent is ChargeSucceededEvent succeeded)
    {
        Console.WriteLine($"Paid: {succeeded.Data?.Id}");
    }
    return Results.Ok();
});

app.Run();

Skip events whose Id you've already handled.

Each event type has a class, such as ChargeSucceededEvent, whose Data is typed. In your tests, pay.Webhooks.GenerateTestHeader(payload, secret) makes a valid header.

Options

Set these on a PayOptions, and pass it to new Pay().

ApiKeystring
The secret key.

Default: PAY_COM_API_KEY

EnvironmentPayEnvironment
PayEnvironment.Sandbox or PayEnvironment.Live, for a key without either prefix.
MerchantIdstring
Target merchant ID for multi-workspace API keys.
TimeoutTimeSpan
How long each attempt can take, reading the response included.

Default: 60 seconds

MaxRetriesint
Maximum number of automatic retry attempts.

Default: 2

BaseUrlstring
Custom API base URL for local mocks or proxies.
DefaultHeadersIDictionary<string, string>
Headers sent with every request.
HttpClientHttpClient
Your own client, for a proxy or a handler. Build it on PayHttpHandler.Create(), with an infinite Timeout.
LogLevelPayLogLevel
Log verbosity level, written to Logger or standard error. Also read from PAY_COM_LOG.

Default: Warn

RequestOptions sets IdempotencyKey, MerchantId, Timeout, MaxRetries, and Headers for one request. Every method also takes a CancellationToken, last. The sandbox's simulate endpoints are under pay.TestHelpers. pay.Documents.UploadAsync() takes an Upload with the file and its content type. See Upload and download files.

Was this page helpful?