Viincenttt / MollieApi

This project allows you to easily add the Mollie payment provider to your application.
MIT License
144 stars 83 forks source link

How to set your own idempotency key? #347

Closed JSCProjects closed 3 months ago

JSCProjects commented 3 months ago

I have a own unique guid which I want to use for the Idempotency-Key. I create payments from a message queue and these already have a unique id and I use the resilience of the queue. We get duplicate payments when a message is retried which was in a deadletter. Is it possible to extend this library to use this own provided identifier when provided?

Thanx in advance.

Regards,

Joey Chömpff

Viincenttt commented 3 months ago

Hi,

Currently this is not possible, but I definitely like the idea of being able to configure the idempotency key. However, I don't want to add an optional idempotency key to all the API methods, so I'm not yet sure about what the best way would be to implement this. I'll have to think about it for a bit.

If you have any suggestions on how to implement it, feel free to make a suggestion.

Kind regards, Vincent

JSCProjects commented 3 months ago

I have a solution perhaps will send tomorrow a setup how I fixed it with a fork. I only want those with payments and refunds


Van: Vincent Kok @.> Verzonden: Wednesday, March 27, 2024 6:21:33 PM Aan: Viincenttt/MollieApi @.> CC: JSC Projects @.>; Author @.> Onderwerp: Re: [Viincenttt/MollieApi] How to set your own idempotency key? (Issue #347)

Hi,

Currently this is not possible, but I definitely like the idea of being able to configure the idempotency key. However, I don't want to add an optional idempotency key to all the API methods, so I'm not yet sure about what the best way would be to implement this. I'll have to think about it for a bit.

If you have any suggestions on how to implement it, feel free to make a suggestion.

Kind regards, Vincent

— Reply to this email directly, view it on GitHubhttps://github.com/Viincenttt/MollieApi/issues/347#issuecomment-2023358427, or unsubscribehttps://github.com/notifications/unsubscribe-auth/AEVA2XJYUFOAINQNRBXNFUTY2LWY3AVCNFSM6AAAAABFKVTKZ6VHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDAMRTGM2TQNBSG4. You are receiving this because you authored the thread.Message ID: @.***>

Viincenttt commented 3 months ago

One idea that I currently have is to be able to specify a custom idempotency key inside a using block. This would work very similar to the structure that logger.BeginScope uses. For example:

using IPaymentClient paymentClient = new PaymentClient("api-key");
using (paymentClient.WithIdempotencyKey("my-custom-key"))
{
    PaymentRequest paymentRequest = new PaymentRequest() {
        Amount = new Amount(Currency.EUR, "100.00"),
        Description = "description",
        RedirectUrl = "url"
    };

     await paymentClient.CreatePaymentAsync(paymentRequest);
}

All requests within the using scope will use the custom idempotency key that you set.

Let me know what you think :)

JSCProjects commented 3 months ago

If you are using dependency injection then the first line will not work. I'm wondering how you would implement the second line. IMHO this looks better then what I've thought out. Is it possible to implement this also in v2? Because v3 gives us problems because it's depending on new v7 packages from Microsoft and that doesn't work in all .NET 6 hosts.

Thanx in advance

Viincenttt commented 3 months ago

The first line is purely for demonstration. The payment client can be instantiated through dependency injection or by simply creating a new object like I did in this example.

The implementation of the second line is going to be interesting indeed. I think it should be possible to store the custom idempotency key in a AsyncLocal variable. This ensures that the value is stored in a thread-safe matter and contexts between different threads will never overlap. The variable needs to be reset when the using block ends, so it should be contained inside a class that implements the IDisposable interface.

It sounds more complicated then it is, I think something like this should do the trick (untested):

public class AsyncLocalVariable<T> : IDisposable
{
    private readonly AsyncLocal<T> _asyncLocal = new AsyncLocal<T>();

    public AsyncLocalVariable(T value)
    {
        _asyncLocal.Value = value;
    }

    public void Set(T value)
    {
        _asyncLocal.Value = value;
    }

    publid T Get() 
    {
         return _asyncLocal.Value;
    }

    public void Dispose()
    {
        _asyncLocal.Value = null;
    }
}

// In BaseMollieClient.cs
private readonly AsyncLocalVariable<string> _idempotencyKey = new AsyncLocalVariable<string>(null);
public IDisposable WithIdempotencyKey(string value) {
    _idempotencyKey.Set(value);
    return _idempotencyKey;
}

protected virtual HttpRequestMessage CreateHttpRequest(HttpMethod method, string relativeUri, HttpContent? content = null) 
{
    ...
    var idemPotencyKey = _idempotencyKey.Get() ?? Guid.NewGuid().ToString();
    httpRequest.Headers.Add("Idempotency-Key", idemPotencyKey);
    ....
}

I'll play around with this idea next weekend.

I'm also interested in hearing the issues you have with v3 of the library. Can you tell me to what platform you are publishing and what errors you are getting? Perhaps there is something I can do in the library side to fix this.

Viincenttt commented 3 months ago

Hi @JSCProjects ,

I have added the feature to the development branch and plan to release a new version on NuGet later this weekend. Example code on how to use the feature can be seen in the integration test linked below. I have also downgraded the Microsoft dependencies to version 6, so hopefully you'll be able to upgrade to v3 of the Mollie library.

I'll update the issue when the new version has been released.

https://github.com/Viincenttt/MollieApi/pull/352/files#diff-07edb06086f59977e3efd91607ee0a9b93f135e9036de12bbd33073d1b5de448

// Given: we create a payment request with only the required parameters
PaymentRequest paymentRequest = new PaymentRequest() {
    Amount = new Amount(Currency.EUR, "100.00"),
    Description = "Description",
    RedirectUrl = DefaultRedirectUrl
};

// When: We send the payment request to Mollie
using (_paymentClient.WithIdempotencyKey("my-idempotency-key"))
{
    PaymentResponse firstAttempt = await _paymentClient.CreatePaymentAsync(paymentRequest);
    PaymentResponse secondAttempt = await _paymentClient.CreatePaymentAsync(paymentRequest);

    // Then: Make sure the responses have the same payment Id
    firstAttempt.Id.Should().Be(secondAttempt.Id);
}
Viincenttt commented 3 months ago

This is now live in version 3.6.0 of the library. Keep in mind I downgraded the Microsoft dependencies from version 7 to version 6. Please let me know if this solved the issues you had with .NET6 hosts.

JSCProjects commented 3 months ago

Hi @Viincenttt good work. I will test it ASAP.

JSCProjects commented 3 months ago

Hi @Viincenttt I've tested all my hosts and all are starting and accepting payments.

Viincenttt commented 3 months ago

Good to hear that all is working 👍