Skip to content

Upgrading to 2.0

This page collects what has to be done in application code when moving from 1.x to 2.0. New capabilities are described on the pages of the individual libraries; here are only the changes after which code no longer compiles or behaves differently.

Requirements

The 2.0 libraries are released for net10.0 and net11.0. Applications on older platforms stay on the 1.6.x packages (security fixes). Details: Target frameworks.


Checklist

# Library What to do If skipped
1 Payments Catch HttpRequestException around RegisterPayment and GetStatus A failing gateway ends the request with a 500
2 Payments Set PaymentProvider, Amount and Currency on every PaymentRequest Compile error CS9035
3 Payments (Tpay, Adyen) Pass the raw webhook body, answer with the text the gateway expects, send your own order number Notifications are rejected or repeated; a webhook cannot be matched with an order
4 Payments Handle the webhook result as one of three records - (the old properties still work)
5 MediatR Remove the ICache registration, clear the shared cache Compile error; entries in the old format are read
6 DateTime Nothing - optionally AddDateTimeProvider() and OffsetUtcNow -

Payments

1. A failing gateway is an exception, not the Rejected status

In 1.x a gateway that answered 5xx, or refused a status query, was reported as PaymentStatusEnum.Rejected. An application acting on that status cancelled an order whose payment may have succeeded.

In 2.0 Rejected means only what the gateway said. When the gateway gives no usable answer, the call throws PaymentGatewayException (derives from HttpRequestException) - the state of the payment is then not known.

// 1.x
var payment = await _payments.GetStatus("Tpay", paymentId);
if (payment.PaymentStatus == PaymentStatusEnum.Rejected)
    await _orders.CancelAsync(orderId);          // also when the gateway was failing!

// 2.0
try
{
    var payment = await _payments.GetStatus("Tpay", paymentId, cancellationToken);
    if (payment.PaymentStatus == PaymentStatusEnum.Rejected)
        await _orders.CancelAsync(orderId, cancellationToken);   // the gateway answered: declined
}
catch (HttpRequestException exception)   // covers PaymentGatewayException
{
    // The state of the payment is not known: leave the order as it is and check again later.
    _logger.LogWarning(exception, "Gateway unavailable for payment {PaymentId}", paymentId);
}

The same applies to RegisterPayment: a 5xx, 408 or 429 while creating a payment throws, because the payment may or may not have been created. A 4xx answer is still Rejected with the gateway's error text in ResponseObject.

  • PaymentGatewayException has Provider, StatusCode, IsTransient (whether a retry makes sense) and ResponseBody.
  • A timeout surfaces as TaskCanceledException.
  • Stripe reports failures as StripeException, as in 1.x (from 3.0 PaymentGatewayException too - see Upgrading to 3.0). CashBill still throws WebException in 2.0.0 and 2.0.1; from the next version PaymentGatewayException.

The full table of cases: Payments - A failing gateway is not a refusal.

2. PaymentRequest requires a provider, an amount and a currency

PaymentProvider, Amount and Currency are required members. An initializer that leaves one out does not compile (CS9035), and System.Text.Json refuses a document without them - an endpoint that takes a PaymentRequest from the body answers 400.

// 1.x - compiled, the error surfaced only at the gateway
var request = new PaymentRequest { Title = "Order 7", Amount = 49.99m };

// 2.0
var request = new PaymentRequest
{
    PaymentProvider = "Tpay",
    Amount = 49.99m,
    Currency = "PLN",
    Title = "Order 7",
};

// or shorter
var request = new PaymentRequest("Tpay", 49.99m, "PLN") { Title = "Order 7" };

RegisterPayment also refuses a blank provider key or currency (ArgumentException) and an amount of zero or less (ArgumentOutOfRangeException) before it calls the gateway.

3. Tpay and Adyen webhooks

In 1.x the verification of both gateways' notifications did not match their protocols and rejected genuine notifications. In 2.0 it works, but needs three things from the application.

a) Pass the raw body. The signature covers the exact bytes of the request. Read the body from the stream - not through [FromForm], [FromBody] or a re-serialization.

b) Answer with the text the gateway expects. It is in PaymentResponse.ResponseObject of the result and in the constants TpayProvider.Acknowledgement (TRUE) and AdyenProvider.Acknowledgement ([accepted]). Any other answer makes the gateway repeat the notification.

c) Send your own order number in PaymentRequest.AdditionalData. Tpay and Adyen notifications do not carry the identifier returned by RegisterPayment. PaymentUniqueId of the webhook result is the value from AdditionalData (Tpay: tr_crc, Adyen: merchantReference); without it you get only the gateway's reference, which the application does not know.

[HttpPost("webhooks/tpay")]
public async Task<IActionResult> TpayWebhook(CancellationToken cancellationToken)
{
    using var reader = new StreamReader(Request.Body, Encoding.UTF8);
    var body = await reader.ReadToEndAsync(cancellationToken);                 // a) the raw body

    var result = await _payments.HandleWebhookAsync("Tpay", new PaymentWebhookRequest
    {
        Body = body,
        ContentType = Request.ContentType,
        Headers = Request.Headers.ToDictionary(h => h.Key, h => h.Value),
    }, cancellationToken);

    if (result is PaymentWebhookProcessed processed)
        await _orders.ApplyPaymentAsync(processed.Payment.PaymentUniqueId, processed.Payment.PaymentStatus, cancellationToken);   // c) the order number

    return result is PaymentWebhookRejected
        ? BadRequest("FALSE")
        : Content(TpayProvider.Acknowledgement, "text/plain");                 // b) "TRUE"
}

In addition:

  • Tpay: the signature header is X-JWS-Signature (not X-Signature); in the sandbox set JwsCertificateBaseUrl to https://secure.sandbox.tpay.com. Your own ITpayServiceCaller implementation needs VerifyNotificationAsync instead of VerifyNotification.
  • Adyen: the signature is in additionalData.hmacSignature of the notification item, not in a header. Enable HMAC signing of the webhook in the Adyen Customer Area and copy the key into NotificationHmacKey.

Details and status tables: Tpay, Adyen.

4. Other changes in Payments

  • The webhook result is one of three records: PaymentWebhookProcessed, PaymentWebhookIgnored, PaymentWebhookRejected (with the reason in Rejection). The former Success, Ignored and ErrorMessage still work.
  • CancellationToken is an optional parameter of every asynchronous method. Calls need no change; your own provider (IPaymentProvider, I*ServiceCaller) has to add the parameter to the methods it implements.
  • Configuration is validated at startup: Register*Provider() stops the host (OptionsValidationException) when credentials or the webhook secret are missing. Register only the providers you have configured.

Described on: Payments.


MediatR

CachingBehavior uses HybridCache. The ICache interface and the Cache class are removed together with the Newtonsoft.Json dependency:

  • delete your own ICache registration,
  • ICachePolicy.SlidingExpiration is no longer supported,
  • after upgrading, clear the shared cache or change the key prefix - entries written by 1.x have a different format.

Retries and the circuit breaker no longer use Polly. Described on: Mediator (named MediatR in 2.x).


DateTime

Code that uses IDateTimeProvider needs no change; your own implementations of the interface and existing mocks compile as before.

  • DateTimeProvider reads its time from System.TimeProvider, so an application has one clock.
  • New: OffsetUtcNow and OffsetNow (DateTimeOffset) and the registration builder.Services.AddDateTimeProvider().
  • UtcTimeOfDaty (a typo) is obsolete - use UtcTimeOfDay (removed in 3.0).
  • Behaviour change: Now and Today report the time zone of the TimeProvider in use (no difference for the system clock).

Described on: DateTime.


Other libraries

  • All: the public API carries nullable annotations - a project with <Nullable>enable</Nullable> may see new warnings (Target frameworks).
  • EntityFramework: PagingAsync works for non-empty pages (in 1.x it threw InvalidOperationException).
  • WebApi: the default HTTP client resilience does not retry requests that change state (WebApi).

🤖 AI Agent Prompt

## Upgrading TailoredApps.Shared.* from 1.x to 2.0 - instructions for an AI agent

You are upgrading a .NET 10 or .NET 11 application from the TailoredApps.Shared.* 1.x packages to 2.0. Do the following in order:

### Registration
- Raise every TailoredApps.Shared.* package to the same 2.x version
- Remove the ICache registration (MediatR); optionally add builder.Services.AddDateTimeProvider()

### What needs code changes
- Payments: wrap every IPaymentService.RegisterPayment and GetStatus call in try/catch (HttpRequestException) - a failing gateway is an unknown state, not a refusal
- Payments: every new PaymentRequest must set PaymentProvider, Amount (> 0) and Currency
- Payments: webhook endpoints pass the raw body from the request stream and every header
- Tpay: HTTP 200 with the body "TRUE" (TpayProvider.Acknowledgement); Adyen: "[accepted]" (AdyenProvider.Acknowledgement)
- Tpay and Adyen: set PaymentRequest.AdditionalData to the order number; in the webhook match the order by PaymentUniqueId
- Your own IPaymentProvider / I*ServiceCaller implementations: add the parameter CancellationToken cancellationToken = default

### Configuration
- Tpay sandbox: Payments:Providers:Tpay:JwsCertificateBaseUrl = "https://secure.sandbox.tpay.com"
- Adyen: Payments:Providers:Adyen:NotificationHmacKey = the webhook HMAC key (hex) from the Adyen Customer Area
- Every registered provider needs its full credentials and webhook secret, otherwise the host does not start

### Rules
- Do not cancel an order after an exception from RegisterPayment / GetStatus; Rejected is reliable only when the call returned a result
- Do not read a webhook body through [FromForm] or [FromBody] - the signature covers the raw bytes
- Do not replace signature verification with a stub that returns true
- After upgrading MediatR clear the shared cache or change the key prefix
- Applications on net8.0 / net9.0 / netstandard stay on 1.6.x - do not raise them to 2.0